Mark Henry
Mark Henry

Reputation: 2699

updating html elements with ajax json response

I use this script to update table cells based on ajax request with json response. The thing it does not update the specified table cells. Is my json string not formatted correctly?

$(document).ready(function() {

    $('select.swcomp').change(function () {
        var res_id = $(this).val();
        var index = $(this).data('index');

        $.ajax({
            type: 'POST',
            url:'http://skiweather.eu/v3/ajax/compare_snow.php',
            data: '{ "res_id":"' + res_id + '", "index":"' + index + '" }',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (response) {
                $('#destin_' + index).html(response.resort);               
                $('#snowval_' + index).html(response.snow_valley);
                $('#snowmnt_' + index).html(response.snow_mountain);            
            }
        });
        return false;
    });

});

html

 <select name="resort_1" class="swcomp" data-index="1">
                    <option value="NoResort">resorts</option>
                    <option value="6">Adelboden</option>
                    <option value="237">Davos</option>
</select>

<table>
    <tr><td id="destin_1">res</td></tr>
    <tr><td id="snowval_1">val</td></tr>
    <tr><td id="snowmnt_1">mnt</td></tr>
</table>   

json

var response =[{"snow_valley":"40","snow_mountain":"40","resort":"Adelboden"}]

Upvotes: 0

Views: 2847

Answers (2)

yes your received json formatted correctly . if your want check your json farmatted correctly follow this site http://jsonlint.com/ it will check your json validation. for accessing json data http://jsontree.com/ simply paste your json and parse it will provide how easily acess data

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

response is not an object, it is an array so response.resort is undefined it should be response[0].resort

$('#destin_' + index).html(response[0].resort);               
$('#snowval_' + index).html(response[0].snow_valley);
$('#snowmnt_' + index).html(response[0].snow_mountain); 

Upvotes: 2

Related Questions