jQuery .getJSON vs .post which one is faster? - javascript

Using
$.getJSON();
or
$.post();
I'm trying to send some parameters through a page that is just for AJAX request
and get some results in JSON or html snippet.
What I want to know is that which one is faster?
Assume the HTML file would be simply plain boolean text (true or false)

As others said there is no real difference between the two functions, because both of them will be sent by XMLHttpRequest.
If the server is handling both of the requests with the same code then the handling times should be the same.
Therefore the question can be translated to which one is faster the HTTP GET request or the POST request?
Because the POST request needs two additional HTTP headers (Content-Type and Content-Length) comparing to the GET request the latter should be faster (because less data will be transferred).
But that's just the speed, I think it's better to follow the REST guidelines here. Use POST if you're modifying something, use GET if you want to fetch something.
And one another important thing, GET responses could be cached, but I was having problems caching POST ones.

i dont think it will make a difference both make use of ajax, .post loads the data using http post request where as getJSON uses a http get request more over you dont have to explicitly tell getJSON the dataType

If it is a HTTP action that is retrieving data from the server without persisting (updating) anything, GET is the correct semantic to use.
Both post and get use HTTP so performance difference will be negligible, especially considering the variables of WAN communication.

They are both wrappers/shorthand methods for jQuery.ajax, so there wont be a performance difference.

This is old but ...
We all have to remember about: CSRF/XSRF.
If you do it this way:
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: {
token : 'pass-some-security-token-here'
},
cache: false,
success: function(data) {
//do your stuff here
}
});
you can receive it then like this, nullifying most CSRF/XSRF
if (isset($_POST['token'])) { //you can also test token further
//do your stuff her and send back result
} else {
//error: sorry, invalid, or no security token
}
In many cases GET is an invitation for bad guys, as getJSON uses GET HTTP request.

$.getJSON(); is a shortcut to $.ajax(); which also calls $.post(); so you won't see much difference (but it will be easier to use $.getJSON() directly).
See the jquery doc
[EDIT] NimChimpsky was faster than me...

There are no difference, Because both are using XMLHttpRequest.
First, $.getJSON() is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
https://api.jquery.com/jQuery.getJSON/
Second, $.post() is also a shorthand Ajax function, which is equivalent to:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
https://api.jquery.com/jquery.post/

Related

jQuery $.ajax done callback not firing

I have the following code :
$("#loginSubmitButton").on("click",function(){
var loginUserDetails = {
email: $("#email").val(),
password: $("#password").val()
};
//Send the AJAX request to authenticate the user
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: JSON.stringify(loginUserDetails),
contentType: "application/json;charset=UTF-8",
dataType: "json",
}).done(function() {
$("#loginResult").text("Login successful");
})
.fail(function() {
$("#loginResult").text("Login failed");
});
});
As per the jquery documentation (unless I am understanding something incorrectly) I expect the done to be fired if I receive a 200 OK from my web server. However, in chrome console I can see a 200 OK response but jquery seems to fire the fail handler.
Does anyone have any idea what I might be doing wrong here?
You need to remove:
dataType: "json"
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's probably ignoring the underlying issue. It's most likely caused by a parser error (the browser parsing the json response). Firstly examine the XHR parameter in either .always() or .fail().
Assuming it is a parser fail then why? Perhaps the return string isn't JSON. Or it could be errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
If your server returns empty string for a json response (even if with a 200 OK), jQuery treats it as failed. Since v1.9, an empty string is considered invalid json.
Whatever is the cause, a good place to look at is the 'data' parameter passed to the callbacks:
$.ajax( .. ).always(function(data) {
console.log(JSON.stringify(data));
});
Its contents will give you an understanding of what's wrong.
Need to remove , from dataType: "json",
dataType: "json"
The ajax URL must be the same domain. You can't use AJAX to access cross-domain scripts. This is because of the Same Origin Policy.
add "dataType:JSONP" to achieve cross domain communication
use below code
$.ajax({
URL: cross domain
dataType: 'jsonp'
// must use dataType:JSONP to achieve cross domain communication, otherwise done function would not called.
// jquery ajax will return "statustext error" at }).always(function(data){}
}).always(function(data){
alert(JSON.stringify(data));
}
A few things that should clear up your issue and a couple hints in general.
Don't listen for a click on a submit button. You should wait for the submit event on the form.
The data option for $.ajax isn't expecting a JSON string. It wants a serialized string or an array with name and value objects. You can create either of those easily with .serialize() or .serializeArray().
Here is what I was thinking for your script.
$('#form-with-loginSubmitButton').on('submit', function(e){
e.preventDefault():
var $form = $(this),
data = $form.serializeArray();
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: data
}).done(function(result){
console.log(result);
});
});

Getting response in return to use it further in Javascript

jQuery.ajax({
url:'https://graph.facebook.com/me/feed?message=Hello&method=POST',
dataType:'script',
success:function(){
How do I get the response in return to use it further in Javascript?
Please Help Anyone.
You're half-way there already. The docs for the jQuery.ajax method explain that the success option defines a function to be executed when the request is successful, and that it will receive the response as its first parameter.
jQuery.ajax({
type: 'POST',
url:'https://graph.facebook.com/me/feed?message=Hello&method=POST',
success:function(response) {
// This will display the actual response in your console (e.g. FireBug)
// Note that jQuery may attempt to format the response into an object (if it receives JSON or XML for instance)
console.log(response);
// Do stuff with the response
}
});
It's possible you may be running into some trouble with your dataType: 'script' setting. That tells jQuery to try and execute the response data as though it were valid Javascript. Maybe that's what you want, but it sounds to me like you just want to use the data.
Personally, I feel it's good practice to always declare the dataType explicitly.
jQuery.ajax({
url:'https://graph.facebook.com/me/feed?message=Hello&method=POST',
dataType:'script',
success:function(response) {
// use repsonse here. For example:
alert(response);
}
});

Calling a web service in JQuery and assign returned Json to JS variable

This is my first time attempting working with JQuery, Json AND calling a web service.. So please bear with me here.
I need to call a webserivce using JQuery, that then returns a Json object that I then want to save to a javascript variable. I've attempted writing a little something. I just need someone to confirm that this is indeed how you do it. Before I instantiate it and potentially mess up something on my company's servers. Anyways, here it is:
var returnedJson = $.ajax({
type: 'Get',
url: 'http://172.16.2.45:8080/Auth/login?n=dean&p=hello'
});
So there it is, calling a webservice with JQuery and assigning the returned jsonObject to a javascript variable. Can anyone confirm this is correct?
Thanks in advance!
var returnedJson = $.ajax({
type: 'Get',
url: 'http://172.16.2.45:8080/Auth/login?n=dean&p=hello'
});
If you do it like this returnedJson would be an XHR object, and not the json that youre after. You want to handle it in the success callback. Something like this:
$.ajax({
// GET is the default type, no need to specify it
url: 'http://172.16.2.45:8080/Auth/login',
data: { n: 'dean', p: 'hello' },
success: function(data) {
//data is the object that youre after, handle it here
}
});
The jQuery ajax function does not return the data, it returns a jQuery jqHXR object.
You need to use the success callback to handle the data, and also deal with the same origin policy as Darin mentions.
Can anyone confirm this is correct?
It will depend on which domain you stored this script. Due to the same origin policy restriction that's built into browsers you cannot send cross domain AJAX requests. This means that if the page serving this script is not hosted on http://172.16.2.45:8080 this query won't work. The best way to ensure that you are not violating this policy is to use relative urls:
$.ajax({
type: 'Get',
url: '/Auth/login?n=dean&p=hello'
});
There are several workarounds to the same origin policy restriction but might require you modifying the service that you are trying to consume. Here's a nice guide which covers some of the possible workarounds if you need to perform cross domain AJAX calls.
Also there's another issue with your code. You have assigned the result of the $.ajax call to some returnedJson variable. But that's not how AJAX works. AJAX is asynchronous. This means that the $.ajax function will return immediately while the request continues to be executed in the background. Once the server has finished processing the request and returned a response the results will be available in the success callback that you need to subscribe to and which will be automatically invoked:
$.ajax({
type: 'Get',
url: '/Auth/login?n=dean&p=hello',
success: function(returnedJson) {
// use returnedJson here
}
});
And yet another remark about your code: it seems that you are calling a web service that performs authentication and sending a username and password. To avoid transmitting this information in clear text over the wire it is highly recommended to use SSL.

Calling a webservice using JQuery

I am using this code from http://www.joe-stevens.com/2010/01/04/using-jquery-to-make-ajax-calls-to-an-asmx-web-service-using-asp-net/
function callWebService(address) {
var result;
$("#result").addClass("loading");
$.ajax({
type: "POST",
url: address,
data: "{}",contentType: "application/json; charset=utf-8",
dataType: "json",
success: Success,
error: Error
});
}
function Success(data, status) {
$("#result").removeClass("loading");
$("#result").html(data.d);
alert("Success");
}
function Error(request, status, error) {
$("#result").removeClass("loading");
$("#result").html(request.statusText);
alert("Error");
}
I don't understand what is wrong with this code. It keeps returning "Error"
Also make sure that the service URL that you're trying to access is in the same domain as your site. AJAX calls won't succeed if you cross domains, since browsers subject AJAX calls to the same domain policy. Can you also include the URL you're trying to access?
If you're trying to access a resource at a different domain, you may want to consider a JSONP request instead. See the jQuery AJAX documentation for a discussion of how to use JSONP.
I think if you combine knowing the URL you're trying to access along with Justin and mohlsen's suggestions, I think we can help.
Your code looks fine at first glance.
I recommend you use FireBug to attempt to isolate the problem further, as it will allow you to see the actual HTTP requests, POSTed data, etc...
A few suggestions based on some code I have doing this. But as others have said, make sure to manually look at the data going out and coming back. Your link references asp.net webservice, is that what you are calling since you didn't mention it.
Make sure the "address" url is of the form /location/page.asmx/methodname
You might need to pass the data to the success method in the call
success: function(msg) {
//msg is a json object, .d is the data field returned by asp.net
if (msg.d.length > 0)
ProcessData(msg.d);
else
HandleError('No data was returned.');
},
error: function() {
HandleError('There was a problem calling the webservice.');
}

jQuery JSONP, only works with same site URLs

I need to make a request to an API which returns json formatted data. This API is on a sub-domain of the domain this script will run off (although at the moment it's on a totally different domain for dev, localhost)
For some reason I thought that jsonp was supposed to enable this behavior, what am I missing?
Using jQuery 1.4.2
$.ajax({
url:'http://another.example.com/returnsJSON.php',
data: data,
dataType:'jsonp',
type: "POST",
error: function(r,error) {
console.log(r);
console.log(error);
},
success:function(r){
console.log(r);
}
});
Change your type from "POST" to "GET".
That is, only if you intend to retrieve data.
You'll need a combination of Arnaud's answer (don't use POST) and R. Bemrose's answer (make sure server-side returns JSONP), with the added specification of a callback function.
In other words, here's your modified request code:
function dosomething(data) {
console.log(data);
}
$.ajax({
url: 'http://another.example.com/returnsJSON.php',
data: data,
dataType: 'jsonp'
});
Helpful to note that in the generated code you'll see that when the dataType is "jsonp", jQuery outputs a script tag pointing at the url; it's not a typical XHR. You could also use jQuery's getJSON() here.
Then your response will have to be formatted as such:
dosomething({
test: 'foo'
});
When the call is complete, your specified callback will fire.
Did you modify the server-side component to use JSONP?
You can't just tell the client to use JSONP and suddenly expect a JSON script on the server-side to return the correct result.
Specifically, JSONP requires the server to return a JavaScript string that calls a specific function (whose name is passed in with the other arguments) with the return results, which the client then evals.

Categories

Resources