AJAX different data records in Response Javascript

All we need is an easy explanation of the problem, so here it is.

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply