ruzD ruzD - 1 year ago 113
Ajax Question

How to get values of the AJAX Response

I am not to getting the values from the result of the AJAX call. I return JSON but I do not know how to get a value. This is my code:

$.ajax({
method: 'POST',
dataType: 'json',
url: 'queryProduct.php',
data: { codigo: cod }
}).done(function(response){

// How do it get values???
});


PHP file result:

$query = "SELECT * FROM produccion.ma_producto WHERE codigo={$codigo}";
$result = pg_query($conn, $query);

if (!$result) {
echo "Error query: " . pg_last_error($conn);
} else {
header('Content-type: application/json; charset=utf-8');
echo json_encode($result);
}


From the first jquery call php file with ajax and after I would like to get the values and set to others elements....

Answer Source

$row = pg_fetch_row($result) echo json_encode($row);

Use above code in your PHP file.

Consider AJAX call returns this JSON Array.

i.e.

response = [
        {
            color: "red",
            value: "#f00"
        },
        {
            color: "green",
            value: "#0f0"
        },
        {
            color: "blue",
            value: "#00f"
        },
        {
            color: "cyan",
            value: "#0ff"
        },
        {
            color: "magenta",
            value: "#f0f"
        },
        {
            color: "yellow",
            value: "#ff0"
        },
        {
            color: "black",
            value: "#000"
        }
    ]

Now, after success of AJAX call you want to iterate through each JSON Object of this array, Where each Object is { color: 'someValue', value : 'someValue'}. You can use item.color and item.value to access them.

You can do something like this:

 $.ajax({
 method: 'POST',
 dataType: 'json',
 url: 'queryProduct.php',
 data: { codigo: cod },
 success: function(response) {                                   
     console.log(response.pagino);
});

Here, response is your JSON Array and item represents an Object of JSON Array.

You can use item.fieldName to access each of your field from each JSON Object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download