Problem:
You need to parse errors from a JSON response and display them in a dialog box in your jqGrid. Ideally, you want the grid to check for "STATUS: 'ERROR'" and show all error messages accordingly.
Answer:
It's crucial to follow HTTP protocol guidelines when communicating between the server and client. The standard successful response includes the following:
HTTP/1.1 200 OK ... Content-Type: application/json ... {"page":"1",....}
In contrast, if the URL doesn't exist, the server response will begin with:
HTTP/1.1 404 Not Found
jqGrid relies on HTTP status codes to determine how to handle server responses. For instance, a 404 status code indicates that the grid won't attempt to interpret JSON data.
Demo Code:
To demonstrate this concept:
$("#list").jqGrid({ url: 'Unknown.json', // file with this name doesn't exist datatype: 'json', // ... other relevant parameters loadComplete: function () { alert("OK"); }, loadError: function (jqXHR, textStatus, errorThrown) { alert('HTTP status code: ' + jqXHR.status + '\n' + 'textStatus: ' + textStatus + '\n' + 'errorThrown: ' + errorThrown); alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText); } });
This code will display the following alerts:
Custom Error Handling:
If you want to handle error responses differently, you can use error HTTP status codes. Below is an extended version of the loadError implementation:
loadComplete: function () { // remove error div if it exists $('#' + this.id + '_err').remove(); }, loadError: function (jqXHR, textStatus, errorThrown) { // remove error div if it exists $('#' + this.id + '_err').remove(); // insert div with the error description before the grid $(this).closest('div.ui-jqgrid').before( '<div>
This function removes any existing error div, then inserts a new div before the grid to display the error message. The decodeErrorMessage function can be customized to handle error messages in your preferred format.
Using displayErrorMessage:
Free jqGrid provides a built-in displayErrorMessage method for displaying error messages in an error div above the grid. Before using custom error handling, it's recommended to test the default behavior to ensure it meets your needs.
The above is the detailed content of How to Handle Server-Side Errors and Form Validation in jqGrid?. For more information, please follow other related articles on the PHP Chinese website!