Search code examples
phpajaxarray-push

How to insert element in a PHP array one by one using AJAX?


I want add the elements in array one by one from php file that i have set as ajax url. i that file the id is changed each time and i want to add these all id in one array.

here is my JS code:

$("body").on("click",".ins-img", function() {       
 var hid = $(this).attr("hid");
 var iname = $(this).attr("iname");
 var datastring = 'hid='+hid+'&iname='+iname;
 alert(datastring);
  $.ajax({
    type:"POST",
    url:"inspire-show.php",
    data:datastring,
    success: function(response) {
    $("#rand").html(response);
    }
  });
});

here is PHP code:inspire-show.php

<?php include("connection.php");
$hid = $_POST['hid'];
$iname = $_POST['iname'];
$result = mysql_query("select holiday_type, holiday_id,holiday_img from cat_holidays     ORDER BY RAND() LIMIT 2");
$msg ='';
while($row = mysql_fetch_array($result)) {
$msg .='<div class="ins-wrap"><img  class="ins-img" hid='.$row['holiday_id'].'    iname="'.$row['holiday_type'].'" src="holiday-type/'.$row["holiday_img"].'"></div>';
}
$arr = array();
array_push($arr, $hid);
print_r($arr);

echo $msg;

?>

Solution

  • Every time you do an AJAX call, a new independent script is launched server side.

    It means that it has no memory of the previous calls and of the previous array entries (It creates a new one, basically).

    You could maybe achieve that by storing values in a JSON (or whatever) file that you change every time, or directly store the values in database.