In a jquery ajax call I get sent back some JSON from the server and want to use some of it in the success callback. I pass in the data, but how do I get at a specific value (say "id")?
I tried this but I get undefined:
success : function(data) {
alert(data["id"]);
},
Your ajax request should look something like this:
$.ajax({
url: "...",
dataType: "json",
success: function(data){
alert(data.id);
});
Related
I have a very simple $.ajax call that is suppose to get the json data from a given url. Currently the url does get called and the data does get returned, however the localHsonpCallback function doesn't seem to get fired.
Here is my code.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
}
function localJsonpCallback(json) {
console.log("Fired");
if (!json.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
So as mentioned above for some reason the localJsonpCallback doesn't seem to get fired at all.
Also I should mention that in my Chrome Dev tools the request link ends up looking like this for reason
http://localhost/api/users?callback=localJsonpCallback&_=1429708885454
Any help in this question would be greatly appreciated.
Thank you.
Try the callback method as an anonymous function directly inside the parameter list.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonpCallback: function(data){
console.log("Fired");
if (!data.Error) {
console.log("Fired");
}
else {
console.log("ERROR");
}
}
});
}
If youre not appending the callback onto the url you can set the jsonp oprion to false and then, as you are doing, set the callback in the options.
function getBuildings(){
$.ajax({
url: 'http://localhost/api/users',
type: "GET",
dataType: "jsonp",
jsonp: false,
jsonpCallback: "localJsonpCallback"
});
}
Since javascript is sequential its also a good idea to define your functions before theyre called. ie - define your callback function before your ajax call.
http://api.jquery.com/jQuery.ajax/
jsonp
Type:
String Override the callback function name in a JSONP request.
This value will be used instead of 'callback' in the 'callback=?' part
of the query string in the url. So {jsonp:'onJSONPLoad'} would result
in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
jsonp option to false prevents jQuery from adding the "?callback"
string to the URL or attempting to use "=?" for transformation. In
this case, you should also explicitly set the jsonpCallback setting.
For example, { jsonp: false, jsonpCallback: "callbackName" }
Maybe this piece of code it will help solve your problem:
$.ajax({
type: 'GET',
url: 'http://localhost/api/users',
data:{todo:"jsonp"},
dataType: "jsonp",
crossDomain: true,
cache:false,
success: success,
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
//your code here
};
This either a server side problem that the callback parameter is not used properly or the parameter name callback does not exist for the server side they are looking for something different.
You said the result is returning, what is the format? JSONP must return a script block not pure data so be sure the result is in below format.
{callbackFunctionName}({hugeDataFromServer});
Basically it is script that calls your function.
if it is not the server side that means it is more likely they are using a different name for callback parameter e.g. cb , _callback etc
What is the actual url sent to the server when I use the jquery ajax? And how do I access that value? For example, consider the following code:
<script>
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: {name:'Smith',age:10},
success: function(data) {
...
}
beforeSend: function(){
console.log(url);
// what do I put here to see what is being sent
// I am expecting to see "response.php?name=Smith&age=10"
}
...
So essentially what variable holds "response.php?name=Smith&age=10".
Thanks.
No variable holds
response.php?name=Smith&age=10
because you aren't sending the data as a query string. This would happen if you issued a GET request, but doesn't with a POST request.
You're sending the data in the request body of an HTTP post. The data is the data that you assigned to the data parameter. You don't need to round-trip it through jQuery's ajax methods. You've got it already. It's:
{name:'Smith',age:10}
does jQuery's interpretation of your data really matter?
The settings object is fully populated when beforeSend is called:
beforeSend: function(jqXHR, settings) {
console.log(settings.url);
console.log(settings.data);
}
$.ajax({ type: "POST", ... }) will log
response.php
name=Smith&age=10
and type: "GET"
response.php?name=Smith&age=10
undefined
I am using JQuery's .ajax method to call to a URL which returns a JSON encoded string. I can see the object returned from the GET in the debugger, but for some reason I'm not falling into the success function. Any ideas?
$.ajax({
type: "GET",
url: 'http://search.issuu.com/api/2_0/document?q=jamie',
dataType: "jsonp",
success: function(data){
alert('Success!');
}
});
If you look at the documentation, it shows that the proper way to make a jsonp request requires a jsonCallback parameter.
Code:
$.ajax({
type: "GET",
url: 'http://search.issuu.com/api/2_0/document?q=jamie&jsonCallback=?',
dataType: "jsonp",
success: function(data){
alert('Success!');
}
});
Fiddle: http://jsfiddle.net/xrk4z6ur/2/
jQuery will by default use callback=? for a jsonp request. In this case, the API accepts jsonCallback. Adding jsonCallback=? to the url will let jQuery handle it properly.
If you are using jsonp you should specify a callback GET parameter like &callback?
On server side return the callback with your desired data as argument (json encoded)
I am using the following jquery to make an ajax call:
$.ajax({
url: "/projects/project/xGetProjectStatus",
type: "GET",
dataType: "json"})
.done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
The alert pop up always says that responseText is undefined. The page I am "get"ting is well formatted JSON and if I run these commands in the console one at a time everything works fine. What is wrong?
You're looking for responseText in the response, it won't be there. You'll find it instead on the jqXHR object itself (which is the third parameter passed to your done() function, and also returned by your whole $.ajax() call).
And because you have dataType: "json" the response is already a JSON parsed object.
Change this:
.done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
To just this:
.done( function(data){
if(data.success){
//stuff here
}
})
When you set the dataType in a jQuery.ajax call it will be returned as a parsed object. So your request object in .done is actually your parsed json string
If you don't want jQuery to automatically parse your JSON you can remove the datatype from the call.
$.ajax({
url: "/projects/project/xGetProjectStatus",
type: "GET"
}).done( function(request){
alert(request.responseText);
var data = JSON.parse(request.responseText);
if(data.success){
//stuff here
}
})
This is because the first parameter of the done function is not the XHR object but the contents of the responseText as an object already. jQuery handles all that for you and so there's no need to do any manual conversion.
the done function is called whenever the ajax call is successful anyways so no need to re-check it and the fail function is called when a response other than 200 is returned.
i need to call a servlet from javascript by using ajax post method and also need to send some parameters to that servlet. How can i do that. I have spent too much time to get rid of this but still no luck...! All help appreciated.....Please help
using jQuery is very easy...
$.post("yourServletUrl",{"param1":"1","param2":"2"},function(data){},"json");
this is method post
first param: servlet url
second param: params
third param: callback
the last param: response data format ("json","xml"...)
Try this ...
jQuery.ajax({
url:URL,
data:{"key1":"value1","key2":"value2"},
type:'POST',
dataType : 'xml', /* use 'jsonp' for cross domain*/
success:function(data, textStatus, jqXHR){
// access response data
},
error:function(data, textStatus, jqXHR){
console.log('Service call failed!');
}
});
Try this
$.ajax({
type : 'GET',
url : '${pageContext.request.contextPath}/Servletname',
data : $('#formname').serialize(),
success : function(response) {
alert(response)
}
});