skip to Main Content

How is it possible to send an array of objects (entity) back to Javascript after an Ajax request?
If I return the array with the objects with a JSON response, the array is empty in Javascript.
Dump of array:

array:2 [
  0 => AppEntityFirewalls {#744
    -id: 2
    -ip: "test.com"
    -user: "admin"
    -pass: "pw"
    -status: AppEntityStatus {#741
      -id: 2
      -status: "Finalize"
      -update: null
      -time: null
      -firewall: AppEntityFirewalls {#744}
    }
  }

2

Answers


  1. I’d encode the json first like

    $firewalls = [ 'your', 'firewalls' ];
    $json = json_encode($firewalls);
    echo $json;
    

    then parse it back

    $.ajax({
      type: "POST",
      url: "server.php",
      dataType: "json",
      success: function (firewalls) {
        console.log(firewalls);
      }
    });
    

    if the datatype is set as json, jQuery should automatically parse it. If it doesn’t work, feel free to share what the browser’s developer tools say.

    Login or Signup to reply.
  2. Do you have composer require symfony/serializer ? if not I recommend you use it.

    You can the use symfony object normalizer and serialize an entity (or array of entities) into a json.

    Create a serializer:

    use SymfonyComponentSerializerEncoderJsonEncoder;
    use SymfonyComponentSerializerEncoderXmlEncoder;
    use SymfonyComponentSerializerNormalizerObjectNormalizer;
    use SymfonyComponentSerializerSerializer;
    
    $encoders = [new XmlEncoder(), new JsonEncoder()];
    $normalizers = [new ObjectNormalizer()];
    
    $serializer = new Serializer($normalizers, $encoders);
    

    And use it with your entity or entities:

    $this->serializer->serialize($data, 'json');
    

    You can read more about this here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search