Home > Net >  AJAX different data records in Response Javascript
AJAX different data records in Response Javascript

Time:02-16

I am working on a site using HTML/CSS/JS and AJAX for connecting to the server. (new to web development)

I currently have this to get data and put it in an array.

var addresses = [];

$.ajax({
     type: "GET",
     url: 'GetAddresses.php',
     data: {"type":"check"},
     success: function(response){
         alert(response);
         addresses.push(response) // add values from php to array
     }
    });

But what if php echoed an address, a name, and a city for example. How could I access those different values?

Thank you for your help.

CodePudding user response:

Typically you would write PHP that outputs structured data, e.g. JSON, and then parse that on the client.

<?php
    header("Content-Type: application/json");

    $data = [ "address" => "foo", "name" => "bar", "city" => "baz" ];

    echo json_encode($data);
?>

and then on the client:

$.ajax({
     type: "GET",
     url: 'GetAddresses.php',
     data: {"type":"check"},
     success: function(response){
         alert(response);
         console.log(response.address);
         console.log(response.name);
         console.log(response.city);
     }
 });

Unrelated to the focus of your question, pushing data into an array in the wider scope from an Ajax callback is likely to cause you problems.

  • Related