Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
},
like image 984
Trt Trt Avatar asked Sep 07 '12 16:09

Trt Trt


People also ask

How do I get AJAX response in JSON format?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

How can I get specific data from AJAX response?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.

What is parseJSON in jQuery?

parseJSON( json )Returns: String or Number or Object or Array or Booleanversion deprecated: 3.0. Description: Takes a well-formed JSON string and returns the resulting JavaScript value.


1 Answers

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.

like image 63
Peter Avatar answered Sep 25 '22 04:09

Peter