user1227914
user1227914

Reputation: 3514

json response in ajax is correct, but content doesn't update?

I have a script that gets called like this:

success: function(json) {
        if(json.valid == 1) {

            // some other show/hide here that works correctly
            $("#div-response-" + id).html(json.message);

        }
        else {
            // some other show/hide here that works correctly
            $("#div-response-" + id).html(json.message);
        }
    }

and returns the response like this:

{"valid":"1","message":"<span class=\"icon color-red\"><\/span>"}

or

{"valid":"0","message":"<span class=\"icon color-black\"><\/span>"}

and the HTML code is:

<div id="div-response-<?=$id;?>" data-id="<?=$id;?>"></div>

For some reason, I can't figure out why ...everything works correctly up to the point when the div should update the information. It just stays empty.

Upvotes: 0

Views: 477

Answers (4)

Jordi Nebot
Jordi Nebot

Reputation: 3401

Assuming the server response has a valid JSON header ( that'd be: header('Content-type: application/json'); ) there's no need for JSON.parse() or $.parseJSON

Also, check the CSS affecting .icon and .color-red .color-black classes on the span. Maybe your code is working but isn't showing anything due to CSS

Upvotes: 0

Mohamed Shaaban
Mohamed Shaaban

Reputation: 1169

Set the dataType to json in your ajax request, and make sure your server produces json data (content-type header set to application/json)

$.ajax({
    url: '/something',
    dataType: 'json',
    success: function(json) {
        if(json.valid == 1) {

            // some other show/hide here that works correctly
            $("#div-response-" + id).html(json.message);

        }
        else {
            // some other show/hide here that works correctly
            $("#div-response-" + id).html(json.message);
        }
    }
});

Upvotes: 0

Anand G
Anand G

Reputation: 3200

Seems like you want to update your div with message in json. Try to use eval function. You may also need to parse json

success: function(json) {
    var json = jQuery.parseJSON(json);
    if(json.valid == 1) {

        // some other show/hide here that works correctly
        $("#div-response-" + id).html(eval(json.message));

    }
    else {
        // some other show/hide here that works correctly
        $("#div-response-" + id).html(eval(json.message));
    }
}

Upvotes: 0

Nishit Maheta
Nishit Maheta

Reputation: 6031

use jQuery.parseJSON() function to convert resonse from server to JSON if you are not use type JSON in ajax param.

json = jQuery.parseJSON(json);

Upvotes: 2

Related Questions