jQuery AJAX response type

ajax, jquery

Solution

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?

Problem

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?

Original source