Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX response type

Tags:

jquery

ajax

I'm trying to make a working example of jQuery 1.9.1 AJAX + icanhaz/mustache. This is my template:

<script id="user" type="text/html">
    {{#users}}<li>Username: {{ username }}, fullname: {{ fullname }}</li>{{/users}}
</script>

and this is my JavaScript:

$(document).ready( function() {
    $("#user-btn").click(function() {
        $.ajax({
            type: "GET",
            url: "../php/client/json.php",
            data: {
                type: "users"
            }
        }).done(function( response ) {
            var element = $('#dialog-message');
            element.html("<ul>");
            element.append(ich.user(response));
            element.append("</ul>");
        });
});

The AJAX response from this address looks something like:

{"users":[{"username":"jd","fullname":"John Doe"},{"username":"jl","fullname":"John Lennon"}]};

With the following code, icanhaz cannot render anything for me. I spent some time with javascript console and found out that the typeof response is string and I expected object. Icanhaz also expects object - that's why it didn't manage to render the correct response.

Am I doing something wrong or am I just a poor newbie who didn't know that jquery.ajax returns string responses always? If so, how should I handle them?

like image 314
ducin Avatar asked Mar 27 '13 23:03

ducin


Video Answer


2 Answers

If you are getting a string returned from your AJAX call, you need to add dataType: "json". This will make jQuery parse the response as JSON, if possible.

$(document).ready( function() {
    $("#user-btn").click(function() {
        $.ajax({
            type: "GET",
            url: "../php/client/json.php",
            data: {
                type: "users"
            },
            dataType: "json"
        }).done(function( response ) {
            ...
        });
});

Are you sure your ich.user method expects an array of users and not just a single user object?

like image 142
Steve Avatar answered Nov 02 '22 17:11

Steve


Try the option dataType: "json" for $.ajax.

like image 23
Marcel Gwerder Avatar answered Nov 02 '22 18:11

Marcel Gwerder