tags:

views:

51

answers:

2

I'm using jqGrid to display the results of a database query. The php script which performs the query and then formats the results as XML for consumption by jqGrid also does some error-checking. (For example, it might validate dates to be sure that they're in the correct format and that the start date is before the end date.) These kinds of errors are formatted into XML, but in a different format than a successful query.

What I want to do is to intercept the result of the ajax call and process it differently depending on whether the result contains one of these custom errors. If no error is present, then I would want to load the result in jqGrid. If there is an error, I would just display on the page without the grid (since the grid is set up for a different number of columns).

What I'm looking for is the correct approach of how to proceed (not necessarily the actual code). (My issue is not how to parse the XML response, but how to intercept it so I am able to parse it.) I had hoped to use the jqGrid events like gridComplete or loadComplete, but these seem to fire after the grid is already loaded.

+2  A: 

The best way would be for the server to send a non-200 response (say, HTTP 500). Then you can handle the grid's loadError or jQuery's global ajaxError.

If you can't do that, then you probably need to make the grid's datatype a function and do the $.ajax yourself, calling the grid's addXMLData method if successful.

Craig Stuntz
The returning of some failed HTTP code in HTTP header and the usage of `loadError` event is **the best way** in my opinion. I would only not recommend to use `datatype` as a function. jqGrid has since version 3.6 parameter `ajaxGridOptions` which can be used to overwrite **any** parameter of the `jQuery.ajax` requests used by jqGrid. So you can use for example `dataFilter` inside of `ajaxGridOptions` parameter and modify the response from the server how you want. See http://www.trirand.com/blog/?page_id=393/help/custom-ajax-options/ for example.
Oleg
A: 

Here's my final solution.

My server script returns custom errors in xml format:

 <row>
      <code>problem</code>
      <description>End date is before start date.</description>
 </row>

so I used the ajaxGridOptions technique suggested by @Oleg to check for an error tag, and if found, display the error message:

 ajaxGridOptions:   
        {dataFilter:    
            function(data,dataType){    // preprocess the data
                if ( $(data).find("code").text() == 'problem' ) {   // check for an error in the result
                    $("#list").jqGrid('GridUnload');
                    $("#errormsg").text( $(data).find("description").text() );
                }else{
                    return data;
                }
            }
        }
jalperin