How these arguments of ajax function work? - javascript

I am whatching a tutorial that has the following code
But I can't understand what are url, cache and success? Are they arrays? How do they work?

You can find below the explanations:
cache
Type: Boolean
A Boolean value indicating whether the browser should cache the requested pages. Default is true.
If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters.
url
Type: String
Specifies the URL to send the request to. Default is the
current page
success(result,status,xhr)
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be run when the request succeeds
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
Everything is explained in the jQuery.ajax() Documentation

Related

jQuery ignores HTTP request method and appends weird URL parameters

I have a web service that expects POST requests carrying a JSON string in the body. I'm trying to use this web service using jQuery, but I have two problems :
1) jQuery seems to always use the GET method, no matter what I do ;
2) jQuery seems to append weird things into the URL.
The relevant pice of my code :
var WEB_SERVICE_URL = 'http://localhost/XXXX/';
// ...
$.post({
url: WEB_SERVICE_URL + 'GetConfigLabels/',
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
data: JSON.stringify(data),
processData: false,
success: function(response) {
// Whatever
},
error: function(xhr, message) {
// Whatever
}
});
The developper tools of the browser (Firefox Quantum 60.0.2) shows me a weird URL :
http://localhost/XXXX/GetConfigLabels/?callback=jQuery331012146934861340841_1530707758905&{}&_=1530707758906
While the following was expected :
http://localhost/XXXX/GetConfigLabels/
Also the HTML file is openned as a file (using file:///) through the file system, hence the use of JSONP for cross domain.
I failed to find existing questions related to this issue. What could be causing this ? Thank you !
Please refer to the dataType : json section at http://api.jquery.com/jquery.ajax/ :
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests that have a callback placeholder,
e.g. ?callback=?, are performed using JSONP unless the request
includes jsonp: false in its request options. The JSON data is parsed
in a strict manner; any malformed JSON is rejected and a parse error
is thrown. As of jQuery 1.9, an empty response is also rejected; the
server should return a response of null or {} instead. (See json.org
for more information on proper JSON format
overrding random name of callback using jsonpCallback :
jsonpCallback Type: String or Function() Specify the callback function
name for a JSONP request. This value will be used instead of the
random name automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests. As of jQuery 1.5, you can also use a function for this
setting, in which case the value of jsonpCallback is set to the return
value of that function.

Ajax MVC Partial Returning Correct Response Yet Fires the Error Handler

This has me completely stumped. So odd.
I have this Ajax function defined:
$.ajax({
type: 'GET',
dataType: 'text/HTML',
url: getLicenseeDetailsUrl,
success: function (response) {
$('#licenseeDetails').html('');
$('#licenseeDetails').html(response);
},
error: function (xhr) {
alert('Failed to get licensee details');
}
});
And I have it calling into my controller which has an action like:
public ActionResult LoadLicenseeDetails(long licenseeId)
{
var model = new LicenseeDetailsViewModel();
var licencesee = _licensingRepository.LoadById(licenseeId);
var licenses = _licensingRepository.LoadLicenses(licenseeId);
model.Licencee = Mapper.Map<Licensee, LicenceeViewModel>(licencesee);
model.Licences = Mapper.Map<IEnumerable<License>, IEnumerable<LicenceViewModel>>(licenses);
return this.PartialView("_LicenseeDetails", model);
}
This all seems to be working as expected without any errors, however it ends up firing the Ajax error function, not the success function.
Looking at the xhr.responseText I can see the correct response information from the action controller!!
All with a status 200 OK as well. What on earth am I doing wrong here?
What on earth am I doing wrong here?
this:
dataType: 'text/HTML'
should become:
dataType: 'html'
Quote from the documentation of the dataType parameter:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the
server. If none is specified, jQuery will try to infer it based on the
MIME type of the response (an XML MIME type will yield XML, in 1.4
JSON will yield a JavaScript object, in 1.4 script will execute the
script, and anything else will be returned as a string). The available
types (and the result passed as the first argument to your success
callback) are:
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are
evaluated when inserted in the DOM.
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by
appending a query string parameter, "_=[TIMESTAMP]", to the URL unless
the cache option is set to true. Note: This will turn POSTs into GETs
for remote-domain requests.
"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should
return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
"text": A plain text string.
multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
Or even better, simply get rid of this parameter. jQuery is intelligent enough to use the Content-Type response HTTP header set by the server in order to deduce the correct type and process the parameter passed to the success callback.
Look at the Console tab of your javascript debugging toolbar in the browser. It will provide you with more information about the error.

Explain jQuery's JSONP and the _ parameter [duplicate]

When I look at the query string from a jsonp request (client code below), there are 2 objects, a "callback" string that you need to use in the response (so the client codes directs to the success handler) and one with a key of _... what is this underscore for? I can't find any reference to this in any documentation, it appears to be a number of some kind.
I though that it might be used to direct to the error handler (either on its on, in combination with the callback, or replacing the number after the underscore in the callback string), but it doesn't appear to be.
url = 'http://localhost:11767/Handlers/MyHandler.ashx';
...
$.ajax({
url: url,
dataType: "jsonp",
error: function (jqXHR, textStatus, errorThrown) {
//...
},
success : function(d) {
//...
}
});
or
$.getJSON(url + "?callback=?", function(d) {
}).success(function(d) {
//...
}).error(function(jqXHR, textStatus, errorThrown) {
//...
}).complete(function(d) {
//...
});
Side note in case this helps anyone reading this: as this is a jsonp request, error will only be hit if the exception occurs client side, e.g. there is a timeout or a problem with the formatting of response (i.e. not using the callback), to overcome this, I always log and swallow the exceptions in the handlers, but give a standard response object (which all response are made up of) that has a state property of exception and a message property.
The number you are referring is the date time stamp of the request. Grab the number and use a your browser's JavaScript console and type: alert(new Date(/*insert number here*/))
You'll get an alert with a date/time.
EDIT:
Here's a snippet from jQuery.ajax doc regarding an ajax request:
cache
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser.
Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]",
to the URL.

Javascript automatically parsing nested object

This is more a question of procedure than anything else. I'm curious why this happens and I can't seem to find any documentation on this "feature" within the ECMA script documentation.
When I make an AJAX call within jQuery to my server, it returns the following JSON response to the page:
{"version":"v1","status":"OK","timestamp":"2013-02-14 10:32:45","data":"true","error":""}
With this string I have to call jQuery.parseJSON(string); to get it as an object, and the be able to reference it as an object.
However, when my server returns something like this:
{"version":"v1","status":"OK","timestamp":"2013-02-14 10:12:19","data":{"a":"asgsadfga","b":false,"c":[]},"error":""}
Javascript automatically loads this an an object without the need to parse. It would seem that because this example returns a nested object, despite the fact it was returned from the server as a string, Javascript will immediately recognize that, and parse the string for me.
Is this expected functionality, and if so, can anyone point me to the documentation of this?
EDITED:
Here is the offending AJAX call:
jQuery.ajax({
url: url,
type: 'GET',
async: false,
success: function (result) {
console.log(result)
}
Make sure that your server sets the proper Content-Type response HTTP header:
Content-Type: application/json
So that jQuery will automatically parse the JSON string returned by your server to a javascript object which will be passed as argument to your success callback.
Or if for some reason you've got some broken server side script which you have no control over you could set the dataType parameter to force jQuery to parse the result as JSON:
$.ajax({
url: '/script.cgi',
type: 'POST'
dataType: 'json',
success: function(result) {
// result will be a javascript object
}
});
But obviously the proper thing to do is to fix your server side script to return the proper Content-Type response header.
According to ajax() in jQuery API Documentation under dataType:
dataType (default: Intelligent Guess (xml, json, script, or
html))Type: String The type of data that you're expecting back from
the server. If none is specified, jQuery will try to infer it based
on the MIME type of the response (an XML MIME type will yield XML, in
1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
Hope this helps.
You should specify dataType to be json in your $.ajax call. dataType is the MIME you are expecting to receive from the server. contentType is what the server is expecting from you.

How can I access responseText of a jqXHR object from a successfull AJAX call?

I have following ajax call in my JavaScript code
url = 'http://news.ycombinator.com/?callback=?';
$.ajax({url:url ,async:!1,dataType:'script', complete:function(result)
{alert(JSON.stringify(result));}
});
Following is printed out in alert.
{'readyState':4, status:200, statusText:'success'}
It doesn't have responseText.But still, in the chrome console I can see all of the return HTML data of ycombinator page.How can I access this text?
On the other hand if I change the url variable to a url which returns a valid json object like following,
urll = 'http://gdata.youtube.com/feeds/api/videos?q=basshunter&format=5&max-results=5&v=2&alt=jsonc';
$.ajax({url:urll ,async:!1, complete:function(result)
{alert(JSON.stringify(result));}
});
this returns all of the responseText as expected.
One thing to note is if I don't point the url to a valid JSON returning url as in first case, I have to provide option dataType:'script'(or JSON).Otherwise it will throw a cross-domain request error.In second case it didn't throw any cross-domain error even if I didn't specify dataType.
Replace your complete callback with success. Success callback executed when ajax request completed successfully.
Also in your dataType use "json" instead of "script"
if you use "script" in dataType it will return like "{\"key\":\"value\"}".
if you use "json" in dataType it will return like {"key":"value"}.

Categories