0

I want to pass through an array of "Blocks" with Ajax. I created "Blocks" with a PHP class: I know how to pass an array with numbers, with JSON, but I dont know how to pass an array with objects.

Will I have to recreate a class in Javascript that mimiks the "Blocks" class and then pass every value through?

class RequirementsEntity {
public $num;
public $name;

function __construct($num, $field, $name, $desc, $bool) {
    $this->num = $num;
    $this->name = $name;

My code for PHP:

$result = [];
while ($row = mysql_fetch_array($query)) {
    $num = $row[0];
    $name = $row[1];

    $ablock = new BlockEntity($num, $name);
    array_push($result, $arequirement);
}
echo json_encode($result);

My code for jQuery:

$('#selProgram').on('change', function() {
  var id = this.value;
  if (id != "None") {
    $.ajax({
      type: "POST",
      url: "assets/php/fetch_req.php", 
      data: "id="+id,
      datatype: "json"
      success: function(data) {
        alert(data);
        GenerateRequirements(data, 1);
        }
      });
    }
  });
  • just pass the values to the `RequirementsEntity` class – tttony Sep 03 '14 at 00:16
  • this post might be helpful, it explains ways to encode/decode in both PHP and JavaScript - http://stackoverflow.com/questions/8823925/how-to-return-an-array-from-an-ajax-call – Raf Sep 03 '14 at 00:18

2 Answers2

0

From the php.net docs

The JSON standard only supports these values when they are nested inside an array or an object.

json_encode turns the variables from an object into JSON variables, so if you save the name and number in the BlockEntity object they would show up.

Coded Monkey
  • 604
  • 7
  • 19
  • thanks! they show up now, but it shows up as a huge block of text -> is there a way javascript automatically can turn the huge block of text into an array, or will i have to manually do it? EDIT: I just figured it out, after I parse it it fixes it. Thanks! – Davis Wu Sep 03 '14 at 00:54
  • Multiple string methods available in JavaScript to manipulate your string: http://www.w3schools.com/jsref/jsref_obj_string.asp – Coded Monkey Sep 03 '14 at 00:59
0

With the help of the responses, if anyone in the future has the same issue, you should:

Call Ajax with a parameter data-type: "json", and making sure to parse the data after you receive it:

$('#selProgram').on('change', function() {
      var id = this.value;
      if (id != "None") {
        $.ajax({
          type: "POST",
          url: "assets/php/fetch_req.php", 
          data: "id="+id,
          datatype: "json",
          success: function(data) {
            JSON.parse(data)
          }
        });
      }
    });

Also, encode into JSON when sending with php:

echo json_encode($result);

Thanks!

This helped a lot How to return an array from an AJAX call?

Community
  • 1
  • 1