Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.post processing JSON response

Tags:

json

jquery

php

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!!

like image 843
Jon Rubins Avatar asked May 07 '12 01:05

Jon Rubins


People also ask

How to return JSON response in AJAX?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

How to call http POST method in jQuery?

The jQuery post() method sends asynchronous http POST request to the server to submit the data to the server and get the response. Syntax: $. post(url,[data],[callback],[type]);

What is parseJSON in jQuery?

The jQuery parseJSON() method takes a JSON string and returns a JavaScript object. The specified JSON string must follow the strict JSON format. Passing an incorrect string will cause a JS exception. Some of the examples of malformed JSON strings that can cause an exception on passing are given as follows -

How to return JSON data to AJAX?

ajax({ url: '<? php echo site_url('find_representatives/find_rep_by_address/get_coordinates'); ?> ', dataType: 'json', data: '', success: function(data, status, xhr) { alert(data); }, error: function(xhr, status, error) { alert(status); } });


2 Answers

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]);
        }
    }
);
like image 191
ltiong_sh Avatar answered Oct 12 '22 11:10

ltiong_sh


$.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);
    ?>
like image 36
Bryan Avatar answered Oct 12 '22 12:10

Bryan