Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an AJAX response has HTML contents in jQuery?

I have a page with one form and two possible responses in the event of a successful AJAX call, one of which only returns a status code.

What I need to do is check the response object in my success callback for any HTML contents so that I can display them on my page.

I already know that I can access response in my callback by adding it as a parameter, like so:

function success(response) { }

The only thing I can't figure out is how to check if that object has any HTML contents. How can I do this?

like image 525
keeehlan Avatar asked Jul 25 '13 17:07

keeehlan


People also ask

How do you check AJAX response is HTML or JSON?

The only reliable way to check if an arbitrary string is json or not in JS is to try and parse it, and catch the error. Also, the content-type won't tell you if it is valid json.

How do I get AJAX response in HTML?

To retrieve that page using jQuery's AJAX function, you would simply use some javascript similar to the following. $. ajax({ url: 'test. html', dataType: 'html' });

How do I know if AJAX response is empty?

Secondly, you could try to alert the returned data to check the actual value of the returned data. Besides, you could try to modify your “GetProductByCode” method to return a flag to indicate it is null or not. Then your success callback function may look like this.


1 Answers

You probably want to look at the response headers for an HTML MIME type. $.ajax will pass a jqXHR object back into your success callback, which you can then call .getResponseHeader() on:

function success( response, status, jqXHR ) {
    if( jqXHR.getResponseHeader('content-type').indexOf('text/html') >= 0 ) {
        ...
    }
}
like image 82
André Dion Avatar answered Oct 01 '22 23:10

André Dion