0

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.

1 Answers1

0

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Your link has a lot to say about scope in JavaScript, but I don't see the part that relates to your specific warning. Could you quote the relevant text? – mark_b Feb 15 '22 at 14:46
  • It's the whole accepted answer. Worry about it when you find the array unexpectedly empty. – Quentin Feb 15 '22 at 14:47