Lokesh Yadav
Lokesh Yadav

Reputation: 1602

Using JSON with Jquery Ajax

I started my hands on training on Jquery AJAX JSON this morning. I have knowledge of Jquery but JSON & Ajax is something new to me.

I have developed a small snippet of code to read JSON file with ajax and show the data values by appending the list.

using following div in body section.

<div id="tabPanelWrapper"></div>

Javascript:

$(document).ready(function() {

    // Calling Ajax Function
    loadContent();                          

});

function loadContent() {
    $.ajax({
       type: "GET",
       url: "data.js",
       dataType: "json",
       cache: false,
       contentType: "application/json",
       success: function(data) {
        alert("Success");
        $.each(data.dashboard, function(i,post){
            $('#tabPanelWrapper').append('<ul><li>' + data.id + '</li><li>' + data.name +'</li></ul>');
        });
      },
        error: function(xhr, status, error) {
            alert(xhr.status);
        }
    });
}

JSON File:

{
    dashboard: [
    {
        "id": "tcm:20-1869",
        "name": "FEATURED ARTICLE"
    },
    {
        "id": "tcm:20-1869",
        "name": "FEATURED ARTICLE"
    }
]
}

Page is throwing 404 error. Please help me with this code.

Thanks in advance | Lokesh Yadav

Upvotes: 0

Views: 4091

Answers (3)

mdaguerre
mdaguerre

Reputation: 1267

Check the URL property. An 404 error is not a json error.

Upvotes: 0

Yngve B-Nilsen
Yngve B-Nilsen

Reputation: 9676

a 404 error is a Page Not found error. I'd try to browse to the data.js file you're trying to access, and maybe try to write out the full url to the file in your .ajax-call.

I.e.

 http://myhost.com/script/data.js

if that's the location of your script.

UPDATE Your error is invalid Json. If you check the error argument in your Error-function, you'd see that.

Try adding quotes around dashboard, and you should be one step further!

And you'll also have to change in your success-method:

 $.each(data.dashboard, function(i,post){
            $('#tabPanelWrapper').append('<ul><li>' + post.id + '</li><li>' + post.name +'</li></ul>');
        });

note that I'm looking at post.id and post.name since that is the current item in the $.each enumeration. data.id would look for an id-property next to dashboard in your Json, but that doesn't exist.

Upvotes: 1

Jishnu A P
Jishnu A P

Reputation: 14382

change

$.each(data.dashboard, function(i,post){
        $('#tabPanelWrapper').append('<ul><li>' + data.id + '</li><li>' + data.name +'</li></ul>');
});

to

 $.each(data.dashboard, function(i,post){
        $('#tabPanelWrapper').append('<ul><li>' + post.id + '</li><li>' + post.name +'</li></ul>');
 });

defnitely the 404 error is not due to this.

Upvotes: 0

Related Questions