Trt Trt
Trt Trt

Reputation: 5532

jQuery Ajax GET JSON

I have this piece of code:

$.ajax({
url: '/piece.json',
type: "GET",
dataType: "json",
success: function (data) {
    alert(data);
}
});

I am on a rail3 app, when I type "/piece.json" I get on my browser what I want. But I cant make it alert using Javascript! Why this happens?

Solved, had to use this:

complete: function (data_response) {

    alert(data_response.responseText);
},

Upvotes: 16

Views: 98021

Answers (6)

Philip E
Philip E

Reputation: 858

This worked for me:

$.getJSON( "example.json", function(data) {
   console.log( "success" );
}).done(function() {
   console.log( "second success" );
})
.fail(function() {
  console.log( "error" );
})
.always(function() {
   console.log( "complete" );
});

Replace example.json, with the url or path of your json file. Note the use of $.getJSON vs $get . Here's my reference: http://api.jquery.com/jquery.getjson/

Upvotes: 8

Phrogz
Phrogz

Reputation: 303136

Presumably you don't have a working route for /piece.json. Use the Developer Tools in your browser and log from the rails app to see what is going on with the XHR request.

(Look at the http response in the browser.)

Note that you can more simply use:

$.get('/piece.json',function(data){
  // data is a JS object parsed from a JSON response
},'json');

Upvotes: 3

ck3g
ck3g

Reputation: 5929

try to use complete callback instead of success. I don't why but success callback doesn't fires even if all data and response are correct. Looks like some kind of bug

Upvotes: 2

Jim Buck
Jim Buck

Reputation: 2444

Try changing the datatype to JSONP. It's usually to overcome the Same Origin Policy but may work in your case.

$.ajax({
    url: '/piece.json',
    type: "GET",
    dataType: "jsonp",
    success: function (data) {
        alert(data);
    }
});

Upvotes: 3

DadViegas
DadViegas

Reputation: 2291

Add this and see what is returned

error: function (error) {
    alert(JSON.stringify(error));
}

Upvotes: 1

Peter
Peter

Reputation: 5156

It's possible that piece.json doesn't returns valid JSON so jQuery discards it. Try to change dataType: "json" to dataType: "html" and see if the alert(data) shows the output. If the alert shows your data then there's a syntax error in the json object.

Upvotes: 6

Related Questions