1

I have a checkbox and the user checks it in, an AJAX call should be sent to a PHP file which returns an object. I have a SQL statement which returns data and the AJAX should get it from the PHP.

For instance the SQL returns 2 rows:

$sql = "SELECT * FROM table WHERE 1";
    if ($result = mysqli_query($con, $sql)) { $num = mysqli_num_rows($result); $arr = array();
        if ($num > 0) { $object = new stdClass();
            while ($bsi = $result-> fetch_assoc()) { 
                $object->id = $bsi['id']; $object->name = $bsi['name'];
                array_push($arr, $object);
            } die(json_encode($arr)); 
        }
    }

// Create an array, create an object. save fetched data into an object, then add the object into an array.

Let's say the above statement returns the 2 rows: [0: {id: 1, name: "name1"}, 1: {id: 2, name: "name2"} ]

AND THE AJAX CALL

$.ajax({
  enctype: "multipart/form-data", type: "POST", url: "path", dataType: 'json', contentType: false, processData: false,
  success: function(data) { console.log(data); }

BUT the console.log will display this: [0: {id: 1, name: "name1"}, 1: {id: 1, name: "name1"} ] It always shows the first element of the array.

mkiuygfd
  • 45
  • 6
  • You're pushing multiple copies of the same object into the array. You need to create a new one in each iteration i.e. move `$object = new stdClass();` into the `while ($bsi = $result-> fetch_assoc()) {` loop – Nick May 26 '22 at 08:19

0 Answers0