jQuery.get( url [, data ] [, success ] [, dataType ] )Returns: jqXHR
Description: Load data from the server using a HTTP GET request.
-
version added: 1.0jQuery.get( url [, data ] [, success ] [, dataType ] )
-
url
A string containing the URL to which the request is sent.
-
data
A plain object or string that is sent to the server with the request.
-
success
A callback function that is executed if the request succeeds. Required if
dataType
is provided, but you can usenull
orjQuery.noop
as a placeholder. -
dataType
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
-
-
version added: 1.12-and-2.2jQuery.get( [settings ] )
-
settings
A set of key/value pairs that configure the Ajax request. All properties except for
url
are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a complete list of all settings. The type option will automatically be set toGET
.
-
This is a shorthand Ajax function, which is equivalent to:
The success
callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.
As of jQuery 1.5, the success
callback function is also passed a «jqXHR» object (in jQuery 1.4, it was passed the XMLHttpRequest
object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR
and textStatus
parameters passed to the success callback are undefined.
Most implementations will specify a success handler:
1 2 3 4 |
|
This example fetches the requested HTML snippet and inserts it on the page.
The jqXHR Object
As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the XMLHTTPRequest
object. This jQuery XHR object, or «jqXHR,» returned by $.get()
implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done()
(for success), jqXHR.fail()
(for error), and jqXHR.always()
(for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax()
documentation.
The Promise interface also allows jQuery’s Ajax methods, including $.get()
, to chain multiple .done()
, .fail()
, and .always()
callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Deprecation Notice
The jqXHR.success()
, jqXHR.error()
, and jqXHR.complete()
callback methods are removed as of jQuery 3.0. You can use jqXHR.done()
, jqXHR.fail()
, and jqXHR.always()
instead.
Additional Notes:
- Due to browser security restrictions, most «Ajax» requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
-
If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method. Alternatively, as of jQuery 1.5, the
.error()
method of thejqXHR
object returned by jQuery.get() is also available for error handling. - Script and JSONP requests are not subject to the same origin policy restrictions.
Examples:
Request the test.php page, but ignore the return results.
Request the test.php page and send some additional data along (while still ignoring the return results).
1 |
|
Pass arrays of data to the server (while still ignoring the return results).
1 |
|
Alert the results from requesting test.php (HTML or XML, depending on what was returned).
1 2 3 |
|
Alert the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned).
1 2 3 4 |
|
Get the test.php page contents, which has been returned in json format (<?php echo json_encode( array( «name»=>»John»,»time»=>»2pm» ) ); ?>), and add it to the page.
1 2 3 4 5 |
|
Get another page on the same domain. Outputs to console both the data returned and the type of data returned.
1 2 3 4 5 6 |
|
Содержание
- jQuery.get()
- jQuery.get( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR
- version added: 1.0 jQuery.get( url [, data ] [, success ] [, dataType ] )
- version added: 1.12-and-2.2 jQuery.get( [settings ] )
- The jqXHR Object
- jQuery.get()
- jQuery.get( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR
- version added: 1.0 jQuery.get( url [, data ] [, success ] [, dataType ] )
- version added: 1.12-and-2.2 jQuery.get( [settings ] )
- The jqXHR Object
- jQuery.ajax()
- jQuery.ajax( url [, settings ] ) Returns: jqXHR
- version added: 1.5 jQuery.ajax( url [, settings ] )
- version added: 1.0 jQuery.ajax( [settings ] )
- The jqXHR Object
- Callback Function Queues
- Data Types
- Sending Data to the Server
- Advanced Options
jQuery.get()
jQuery.get( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR
Description: Load data from the server using a HTTP GET request.
version added: 1.0 jQuery.get( url [, data ] [, success ] [, dataType ] )
version added: 1.12-and-2.2 jQuery.get( [settings ] )
This is a shorthand Ajax function, which is equivalent to:
The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.
As of jQuery 1.5, the success callback function is also passed a «jqXHR» object (in jQuery 1.4, it was passed the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR , in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.
Most implementations will specify a success handler:
This example fetches the requested HTML snippet and inserts it on the page.
The jqXHR Object
As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or «jqXHR,» returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.
The Promise interface also allows jQuery’s Ajax methods, including $.get() , to chain multiple .done() , .fail() , and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.
Источник
jQuery.get()
jQuery.get( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR
Description: Load data from the server using a HTTP GET request.
version added: 1.0 jQuery.get( url [, data ] [, success ] [, dataType ] )
version added: 1.12-and-2.2 jQuery.get( [settings ] )
This is a shorthand Ajax function, which is equivalent to:
The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.
As of jQuery 1.5, the success callback function is also passed a «jqXHR» object (in jQuery 1.4, it was passed the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR , in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.
Most implementations will specify a success handler:
This example fetches the requested HTML snippet and inserts it on the page.
The jqXHR Object
As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or «jqXHR,» returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.
The Promise interface also allows jQuery’s Ajax methods, including $.get() , to chain multiple .done() , .fail() , and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.
Источник
jQuery.ajax()
jQuery.ajax( url [, settings ] ) Returns: jqXHR
Description: Perform an asynchronous HTTP (Ajax) request.
version added: 1.5 jQuery.ajax( url [, settings ] )
version added: 1.0 jQuery.ajax( [settings ] )
Data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL.
When data is an object, jQuery generates the data string from the object’s key/value pairs unless the processData option is set to false . For example, < a: «bc», d: «e,f» >is converted to the string «a=bc&d=e%2Cf» . If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, < a: [1,2] >becomes the string «a%5B%5D=1&a%5B%5D=2» with the default traditional: false setting.
When data is passed as a string it should already be encoded using the correct encoding for contentType , which by default is application/x-www-form-urlencoded .
In requests with dataType: «json» or dataType: «jsonp» , if the string contains a double question mark ( ?? ) anywhere in the URL or a single question mark ( ? ) in the query string, it is replaced with a value generated by jQuery that is unique for each copy of the library on the page (e.g. jQuery21406515378922229067_1479880736745 ).
An object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:
If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback.
In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.
The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use. If less common options are required, though, $.ajax() can be used more flexibly.
At its simplest, the $.ajax() function can be called with no arguments:
Note: Default settings can be set globally by using the $.ajaxSetup() function.
This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, you can implement one of the callback functions.
The jqXHR Object
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser’s native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.
As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header:
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
- jqXHR.done(function( data, textStatus, jqXHR ) <>);
An alternative construct to the success callback option, refer to deferred.done() for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) <>);
An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) < >); (added in jQuery 1.6)
An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.
In response to a successful request, the function’s arguments are the same as those of .done() : data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail() : the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) <>, function( jqXHR, textStatus, errorThrown ) <>);
Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.
Deprecation Notice: The jqXHR.success() , jqXHR.error() , and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done() , jqXHR.fail() , and jqXHR.always() instead.
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
For backward compatibility with XMLHttpRequest , a jqXHR object will expose the following properties and methods:
- readyState
- responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
- status
- statusText (may be an empty string in HTTP/2)
- abort( [ statusText ] )
- getAllResponseHeaders() as a string
- getResponseHeader( name )
- overrideMimeType( mimeType )
- setRequestHeader( name, value ) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
- statusCode( callbacksByStatusCode )
No onreadystatechange mechanism is provided, however, since done , fail , always , and statusCode cover all conceivable requirements.
Callback Function Queues
The beforeSend , error , dataFilter , success and complete options all accept callback functions that are invoked at the appropriate times.
As of jQuery 1.5, the fail and done , and, as of jQuery 1.6, always callback hooks are first-in, first-out managed queues, allowing for more than one callback for each hook. See Deferred object methods, which are implemented internally for these $.ajax() callback hooks.
The callback hooks provided by $.ajax() are as follows:
- beforeSend callback option is invoked; it receives the jqXHR object and the settings object as parameters.
- error callback option is invoked, if the request fails. It receives the jqXHR , a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: «abort», «timeout», «No Transport».
- dataFilter callback option is invoked immediately upon successful receipt of response data. It receives the returned data and the value of dataType , and must return the (possibly altered) data to pass on to success .
- success callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the jqXHR object.
- Promise callbacks — .done() , .fail() , .always() , and .then() — are invoked, in the order they are registered.
- complete callback option fires, when the request finishes, whether in failure or success. It receives the jqXHR object, as well as a string containing the success or error code.
Data Types
Different types of response to $.ajax() call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.
The available data types are text , html , xml , json , jsonp , and script .
If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.
If xml is specified, the response is parsed using jQuery.parseXML before being passed, as an XMLDocument , to the success handler. The XML document is made available through the responseXML property of the jqXHR object.
If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
If script is specified, $.ajax() will execute the JavaScript that is received from the server before passing it on to the success handler as a string.
If jsonp is specified, $.ajax() will automatically append a query string parameter of (by default) callback=? to the URL. The jsonp and jsonpCallback properties of the settings passed to $.ajax() can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function. $.ajax() will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the $.ajax() success handler.
For more information on JSONP, see the original post detailing its use.
Sending Data to the Server
By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.
Advanced Options
The global option prevents handlers registered using .ajaxSend() , .ajaxError() , and similar methods from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with .ajaxSend() if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to false . See the descriptions of these methods below for more details.
If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username and password options.
Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using $.ajaxSetup() rather than being overridden for specific requests with the timeout option.
By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache to false . To cause the request to report failure if the asset has not been modified since the last request, set ifModified to true .
The scriptCharset allows the character set to be explicitly specified for requests that use a
Источник
This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.
Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:
$.ajax({ url: 'does-not-exist.php', success: function(returnData){ var res = JSON.parse(returnData); }, error: function(xhr, status, error){ var errorMessage = xhr.status + ': ' + xhr.statusText alert('Error - ' + errorMessage); } });
If you look at the code above, you will notice that I have two functions:
- success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
- error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.
The Ajax error function has three parameters:
- jqXHR
- textStatus
- errorThrown
In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:
- status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
- statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.
Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.
JQuery 3.0: The error, success and complete callbacks are deprecated.
Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.
An example of done and fail being used:
$.ajax("submit.php") .done(function(data) { //Ajax request was successful. }) .fail(function(xhr, status, error) { //Ajax request failed. var errorMessage = xhr.status + ': ' + xhr.statusText alert('Error - ' + errorMessage); })
Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.
Hopefully, you found this tutorial to be useful.
Learn how to use the jQuery .get() method to make AJAX calls.
What you will learn ?
I’m going to show how to fetch contents from text files and database by using this method.
The full codes can be downloaded by the link given at the end of this tutorial.
In short: you will master this method.
The jQuery Get function is used to make AJAX calls and can be helpful to update a web page with partial page reloading. It uses HTTP GET method to initiate an AJAX request and fetch data from the external pages.
Let us understand all about this method in details.
Syntax of jQuery Get Method
jQuery.get( url [, data ] [, success ] [, dataType ] )
Parameters:
Name | Value |
---|---|
url | The URL to where the AJAX request of HTTP GET type is made. It is the Required parameter. |
Data | Optional parameter – the key-value pairs that will be send with the AJAX request. Eg {sport: “football”,player: “Cristiano Ronaldo”} |
success(result,status,xhr) | Optional Parameter – the function to call when the AJAX request is successful. All 3 parameters are optional. The result parameter will get the AJAX response. |
dataType | The Optional Parameter – the type of data returned from the AJAX response. It can be xml, json, script, text, or html |
jQuery Get Method to Fetch Contents of a Text File
Let’s fetch a text file’s content with the jQuery Get method:
<button id="loadTextFile">Try</button> <div id="textData"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> $(document).ready(function () { $.get("file.txt", function (result, status, xhr) { $("#textData").html(result); }); }); </script>
The jQuery .get() method makes the AJAX call to the file.txt and shows it’s contents inside a div called textData.
Not just a text file, the above code can be use to fetch contents of other file types, like HTML, JSON, XML, etc.
Capturing jQuery Get Error
Use .fail() to capture any errors that come during the AJAX request.
See the below code:
<button id="loadNoTextFile">Try</button> <div id="textNoData"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> $(document).ready(function () { $("#loadNoTextFile").click(function (e) { $.get("no-file.txt", function (result, status, xhr) { $("#textNoData").html(result); }).fail(function (xhr, status, error) { $("#textNoData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) }); }); </script>
In the above code, when trying to access a non-existing file, the .fail() function is called and it shows the message – Result: error Not Found 404 Not Found.
jQuery Get method to Fetch Data from Database
With the jQuery Get method you can make AJAX calls to a server page also. This server page in turn fetches data from the Database and returns it back as an AJAX response.
Let us create a small demo application in ASP.NET Web Forms to understand this feature.
jQuery Get Demo Application
There are 2 pages – one is HTML and other is .ASPX. The HTML page has 3 controls – 2 selects and a button.
On clicking the button, the 2 ‘select’ control values are passed to the .ASPX page by the jQuery Get method.
The HTML page code:
<div id="message"></div> <select id="sportSelect"> <option value="Select">Select Sports</option> <option value="Tennis">Tennis</option> <option value="Football">Football</option> <option value="Cricket">Cricket</option> </select> <select id="playerSelect"> <option value="Select">Select Sports Person</option> <option value="Maria Sharapova">Maria Sharapova</option> <option value="Cristiano Ronaldo">Cristiano Ronaldo</option> <option value="Sachin Tendulkar">Sachin Tendulkar</option> </select> <button id="loadDatabase">Try</button> <div id="dbData"></div>
The jQuery Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> $("#loadDatabase").click(function (e) { $.get("result.aspx", { sport: $("#sportSelect").val(), player: $("#playerSelect").val() }, function (result, status, xhr) { $("#dbData").html(result); }).fail(function (xhr, status, error) { $("#dbData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) }); }); </script>
In the .ASPX page, I get these 2 select control values, using Request.QueryString method.
I then fetch the respective data from the database.
Once I have the data from the DB then I use the Response.Write method to send it to the jQuery Get method as AJAX response.
The .ASPX page code:
List<MyDataBase> myDataBase; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { LoadData(); SearchDatabase(); } } void SearchDatabase() { string sport = Request.QueryString["sport"]; string player = Request.QueryString["player"]; try { string information = myDataBase.FirstOrDefault(x => x.sport == sport & x.player == player).information; Response.Write(information); Response.End(); } catch (Exception ex) { Response.Write("NO DATA"); Response.End(); } } void LoadData() { myDataBase = new List<MyDataBase>(); myDataBase.Add(new MyDataBase() { sport = "Tennis", player = "Maria Sharapova", information = "Maria Sharapova is a...}); myDataBase.Add(new MyDataBase() { sport = "Football", player = "Cristiano Ronaldo", information = "Cristiano Ronaldo is a..." }); myDataBase.Add(new MyDataBase() { sport = "Cricket", player = "Sachin Tendulkar", information = "Sachin Tendulkar is a..." }); } class MyDataBase { public string sport { get; set; } public string player { get; set; } public string information { get; set; } }
Instead of a Database, I have used a list type object which contains some dummy data. The ‘LoadData()’ function adds these dummy data to the list.
Download the source codes and check the download link:
DOWNLOAD
Conclusion
You are now ready to use the .get() method to make any type of AJAX feature in your website. Also check other similar topics in jQuery AJAX:
- 1. jQuery AJAX Events
- 2. jQuery AJAX
- 3. jQuery Load
- 4. jQuery Post
In this post we will show you how to jQuery ajax error function when Ajax decision passing information to a page that then returns a worth(value).
I have retrieved the self-made decision from the page however I even have coded it so it raises an erreo(bug) within the your call page(example url: "data.php"
). however do we retrieve that error from the jquery? how we get jQuery Ajax Error Handling Function hear is the solution of ajax error function.
this jQuery ajax error function is very basic and easy to use with your ajax call.
$.ajax({ type: "POST", url: "data.php", data: { search: '1',keyword : 'somedata'}, cache: false, success: function(data) { // success alert message alert(data); }, error: function (error) { // error alert message alert('error :: ' + eval(error)); } });
jQuery ajax error function using jqXHR
jQuery ajax error function using jqXHR in this function we can get different type ajax error like 404 page error, 500 Internal Server error, Requested JSON parse, Time out error.
$.ajax({ type: "POST", url: "data.php", data: { search: '1',keyword : 'somedata'}, cache: false, success: function(data) { // success alert message alert(data); }, error: function (jqXHR, exception) { var error_msg = ''; if (jqXHR.status === 0) { error_msg = 'Not connect.n Verify Network.'; } else if (jqXHR.status == 404) { // 404 page error error_msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { // 500 Internal Server error error_msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { // Requested JSON parse error_msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { // Time out error error_msg = 'Time out error.'; } else if (exception === 'abort') { // request aborte error_msg = 'Ajax request aborted.'; } else { error_msg = 'Uncaught Error.n' + jqXHR.responseText; } // error alert message alert('error :: ' + error_msg); }, });
Parameters for jQuery ajax error function with jqXHR
Parameters for jQuery ajax error function with jqXHR for It actually an error object which is looks like this.
jQuery ajax error function with an validation error
jQuery ajax error function with an validation error :: If we want to inform(get error message) in frontend about an validation error try this method.
$.ajax({ type: "POST", url: "data.php", data: { search: '1',keyword : 'somedata'}, cache: false, success: function(data, textStatus, jqXHR) { console.log(data.error); } });
jQuery.get()
JQ Home <<
Ajax <<
jQuery.get()
Asynchronous HTTP (Ajax) load request.
Description
The jQuery.get()
Ajax method, allows us to load data from the server, using a HTTP GET request.
Shorthand version $.get()
- Browsers operate the ‘same origin policy’, which means a request can not successfully retrieve data from a different domain, subdomain, or protocol. jQuery ‘Ajax’ requests are subject to this security restriction,
the exceptions being requests made with a datatype of ‘script’ or ‘jsonp’. - The
jQuery.get()
method returns ajqXHR
object which is a superset of the browser’s nativeXMLHttpRequest
object. ThejqXHR
object implements the
Promise
interface, giving it all the properties, methods, and behavior of a Promise. See the lesson on theDeferred
object for
details of this. For standardization with the theDeferred
object, thejqXHR
object also providesdone()
,fail()
andalways()
methods. These methods take a function argument that is called when thejQuery.get()
request terminates and the function receives the same arguments as the same-namedsuccess()
,error()
andcomplete()
setting callbacks respectively. This allows assignment of multiple callbacks for a single request as well as assigning callbacks after the request has completed. For completed requests, the callback is fired immediately.- It should be noted that the
success()
,error()
andcomplete()
callbacks of thejqXHR
object are deprecated from use on request completion from jQuery 1.8 and removed in jQuery 3.0. This is for completion processing only and the Ajax settings will still have these values. Best practice is to usedone()
,fail()
andalways()
methods on request completion to future proof code or use the newthen()
andcatch()
methods for Promises/A+ compliance.
- It should be noted that the
- A
jqXHR
object will expose the following properties and methods for backward compatibility with theXMLHttpRequest
object:
jqXHR Object Description Methods abort() Cancels the currently executing request. getAllResponseHeaders() Returns a string containing the names and value of all response headers. getResponseHeader(name) Returns the value of the specified response headers. .overrideMimeType() Used in the beforeSend() callback function, to modify the response content-type header. setRequestHeader(name, value) Set a request header using the specified name and value. Properties readyState An integer indicating the current state of the request. responseText Underlying request responded with text. responseXML Underlying request responded with xml. status Response status code returned from the server. statusText Status text message returned by the response.
Syntax
Signature | Description |
---|---|
jQuery.get( url [, data] [, function(data, textStatus, jqXHR)] [, dataType] ) |
Load data from the server, using a HTTP GET request. |
jQuery.get( settings ) |
Load data from the server using a HTTP GET request, passing some request settings. |
Parameters
Parameter | Description | Type |
---|---|---|
url |
A string containing the URL to send the request to. | String |
data |
An object or string sent to the server with the request.
|
String orPlainObject |
function(data, textStatus, jqXHR) |
A callback function executed when the request succeeds. | Function |
dataType |
The type of data expected from the server.
|
String |
settings |
Default settings can be set globally by using the jQuery.ajaxSetup() method but the settings as described in jQuery.ajax( settings ) can be useful for individual Ajax requests. |
Various dependant upon settings parameter. |
Return
A jqXHR
object.
jQuery.get( url [, data] [, function( data, textStatus, jqXHR)] [, dataType] )
ExamplesAjax << Top
Load data from the server, using a HTTP GET request.
This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax()
method as follows:
$.ajax({
type: 'GET',
url: url
,
data: data
,
dataType: dataType
,
});
In the example below when we press the left button the first time we use the jQuery.get()
method in its simplest form just using a url and output some messages dependant upon request success.
When we press the right button the first time we use the jQuery.get()
method with a url and a success handler and output some messages dependant upon request success.
$(function(){
$('#btn1').one('click', function(){
$.get( "../../../js/get1.js" )
.done(function() { $('#div1').append('Request succeeded! <br>'); })
.fail(function() { $('#div1').append('Request failed! <br>'); })
.always(function() { $('#div1').append('Request ended! <br><br>');
});
});
$('#btn2').one('click', function(){
$.get( "../../../js/get1.js", function(data, textStatus, jqXHR) {
$('#div1').append('The request was a success! <br>');
})
.done(function() { $('#div1').append('Request succeeded! <br>'); })
.fail(function() { $('#div1').append('Request failed! <br>'); })
.always(function() { $('#div1').append('Request ended! <br><br>');
});
});
});
/*
* The code for the external Javascript file called from $.ajax() (url: "../../../js/get1.js")
* is shown below.
*/
$(function(){
var someText = 'Passing some text. ';
$('#div1').append('Message from get1.js: ' + someText + '<br>');
});
div1. Some initial text.
jQuery.get( settings )
ExamplesAjax << Top
Load data from the server using a HTTP GET request, passing some request settings.
This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax()
method as follows:
$.ajax({
type: 'GET',
url: url
,
dataType: dataType
,
error: callback
success: callback
});
In the example below when we press the left button the first time we use the jQuery.get()
using a url, dataType and error and success parameters and output a fail messages as the url doesn’t exist.
In the example below when we press the right button the first time we use the jQuery.get()
using a url, dataType and error and success parameters and output a success message and the contents of the retrieved url.
$(function(){
$('#btn10').one('click', function(){
$.get({
url: "../../../js/get22.js",
dataType: "script",
error: function() {
$('#div2').append('The request failed! <br><br>');
},
success: function() {
$('#div2').append('The request was a sucesss! <br><br>');
}
});
});
$('#btn11').one('click', function(){
$.get({
url: "../../../js/get2.js",
dataType: "script",
error: function() {
$('#div2').append('The request failed! <br><br>');
},
success: function() {
$('#div2').append('The request was a sucesss! <br><br>');
}
});
});
/*
* The code for the external Javascript file called from $.ajax() (url: "../../../js/get2.js")
* is shown below.
*/
$(function(){
var someText = 'Passing some text. ';
$('#div2').append('Message from get2.js: ' + someText + '<br>');
});
div2. Some initial text.
Related Tutorials
jQuery Advanced Tutorials — Lesson 9 — Ajax Shorthand Methods
- Связанные категории:
-
Ajax
» Shorthand Methods
Returns: jqXHR
Загружает данные с сервера, используя HTTP GET запрос.
-
version added: 1.0jQuery.get( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
url
Тип: строка
Адрес, на который отправляется запрос.data
Тип: объект или строка
Данные, отправляемые на сервер в виде объекта (ключ:значение) или строки.success(data, textStatus, jqXHR)
Тип: функция
Функция, вызываемая при успешном завершении Ajax запроса.dataType
Тип: строка
Тип данных, ожидаемых в качестве ответа от сервера. По умолчанию jQuery определит сам.
$.get() эквивалетна:
$.ajax({ url: url, data: data, success: success, dataType: dataType });
Функция обратного вызова success, принимает ответ от сервера, который может быть в виде XML, строки, JavaScript файла или объекта JSON, в зависимости от MIME типа ответа. Это значение так же помещается в статус ответа.
Начиная с версии 1.5, функция обратного вызова success принимает объект jqXHR (в ранних версиях объект XMLHttpRequest). В случае использования JSONP, значение второго и третьего параметры функции будет неопределённым (undefined), т.к. при кросс-доменных GET запросах, объект XHR не используется.
$.get('ajax/test.html', function(data) { $('.result').html(data); alert('Загрузка завершена.'); });
Данный код делает запрос к HTML файлу и выводит его содержимое.
Объект jqXHR
Начиная с версии 1.5, $.get() возвращает объект jqXHR, реализующий интерфейс deferred, что позволяет задавать дополнительные обработчики. Помимо стандартных для объекта deferred методов .done(), .fail() и .then(), с помощью которых можно устанавливать обработчики, в jqXHR реализованы их копии: .success(), .error() и .complete(). Это сделано для соответствия привычным названиям методов, с помощью которых устанавливаются обработчики выполнения ajax-запросов.
// запускаем ajax-запрос, устанавливаем обработчики событий. // Возвращаемые методом $.get объект сохраним в переменной jqxhr для дальнейшего использования var jqxhr = $.get("example.php", function() { alert("success"); }) .done(function() { alert("second success"); }) .fail(function() { alert("error"); }) .always(function() { alert("finished"); }); // установим еще один обработчик завершения запроса jqxhr.always(function(){ alert("second finished"); });
Заметка об устаревших методах
Функции обратного действия, введённые в jQuery 1.5 устарени в версии 1.8. Вместо jqXHR.success(), jqXHR.error() и jqXHR.complete() теперь следует использовать jqXHR.done(), jqXHR.fail() и jqXHR.always().
Примеры
Сделать запрос к test.php, игнорируя ответ:
$.get("test.php");
Сделать запрос к test.php, передать данные, игнорировать ответ:
$.get("test.php", { name: "John", time: "2pm" } );
Передать массив данных на сервер, игнорируя ответ:
$.get("test.php", { 'choices[]': ["Jon", "Susan"]} );
Обработать ответ от сервера (HTML или XML в зависимости от того, что пришло):
$.get("test.php", function(data) { alert("Data Loaded: " + data); });
Сделать запрос к test.cgi, предать данные, обработать ответ (HTML или XML в зависимости от того, что пришло):
$.get("test.cgi", { name: "John", time: "2pm" }) .done(function(data) { alert("Data Loaded: " + data); });
Получить от сервера ответ в JSON формате и вывести его на страницу (<?php echo json_encode(array(«name»=>»John»,»time»=>»2pm»)); ?>):
$.get("test.php", function(data) { $('body').append( "Name: " + data.name ) // John .append( "Time: " + data.time ); // 2pm }, "json");
Связанные уроки:
-
Желтые стикеры с помощью AJAX, PHP и jQuery
Сегодня мы создаем систему управления желтыми стикерами.
-
Что нового в jQuery 1.5?
Совсем недавно, как и было обещано, группа разработчиков библиотеки jQuery выпустила новую версию своего продукта. Я попытаюсь вам рассказать о фитчах, которые вошли в свежий релиз.