Search code examples
jqueryajaxjsonjqote

jqote returning undefined


I'm trying to update an HTML table with new data pulled in via json and using jQote.

I have a fairly simple jqote template:

<script type="text/html" id="template">
    <![CDATA[
        <tr>
            <td><%= this.customer_id %></td>
            <td><%= this.campaign_id %></td>
            <td><%= this.cname %></td>
            <td><%= this.create_date %></td>
            <td><%= this.phone %></td>
            <td><%= this.sname %></td>
            <td><%= this.reminder %></td>
            <td><%= this.appt_date %></td>
            <td><%= this.note %></td>
            <td><%= this.unread %></td>
        </tr>
    ]]>
</script>

And here's my JSON:

[{
    "customer_id": "2081",
    "campaign_id": "812",
    "cname": "Jeff",
    "create_date": "3 days ",
    "phone": "1111111111",
    "sname": "Massage Appointment",
    "reminder": "0",
    "appt_date": "0",
    "note": "",
    "unread": "2"
}]

And here's my jQuery:

$.ajax({
    type: 'POST',
    url: 'url/for/json/return',
    dataType: 'text/json',
    data: 'huh',
    success: function(jsondata){
        row = $('#template').jqote(jsondata);
        $('#customers > tbody').html(row); 
    },
 }
});

The ajax request runs fine and jsondata has the proper data stored inside, but my jQote tags are all returning undefined. Does anyone see what I am doing wrong?


Solution

  • Jeff, the JSON data variable fetched via POST is merely a string. You need to parse it with $.parseJSON prior to handing it over to jQote. Another possibility - as you have already figured out yourself - is to use jQuery's $.getJSON method which parses the response automatically.

    In case you are making use of jQote2 and jQuery 1.4.1 or above you should rewrite your script like this:

    $.ajax({
        type: 'POST',
        url: 'url/for/json/return',
        dataType: 'text/json',
        data: 'huh',
        success: function(jsondata){
            var data = $.parseJSON(jsondata);
            // Call the "substitute HTML" convenience method
            $('#customers > tbody').jqotesub('#template', data);
        }
    });
    

    For a description of $().jqotesub have a look at the jQote2 reference.