jQuery $.post processing JSON response

I’m having trouble figuring out how to properly read my JSON response from a jQuery $.post() request.

In the below jQuery code, I populate an associative array of strings from elements from the DOM based on the corresponding “color_entry_id” which I use as the key:

var image_links = {};
$(this).find('input[name="color_id"]').each(function() {
    var color_entry_id = $(this).val();
    var image_link = $(this).parent().find('input[name="edit_image"].' + color_entry_id).val();
    image_links[color_entry_id] = image_link;
});

Then I make the POST request, sending my array of “image_links”:

$.post(
    "test.php",
    { id: product_id, "images[]": jQuery.makeArray(image_links) },
    function(data) {
        var response = jQuery.parseJSON(data);
        $.each(response.images, function(index, item) {
             alert(item);
        });
    }
);

Also, as shown above, I try to loop through the response array and output each item, which I want to be a string, but I only get “[object Object]” as the alerted value. I don’t know how to make it display the strings I’m trying to display!

Here is the PHP code for test.php:

<?php
    $product_id = $_POST['id'];
    $images = $_POST['images'];

    $response = array();
    $response['id'] = $product_id;
    $response['images'] = $images;

    echo json_encode($response);
?>

And here’s what the relevant part of the DOM looks like:

<input type='hidden' value='{{ color_entry_id }}' name='color_id' />
<p><img src='{{ color_img_link }}' /></p>
<p>Image Link: <input class='{{ color_entry_id }}' name='edit_image' type='text' size='150' value='{{ color_img_link }}' /></p>
<div class='colors {{ color_entry_id }}'>
    <div class='img_color'>
        <a href='javascript:void' style='background:...' class='selected'></a>
        <p>...</p>
    </div>
</div>

I’m wondering whether perhaps I’m doing the JSON encoding incorrectly on the PHP side or if I’m just looping through the response incorrectly in the jQuery. Any help is much appreciated!!

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Ok then..the data object you’re getting back from the post is: {"id":"abc","images":[{"color123":"somelink.com\/123","color223":"somelink.com\/‌​223"}]};

If you change your alert, you’ll find the values you’re looking for:

$.post(
    "test.php",
    { id: product_id, "images[]": jQuery.makeArray(image_links) },
    function(data) {
        var response = jQuery.parseJSON(data);

        var images = response.images[0];
        for (var i in images){
            alert(images[i]);
        }
    }
);

Solution 2

$.post expects xml by default, you need to specify the response format

$.post(
    "test.php",
    { id: product_id, images : jQuery.makeArray(image_links) },
    function(response) {
        // Response is automatically a json object
        for(var i = 0; i < response.images.length; i++) {
            alert(response.images[i]);
        }
    }, 'json' // <-- HERE
);

Also, consider adding a content type header in your php script

    <?php
    header("Content-type: application/json"); // Adding a content type helps as well
    $product_id = $_POST['id'];
    $images = $_POST['images'];

    $response = array();
    $response['id'] = $product_id;
    $response['images'] = $images;

    echo json_encode($response);
    ?>

Solution 3

A pretty basic example would be something like :

$.post('test.php', {"id": 42}, function (json) {
 console.log(json);
}, 'json');

PHP example

$number = rand(1,$_POST["id"]);
return print json_encode($number);

Note: Use and implement solution 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