Jquery post error handling

jQuery.post() jQuery.post( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR Description: Send data to the server using a HTTP POST request. version added: 1.0 jQuery.post( url [, data ] [, success ] [, dataType ] ) version added: 1.12-and-2.2 jQuery.post( [settings ] ) This is a shorthand Ajax function, […]

Содержание

  1. jQuery.post()
  2. jQuery.post( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR
  3. version added: 1.0 jQuery.post( url [, data ] [, success ] [, dataType ] )
  4. version added: 1.12-and-2.2 jQuery.post( [settings ] )
  5. The jqXHR Object
  6. jQuery.post()
  7. jQuery.post( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR
  8. version added: 1.0 jQuery.post( url [, data ] [, success ] [, dataType ] )
  9. version added: 1.12-and-2.2 jQuery.post( [settings ] )
  10. The jqXHR Object
  11. jQuery.ajax()
  12. jQuery.ajax( url [, settings ] ) Returns: jqXHR
  13. version added: 1.5 jQuery.ajax( url [, settings ] )
  14. version added: 1.0 jQuery.ajax( [settings ] )
  15. The jqXHR Object
  16. Callback Function Queues
  17. Data Types
  18. Sending Data to the Server
  19. Advanced Options

jQuery.post()

jQuery.post( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR

Description: Send data to the server using a HTTP POST request.

version added: 1.0 jQuery.post( url [, data ] [, success ] [, dataType ] )

version added: 1.12-and-2.2 jQuery.post( [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 or a text string 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).

Most implementations will specify a success handler:

This example fetches the requested HTML snippet and inserts it on the page.

Pages fetched with POST are never cached, so the cache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

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 $.post() 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.post()

jQuery.post( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR

Description: Send data to the server using a HTTP POST request.

version added: 1.0 jQuery.post( url [, data ] [, success ] [, dataType ] )

version added: 1.12-and-2.2 jQuery.post( [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 or a text string 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).

Most implementations will specify a success handler:

This example fetches the requested HTML snippet and inserts it on the page.

Pages fetched with POST are never cached, so the cache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

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 $.post() 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:

  1. beforeSend callback option is invoked; it receives the jqXHR object and the settings object as parameters.
  2. 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».
  3. 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 .
  4. success callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the jqXHR object.
  5. Promise callbacks — .done() , .fail() , .always() , and .then() — are invoked, in the order they are registered.
  6. 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

Источник

# Handling HTTP Response Codes with $.ajax()

In addition to .done, .fail and .always promise callbacks, which are triggered based on whether the request was successful or not, there is the option to trigger a function when a specific HTTP Status Code (opens new window) is returned from the server. This can be done using the statusCode parameter.

As official jQuery documentation states:

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.

# Using Ajax to Submit a Form

Sometimes you may have a form and want to submit it using ajax.

Suppose you have this simple form —

The following jQuery code can be used (within a $(document).ready call) —

Explanation

  • var $form = $(this) — the form, cached for reuse
  • $('#ajax_form').submit(function(event){ — When the form with ID
    «ajax_form» is submitted run this function and pass the event as a
    parameter.
  • event.preventDefault(); — Prevent the form from submitting normally (Alternatively we can use return false after the ajax({}); statement, which will have the same effect)
  • url: $form.attr('action'), — Get the value of the form’s «action» attribute and use it for the «url» property.
  • data: $form.serialize(), — Converts the inputs within the form into a string suitable for sending to the server. In this case it will return something like «name=Bob&email=bob@bobsemailaddress.com»

# All in one examples

Ajax Get:

Solution 1:

Solution 2:

Ajax Load: Another ajax get method created for simplcity

.load can also be called with additional data. The data part can be provided as string or object.

If .load is called with a callback method, the request to the server will be a post

Ajax Post:

Solution 1:

Solution 2:

Ajax Post JSON:

Ajax Get JSON:

Solution 1:

Solution 2:

# Ajax File Uploads

# 1. A Simple Complete Example

We could use this sample code to upload the files selected by the user every time a new file selection is made.

Now let’s break this down and inspect it part by part.

# 2. Working With File Inputs

This MDN Document ( Using files from web applications ) (opens new window) is a good read about various methods on how to handle file inputs. Some of these methods will also be used in this example.

Before we get to uploading files, we first need to give the user a way to select the files they want to upload. For this purpose we will use a file input. The multiple property allows for selecting more than one files, you can remove it if you want the user to select one file at a time.

We will be using input’s change event to capture the files.

Inside the handler function, we access the files through the files property of our input. This gives us a FileList (opens new window), which is an array like object.

# 3. Creating and Filling the FormData

In order to upload files with Ajax we are going to use FormData (opens new window).

FileList (opens new window) we have obtained in the previous step is an array like object and can be iterated using various methods including for loop (opens new window), for…of loop (opens new window) and jQuery.each (opens new window). We will be sticking with the jQuery in this example.

We will be using the append method (opens new window) of FormData to add the files into our formdata object.

We can also add other data we want to send the same way. Let’s say we want to send some personal information we have received from the user along with the files. We could add this this information into our formdata object.

# 4. Sending the Files With Ajax

We set processData and contentType properties to false. This is done so that the files can be send to the server and be processed by the server correctly.

# Ajax Abort a Call or Request

//kill the request

# Sending JSON data

jQuery makes handling jSON responses painless, but a bit more work is required when a given request wishes you to send data in JSON format:

Observe that we’re specifying the correct contentType (opens new window) for the data we’re sending; this is a good practice in general and may be required by the API you’re posting to — but it also has the side-effect of instructing jQuery not to perform the default conversion of %20 to +, which it would do if contentType was left at the default value of application/x-www-form-urlencoded. If for some reason you must leave contentType set to the default, be sure to set processData to false to prevent this.

The call to JSON.stringify (opens new window) could be avoided here, but using it allows us to provide the data in the form of a JavaScript object (thus avoiding embarrassing JSON syntax errors such as failing to quote property names).

# Syntax

  • var jqXHR = $.ajax( url [,settings] )
  • var jqXHR = $.ajax( [settings] )
  • jqXHR.done(function( data, textStatus, jqXHR ) {});
  • jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  • jqXHR.always(function( jqXHR ) {});

# Parameters

Parameter Details
url Specifies the URL to which the request will be sent
settings an object containing numerous values that affect the behavior of the request
type The HTTP method to be used for the request
data Data to be sent by the request
success A callback function to be called if the request succeeds
error A callback to handle error
statusCode An object of numeric HTTP codes and functions to be called when the response has the corresponding code
dataType The type of data that you’re expecting back from the server
contentType Content type of the data to sent to the server. Default is «application/x-www-form-urlencoded; charset=UTF-8»
context Specifies the context to be used inside callbacks, usually this which refers to the current target.

AJAX stands for Asynchronous JavaScript and XML. AJAX allows a webpage to perform an asynchronous HTTP (AJAX) request to the server and receive a response, without needing to reload the entire page.

When discussing errors in jQuery most people think of Ajax methods. Indeed this is a common source of error but limiting ourselves to just Ajax is not enough. We need to have a solid means of capturing errors just like we do in PHP. As a matter of fact we want all JavaScript errors to write to the same error file if possible. I generally like to add some format that will tell me which are client-side and which are server-side errors.

Although JavaScript now supports the try / catch block I see little reason to us it. The approach I favor is the window.onerror() event. This appears to be a viable global capture mechanism for errors that occur in the browser, i.e., HTML / JavaScript / jQuery. The onerror event is now supported by all major browsers (IE, Firefox, Safari, Chrome, and Opera).

The onerror() event handler provides three arguments to identify the exact nature of an error:

  1. msg – The same error message that the browser would display,
  2. url – The file in which the error occurred,
  3. line – The line number in the given URL that caused the error.

My preference is to create a separate ‘js’ file for the sole purpose of managing client-side errors. This way I can place it in each Controller in a project and all pages are covered. The ‘js’ script file looks something like this:

          window.onerror = myErrHandler;
 
          function myErrHandler(msg, url, line){
               var str =’myJQueryErrHandler fired – ‘+msg+’ [‘+url+’] line# ‘+line;
               var thisErr = {‘errorMsg’: str};
               var url2 = ‘../resources/ajaxPak/ajaxLog.php’;
               $.post(url2, thisErr);
               return true;
          }
 

The first thing I do is override the onerror() event sending it to ‘myErrHandler’ function. Note that the function receives the standard ‘onerror’ event arguments. I start my error message (str) with a client-side identifier – ‘myJQueryErrHandler’. In this way I can quickly identify these errors that are client-side. For those of you who want more options, perhaps separate file for client-side, see my session on Using the PHP error_log function. Then I create the arguments that will be part of my Ajax call (post). My preference in jQuery, in general, is to use the shorthand methods that are available to me. Here I make a use the jQuery post() method to send the error to the ‘ajaxLog’ PHP file. Note that this is a fire and forget approach. That is, I am not worried that my post does not always succeed, through testing, I know it will work most of the time.

The PHP file for logging the error is very simple. Looking something like this:

          <?php
               $agent=$_SERVER[‘HTTP_USER_AGENT’];
               $Msg1 = $_POST[‘errorMsg’];
               $Msg2 = $Msg1.”n”.’ ***** USER AGENT: ‘.$agent.” *****n”;
               error_log($Msg2,0);
          ?>
 

Here unlike my PHP error logs I want to add information on the client’s browser and operating system to help diagnose problems. To get this information I use the $SERVER variable HTTP_USER_AGENT. My initial error message comes in the form of a POST variable with the index name defined in the Ajax call. I then concatenate the original message with the user agent information. Finally I generate a log message using PHP’s error_log function.

There are three general types of errors that you need to deal with.

Runtime Errors

Runtime errors occur when a program is being executed. JavaScript is not a compiled language, it is an interpreted language where its source code is converted to machine language a line at a time at the time of execution. If, as it is being executed, it finds that there are references to methods or variables that do not exist it will throw a runtime error. This is a very common occurrence in JavaScript. Runtime errors only affect the function in which they occur.

Example of a runtime error.

$($orderType).css(‘backgroundColor’,’yellowish’);

There are two errors in this statement. The first is the selector that is not in quotes and preceded by a dollar sign($). This will throw a runtime error. The jQuery Function is looking for a String selector, HTML, or a Callback function.

[03-Sep-2012 11:32:07] myJQueryErrHandler fired – ReferenceError: $orderType is not defined [http://localhost/JQueryProj/resources/jQueryPak/jQEffect6_SyntaxTest.js] line# 41

***** USER AGENT: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0 *****

Because the argument is not a string the jQuery Library is treating it as a variable, which it cannot find and is therefore throwing a reference error.

The second is a CSS error ‘yellowish’ that you might prefer to think of as warning in that they will not stop the processing of the web page, just a particular attribute. The actual error looks like this:

CSS Error: expected color but found ‘yellowish’. Error for parsing value for ‘background-color’. Declaration dropped.

Syntax Errors

Syntax errors, also called parsing errors, occur at interpret time for JavaScript.

When a syntax error occurs in JavaScript, the entire script file fails, though it shows as loaded, all the functionality of the file is lost. If you have other script files that successfully loaded but are dependent on the file that failed in any way you may lose additional functionality.

Example of syntax error.

$(‘#orderType’.css(‘backgroundColor’,’yellowish’);

As you can see in the example, we have omitted the closing brace ‘)’ after the selector. This resulted in the following error log being generated:

[03-Sep-2012 11:44:35] myJQueryErrHandler fired – SyntaxError: missing ) after argument list [http://localhost/JQueryProj/resources/jQueryPak/jQEffect6_S.js] line# 41

***** USER AGENT: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0 *****

That also resulted in a second error occurring when another JavaScript file (jQuery6.js) tried to access the function ‘bad’ from the file with the syntax error. As we said earlier the entire JavaScript file is unavailable when a syntax error occurs. The resulting error log (Runtime Error) would look like this:

[03-Sep-2012 11:44:49] myJQueryErrHandler fired – ReferenceError: bad is not defined [http://localhost/JQueryProj/resources/jQueryPak/jQEffect6.js] line# 51

***** USER AGENT: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0 *****

The first error is thrown when the page is loaded and the second when an attempt is made to access the function that is not available due to the first syntax error.

Note because the function ‘bad’ is not defined, no CSS error is thrown.

Logical Errors

Some logic errors in your code will NOT automatically throw an error. Instead you will get an answer or response that does not meet you requirements. For example dividing by zero does not cause an error, calling a method from a jQuery Object with no members will not cause an error, nor will calling an index out of range in a jQuery get() or eq() method. So how does one log a logic error?

One approach is to design your code to throw its own logic errors. This seems strange because if you have the foresight to create a trap for the error couldn’t you just as easily (more easily really) avoid it all together? Yes you could but could the next person who handles the code. Think regression testing. While Unit testing is too advanced for this session, there are some simple steps that you can take to protect your code from logic errors.

By now we all know that in JavaScript, the same variable can hold different types of data. This is a concept known as loose typing. So the same variable can be a string, a number, or a boolean depending on the context. This as you might imagine is a bit of a challenge for us programmers. Yep, its the forgiving nature of loose typing that makes it so easy for us to make errors. Some of this can be handled through testing, testing, testing! But where you can you should attempt to trap important logic errors.

The following are common tests we can setup to throw our own logic errors:

When predefined lists (enum like) are used to define options.

                    switch(state) {
                         :
                         case ‘WV’:
                              … code …
                              break;
                         case ‘WI’:
                              … code …
                              break;
                         case “WY’:
                              … code …
                              break;
                         default:
                              throw new Error(‘Invalid state abbreviation – ‘ + state);
                    }
 

When a specific type of object is required to be passed as an argument.

               function dateEval(dte){
                    if (dte instanceof Date) {
                         … code …
                    } else {
                         throw new Error(‘Invalid Date argument – ‘ + dte);
                    }
               }
 

When checking if an object has a specific property.

               function processObj(myObj) {
                    if (myObj.prop != null) {
                         … code …
                    } else {
                         throw new Error(‘Object property does not exist – myObj.prop’);
                    }
               }
 

When an error is trapped it might look something like this:

[03-Sep-2012 11:55:24] myJQueryErrHandler fired – Error: Invalid Date argument – ‘Wednesday, June 4, 2012’ [http://localhost/JQueryProj/resources/jQueryPak/jQEffect6.js] line# 40

***** USER AGENT: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0 *****

Do yourself a favor and create this simple error log capability. It can save you hours of scrutinizing code to little effect.

Enjoy.

Don

Время прочтения
13 мин

Просмотры 38K

Всем привет в новой записи мы с вами разберём основные функции для Ajax запросов, которые позволяют передавать информацию с сайта в PHP скрипт без перезагрузки страницы.

Для работы Ajax запросов вам нужно подключить jQuery к вашему проекту. Ссылку на jQuery вы можете найти здесь.

Данный взяты с моего сайта Prog-Time.

Стандартная отправка данных через Ajax.

$.ajax({
    url: '/index.php',         /* Куда отправить запрос */
    method: 'get',             /* Метод запроса (post или get) */
    dataType: 'html',          /* Тип данных в ответе (xml, json, script, html). */
    data: {text: 'Текст'},     /* Данные передаваемые в массиве */
    success: function(data){   /* функция которая будет выполнена после успешного запроса.  */
	     alert(data); /* В переменной data содержится ответ от index.php. */
    }
});

Отправка POST запроса через Ajax

Для отправки POST запроса используем подобный код, меняем только параметр method

$.ajax({
    url: '/index.php',
    method: 'post',
    dataType: 'html',
    data: {text: 'Текст'},
    success: function(data){
	alert(data);
    }
});

Отправка JSON данных через Ajax

Для отправки JSON данный через AJAX можно использовать только методом GET.

$.ajax({
    url: '/json.php',
    method: 'get',
    dataType: 'json',
    success: function(data){
			alert(data.text);    /* выведет "Текст" */
			alert(data.error);   /* выведет "Ошибка" */
    }
});

Запланировать выполнение JS скрипта

После выполнения данного запроса, скрипт указанный в параметре url сразу будет выполнен.

$.ajax({
    method: 'get',
    url: '/script.js',
    dataType: "script"
});

Сокращённые виды функций для Ajax запросов

$.post('/index.php', {text: 'Текст'}, function(data){
    alert(data);
});
$.get('/index.php', {text: 'Текст'}, function(data){
    alert(data);
});
$.getJSON('/json.php', function(data) {
    alert(data.text);
    alert(data.error);
});

Сокращённая версия запроса на выполнение JS скрипта

$.getScript('/script.js');

Обработка ошибок связанных с AJAX запросом

$.ajax({
    url: '/index.php',
    method: 'get',
    dataType: 'json',
    success: function(data){
	console.dir(data);
    },
    error: function (jqXHR, exception) {
	if (jqXHR.status === 0) {
		alert('Not connect. Verify Network.');
	} else if (jqXHR.status == 404) {
		alert('Requested page not found (404).');
	} else if (jqXHR.status == 500) {
		alert('Internal Server Error (500).');
	} else if (exception === 'parsererror') {
		alert('Requested JSON parse failed.');
	} else if (exception === 'timeout') {
		alert('Time out error.');
	} else if (exception === 'abort') {
		alert('Ajax request aborted.');
	} else {
		alert('Uncaught Error. ' + jqXHR.responseText);
	}
    }
});

7 Основные параметры для работы с AJAX функциями

Справочные данные взяты с сайта – https://basicweb.ru/jquery/jquery_method_ajax.php

Все параметры для отправки AJAX запросов

  • async (по умолчанию: true).Тип: Boolean.По умолчанию, все запросы отправляются асинхронно и не задерживают работу других JS скриптов (это значение true), для того чтобы ждать пока выполниться Ajax запрос – поставьте значение false.Обратите внимание, что кроссдоменные запросы и элемент, параметр dataType которого имеет значение “jsonp” не поддерживают запросы в синхронном режиме. Учтите, что используя синхронные запросы вы можете временно заблокировать браузер отключив какие-либо действия пока запрос будет активен.

  • beforeSendФункция обратного вызова, которая будет вызвана перед осуществлением AJAX запроса. Функция позволяет изменить объект jqXHR (в jQuery 1.4.х объект XMLHTTPRequest) до его отправки. Объект jqXHR это надстройка расширяющая объект XMLHttpRequest, объект содержит множество свойств и методов, которые позволяет получить более полную информацию об ответе сервера, а так же объект содержит Promise методы. Если функция beforeSend возвращает false, то AJAX запрос будет отменен. Начиная с версии jQuery 1.5 функция beforeSend будет вызываться независимо от типа запроса.

  • cache (по умолчанию: true, для dataType “script” и “jsonp” false).Тип: Boolean.Если задано значение false, то это заставит запрашиваемые страницы не кэшироваться браузером. Обратите внимание, что значение false будет правильно работать только с HEAD и GET запросами.

  • complete.Тип: FunctionjqXHR jqXHRString textStatus ).Функция, которая вызывается, когда запрос заканчивается (функция выполняется после AJAX событий “success” или “error”). В функцию передаются два параметра: jqXHR (в jQuery 1.4.х объект XMLHTTPRequest) и строка соответствующая статусу запроса (“success”“notmodified”“nocontent”“error”“timeout”“abort”, или “parsererror”). Начиная с версии jQuery 1.5 параметр complete может принимать массив из функций, которые будут вызываться по очереди.

  • contents.Тип: PlainObject.Объект состоящий из пар строка/регулярное выражение, определяющих, как jQuery будет обрабатывать (парсить) ответ в зависимости от типа содержимого. Добавлен в версии jQuery 1.5.

  • contentType (по умолчанию: “application/x-www-form-urlencoded; charset=UTF-8”).Тип: Boolean, или String.Определяет тип содержимого, которое указывается в запросе при передаче данных на сервер. С версии с jQuery 1.6 допускается указать значение false, в этом случае jQuery не передает в заголовке поле Content-Type совсем.

  • context.Тип: PlainObject.При выполнении AJAX функций обратного вызова контекстом их выполнения является объект window. Параметр context позволяет настроить контекст исполнения функции таким образом, что $( this ) будет ссылаться на определенный DOM элемент, или объект.

$.ajax({
    url: "test.html", // адрес, на который будет отправлен запрос
    context: $( ".myClass" ), // новый контекст исполнения функции
    success: function(){ // если запрос успешен вызываем функцию
        $( this ).html( "Всё ок" ); // добавляем текст в элемент с классом .myClass
    }
});
  • crossDomain (по умолчанию: false для запросов внутри того же домена, true для кроссдоменных запросов).Тип: Boolean.Если вы хотите сделать кроссдоменный запрос находясь на том же домене (например jsonp-запрос), то установите этот параметр в true. Это позволит, к примеру, сделать перенаправление запроса на другой домен с вашего сервера. Добавлен в версии jQuery 1.5.

  • data.Тип: PlainObject, или String, или Array.Данные, которые будут отправлены на сервер. Если они не является строкой, то преобразуются в строку запроса. Для GET запросов строка будет добавлена к URL. Для того, чтобы предотвратить автоматическую обработку вы можете воспользоваться параметром processData со значением false. Если данные передаются в составе объекта, то он должен состоять из пар ключ/значение. Если значение является массивом, то jQuery сериализует несколько значений с одним и тем же ключом (в зависимости от значения параметра traditional, который позволяет задействовать традиционный тип сериализации основанный на методе $.param).

  • dataFilter.Тип: FunctionString dataString type ) => Anything.Функция вызывается после успешного выполнения AJAX запроса и позволяет обработать “сырые” данные, полученные из ответа сервера. Возврат данных должен происходить сразу после их обработки. Функция принимает два аргумента: data – данные полученные от сервера в виде строки и type – тип этих данных (значение параметра dataType).

  • dataType (по умолчанию: xmljsonscript, или html ).Тип: String.Определяет тип данных, который вы ожидаете получить от сервера. Если тип данных не указан, то jQuery будет пытаться определить его на основе типа MIME из ответа (XML тип MIME приведет к получению XML, с версии jQuery 1.4 json будет давать объект JavaScriptscript будет выполнять скрипт, а все остальное будет возвращено в виде строки).Основные типы (результат передается в качестве первого аргумента в функцию обратного вызова success):

    • “xml” – возвращает XML документ, который может быть обработан с помощью jQuery.

    • “html” – возвращает HTML как обычный текст, теги <script> будут обработаны и выполнены после вставки в объектную модель документа (DOM).

    • “script” – расценивает ответ как JavaScript и возвращает его как обычный текст. Отключает кэширование с помощью добавления параметра к строке запроса _=[TIMESTAMP], даже если парамета cache имеет значение true. Это превратит метод POST в GET для кроссдоменных запросов.

    • “json” – расценивает ответ как JSON и возвращает объект JavaScript. Кроссдоменные “json” запросы преобразуются в “jsonp”, если в параметрах запроса не указано jsonpfalse. Данные JSON парсятся в строгом порядке и должны соответствовать общепринятому формату, любой некорректный JSON отвергается и выдается ошибка. С версии jQuery 1.9, пустой ответ не принимается, сервер должен вернуть в качестве ответа NULL, или {}.

    • “jsonp” – загружает данные в формате JSON, используя при этом формат загрузки JSONP. Добавляет дополнительный параметр “?callback=?” в конец URL адреса для указания имени функции обработчика. Отключает кэширование путем добавления параметра _=[TIMESTAMP] к URL адресу,даже если парамета cache имеет значение true.

    • “text” – обычная текстовая строка.

    • несколько значений – значения разделяются пробелом. Начиная с версии 1.5, jQuery может преобразовать тип данных, который получен в Content-Type заголовка, в тип данных, который вам требуется. Например, если вы хотите, чтобы текстовый ответ был расценен как XML, используйте “text XML” для этого типа данных. Вы также можете сделать JSONP запрос, получить его в виде текста и интерпретировать его в формате XML: “jsonp text XML”. Следующая строка позволит сделать тоже самое: “jsonp XML”, jQuery будет пытаться конвертировать из JSONP в XML, после неудачной попытки попытается преобразовать JSONP в текст, а затем из текста уже в XML.

  • error.Тип: FunctionjqXHR jqXHRString textStatusString errorThrown ).Функция обратного вызова, которая вызывается если AJAX запрос не был выполнен. Функция получает три аргумента:

    • jqXHR – объект jqXHR (в jQuery 1.4.х, объект XMLHttpRequest).

    • textStatus – строка, описывающую тип ошибки, которая произошла. Возможные значения (кроме null) не “timeout”“error”“abort” и “parsererror”.

    • errorThrown – дополнительный объект исключения, если произошло. При возникновении ошибки HTTP аргумент получает текстовую часть состояния, например, “Not Found”, или “Internal Server Error”.Начиная с версии jQuery 1.5 допускается передавать в качестве значения параметра массив функций, при этом каждая функция будет вызвана в свою очедерь. Обратите внимание, что этот обработчик не вызывается для кроссдоменных скриптов и запросов JSONP.

  • global (по умолчанию: true).Тип: Boolean.Логический параметр, который определяет допускается ли вызвать глобальные обработчики событий AJAX для этого запроса. Значением по умолчанию является true. Если Вам необходимо предотвратить вызов глобальных обработчиков событий, таких как .ajaxStart(), или .ajaxStop(), то используйте значение false.

  • headers (по умолчанию: { }).Тип: PlainObject.Объект, который содержит пары ключ/значение дополнительных заголовков запроса, предназначенные для отправки вместе с запросом с использованием объекта XMLHttpRequest. Обращаю Ваше внимание, что заголовок X-Requested-With: XMLHttpRequest добавляется всегда, но значение XMLHttpRequest по умоланию допускается изменить с использованием этого параметра. Значения headers также могут быть переопределены параметром beforeSend. Добавлен в версии jQuery 1.5.

  • ifModified (по умолчанию: false).Тип: Boolean.По умолчанию значение false, игнорирует поля заголовка HTTP запроса, а при значении true AJAX запрос переводится в статус успешно (success), только в том случае, если ответ от сервера изменился с момента последнего запроса. Проверка производится путем проверки поля заголовка Last-Modified. Начиная с версии jQuery 1.4, помимо заголовка Last-Modified производится проверка и “etag” (entity tag) – это закрытый идентификатор, присвоенный веб-сервером на определенную версию ресурса, найденного на URL. Если содержание ресурса для этого адреса меняется на новое, назначается и новый etag.

  • isLocal (по умолчанию: зависит от текущего местоположения).Тип: Boolean.Используйте значение true для определения текущего окружения как “локального” (например, file:///url), даже если jQuery не распознает его таким по умоланию. Следующие протоколы в настоящее время признаются как локальные: file*-extension и widget. Если Вам необходимо изменить параметр isLocal, то рекомендуется сделать это один раз при помощи функции $.ajaxSetup(). Добавлен в версии jQuery 1.5.1.

  • jsonpТип: Boolean, или String.Переопределяет имя функции обратного вызова в JSONP запросе. Это значение будет использоваться вместо “callback“ (“http://domain.ru/test.php?callback=?”) в составе части строки запроса в URL адресе. Например, значение {jsonp: “onLoad} передастся на сервер в виде следующей строки запроса “http://domain/test.php?onLoad=?”.Начиная с версии jQuery 1.5 при установке значения параметра jsonp в значение false предотвращает добавление строки “?callback” к URL адресу, или попытки использовать “=?” для преобразования ответа. В этом случае Вы дополнительно должны указать значение параметра jsonpCallback. По соображениям безопасности, если Вы не доверяете цели ваших AJAX запросов, то рекомендуется установить значение параметра jsonp в значение false.

{
  jsonp: false,
  jsonpCallback: "callbackName"
}
  • jsonpCallback.Тип: String, или Function.Задает имя функции обратного вызова для JSONP запроса. Это значение будет использоваться вместо случайного имени, которое автоматически генерируется и присваивается библиотекой jQuery. Рекомендуется, чтобы jQuery самостоятелно генерировало уникальное имя, это позволит легче управлять запросами и обрабатывать возможные ошибки. В некоторых случаях установка собственного имени функции позволит улучшить браузерное кеширование GET запросов.Начиная с версии jQuery 1.5, вы можете в качестве значения параметра jsonpCallback указать функцию. В этом случае, в значение параметра jsonpCallback должно быть установлено возвращаемое значение этой функцией.

  • method (по умолчанию: “GET”).Тип: String.Метод HTTP, используемый для запроса (например, “POST”“GET”“PUT”). Добавлен в версии jQuery 1.9.0.

  • mimeType.Тип: String.MIME тип, который переопределяет MIME тип, указанынй в объекте XHR по умолчанию. Добавлен в версии jQuery 1.5.1.

  • password.Тип: String.Пароль, который будет использован с XMLHttpRequest в ответе на запрос проверки подлинности доступа HTTP.

  • processData (по умолчанию: true).Тип: Boolean.По умолчанию данные, передаваемые в параметр data в качестве объекта будут обработаны и преобразованы в строку запроса, подходящую для типа данных по умолчанию “application/x-www-form-urlencoded”. Если Вам необходимо отправить DOMDocument, или другие не обработанные данные, то установите значение этого параметра в false.

  • scriptCharset.Тип: String.Устанавливает атрибут charset (кодировка символов) на HTML тег <script>, используемый в запросе. Используется, когда кодировка на странице отличается от кодировки удаленного скрипта. Обратите внимание, что параметр scriptCharset применяется только в кроссдоменных запросах с параметром type со значением “GET” (по умолчанию) и параметром dataType со значением “jsonp”, или “script”.

  • statusCode (по умолчанию: { }).Тип: PlainObject.Объект числовых кодов HTTP и функции, которые будут вызываться, когда код ответа сервера имеет соотвествующее значение (определенный код HTTP). Например, следующая функция будет вызвана, если от сервера получен код ответа 404, или “Not found” (стандартный код ответа HTTP о том, что клиент был в состоянии общаться с сервером, но сервер не может найти данные согласно запросу.)

$.ajax({
  statusCode: { 
    404: function(){ // выполнить функцию если код ответа HTTP 404
      alert( "страница не найдена" );
    },
    403: function(){ // выполнить функцию если код ответа HTTP 403
      alert( "доступ запрещен" );
    } 
  }
});
  • success.Тип: FunctionAnything dataString textStatusjqXHR jqXHR ).Функция обратного вызова, которая вызывается если AJAX запрос выполнится успешно. Функции передаются три аргумента:

    • data – данные возвращенные с сервера. Данные форматируюся в соответствии с параметрами dataType, или dataFilter, если они указаны

    • textStatus – строка описывающая статус запроса.

    • jqXHR – объект jqXHR (до версии jQuery 1.4.x объект XMLHttpRequest).Начиная с версии jQuery 1.5 допускается передавать в качестве значения параметра массив функций, при этом каждая функция будет вызвана в свою очедерь.

  • timeout.Тип: Number.Устанавливает в миллисекундах таймаут для запроса. Значение 0 означает, что таймаут не установлен. Обращаю Ваше внимание, что этот параметр переопределяет значение таймаута, установленного с помощью функции $.ajaxSetup(). Таймаут ожидания начинается в момент вызова метода $.ajax().

  • traditional.Тип: Boolean.Если вы планируете использовать традиционные параметры сериализации (подходит для использования в строке URL запроса или запроса AJAX), то установите значение этого параметра в true.

  • type (по умолчанию: “GET”).Тип: String.Псевдоним (алиас) для параметра method. Вы должны использовать type, если вы используете версии jQuery до 1.9.0.

  • url (по умолчанию: текущая страница).Тип: String.Строка, содержащая URL адрес, на который отправляется запрос.

  • username.Тип: String.Имя пользователя, которое будет использовано с XMLHttpRequest в ответе на запрос проверки подлинности доступа HTTP.

  • xhr (по умолчанию: ActiveXObject, когда доступен (Internet Explorer), в других случаях XMLHttpRequest.Тип: Function().Обратный вызов для создания объекта XMLHttpRequest. С помощью этого параметра Вы можете переопределить объект XMLHttpRequest, чтобы обеспечить свою собственную реализацию.

  • xhrFields.Тип: PlainObject.Объект, содержащий пары имя_поля: значение_поля, которые будут установлены на объект XHR. Например, вы можете определить, должны ли создаваться кроссдоменные запросы с использованием таких идентификационных данных как cookie, авторизационные заголовки или TLS сертификаты

$.ajax({
  url: "cross_domain_url", // адрес, на который будет отправлен запрос
  xhrFields: { 
    withCredentials: true // поддерживается в jQuery 1.5.1 +
  }
});

Форма с отправкой файлов методом AJAX

Создаём форму с 2 текстовыми полями name и phone, и одним полем для передачи файла (fileImage)

HTML

<form id="feedBack" method="post" onsubmit="return false">
    <input type="text" name="name" placeholder="Имя">
    <input type="tel" name="phone" placeholder="Телефон">
&lt;input type="file" name="fileImage" accept=".jpg, .jpeg, .png" multiple="multiple"&gt;
&lt;input type="submit" value="Отправить"&gt;

</form>

JQUERY

/* запускаем скрипт после полной загрузки документа /
$("document").ready(function() {
  / вешаем событие на ранее созданную форму /
  $("#feedBack").on("submit", function() {
    / создаём объект с данными из полей /
    let formData = new FormData(feedBack)
    / добавляем дополнительные данные для отправки */
    formData.append("url_query", "prog-time");
        /* записываем в переменную данные картинок из формы */
    let allfiles = $(this).find('input[name="fileImage"]');

        /* пробегаем покартинкам и записываем их в массив для отправки */
    for(var i = 0; i &lt; allfiles[0].files.length; i++){
        formData.append("file_"+i, allfiles[0].files[i]); 
    }

        /* отправляем AJAX запрос */
    $.ajax({
        type: "POST",
        url: '/query.php',
        contentType: false,
        processData: false,
        data: formData,
        success: function(data){
      console.log(data)
        },
    });

  })

})

11 PHP

/* ... прописываем необходимые проверки и обработки данных */
/* сохраняем картинки на сервере */
	foreach(image["name"], $image["tmp_name"]);
}

На этом всё!
Прокачивайте свои навыки на нашем канале.

By Rod McBride

jQuery has a lot of methods to define and process AJAX requests in a convenient fashion, but one useful feature added to jQuery in version 1.0 is often overlooked by developers. 

The ajaxError() method is a method that can serve as a centralized place for AJAX request error handling. In general, unexpected server responses are handled similarly as on a web page, such as when a notification or a modal dialogue appears to tell the user that something unexpected happened and the operation has failed. 

By looking at the jQuery documentation for the AJAX convenience methods, like $.post and $.get, we notice that we can attach callback methods to successful and failed AJAX calls. 

$.post(«/api/sendStuff», function () {

    //… handle success

}).fail(function () {

    //… handle failure and display notification

});

Having a way to handle errors on individual AJAX calls is a great way to fine-tune your JavaScript and deal with specific error scenarios close to their occurrences. However, being aware of a centralized AJAX error-handling routine could avoid scenarios similar to this:

$.post(«/api/operationA», function(){

   //…

}).fail(function(jqXHR, textStatus, error){

   handleError(error);

});

$.post(«/api/operationB», function(){

   //…

}).fail(function(jqXHR, textStatus, error){

   handleError(error);

});

$.post(«/api/operationC», function(){

   //…

}).fail(function(jqXHR, textStatus, error){

   handleError(error);

});

In this scenario, the developer created a sophisticated, dynamic, single-page application driven by a collection of AJAX requests and wrote a method that processes errors thrown by those AJAX requests. Technically, there isn’t anything wrong with this solution. However, it isn’t the most elegant approach and causes a lot of repeated code fragments. 

We can get rid of all the redundant fail callbacks by defining the default behavior of the page in case an AJAX exception occurs with ajaxError(). The method needs to be attached to the document object and will serve as a centralized processing place for those types of AJAX scenarios:

$(document).ajaxError(function( event, jqxhr, settings, thrownError ) {

   handleError(error);

});

This global handler will always fire upon an error situation regardless if there is a defined local fail callback. Consequently, the following code fragment will display both error notifications at the same time:

$(document).ajaxError(function( event, jqxhr, settings, thrownError ) {

   showErrorNotificationA(error);

});

$.post(«/api/operationA», function(){

   //…

}).fail(function(jqXHR, textStatus, error){

   showErrorNotificationB(error);

});

To suppress the global error handler and prevent duplicate notifications requires adding some additional logic that gives more control over it.

One way to accomplish this is to define a flag in the settings of the AJAX request that determines whether the global error handler should fire.

The biggest disadvantage of this approach is that you can’t use $.post() and $.get() anymore for these kinds of requests, and we need to fall back to $.ajax() that gives more granular control over the request. Here is an example:

$(document).ajaxError(function( event, jqxhr, settings, thrownError ) {

   if(!settings.suppressGlobalErrorHandler){

         handleError(error);

   }

});

$.ajax(«/api/operationA», {

   suppressGlobalErrorHandler: true,

   success: function(){

      //…

   },

   error: function(jqXHR, textStatus, error){

      //…

   }

});

If you’d like to learn more about the AJAX error handling or have other jQuery or JavaScript questions, contact the technology consultants at Wipfli. You can also keep reading more of our technology-focused articles here.

Понравилась статья? Поделить с друзьями:
  • Jquery post 500 internal server error
  • Jquery min js 2 uncaught error syntax error unrecognized expression
  • Jquery json syntax error
  • Jquery img load error
  • Jquery image load error