I'm working on an application (jquery 3.2.1) where making an ajax call can result in one of the following things happening - providing the server gives a HTTP 200 OK response:
HTML is returned. This is the desired outcome as it is the "content" response to a valid request.
A JSON error is returned - if there are validation errors based on the request data.
The ajax code I have looks like this:
$.ajax({
url: $('#searchRegulations').attr('action'),
type: 'post',
cache: false,
data: $('#searchRegulations').serialize()
}).done(function (response) {
if (response) {
// Display response (point 1)
$('main .content').hide();
$('#ajaxContent').html(response).show();
return false;
} else {
// Handle JSON error (point 2)
}
});
As I've mentioned in the comments above, if situation 1 occurs (HTML is returned) then I write it to #ajaxContent
. That's fine.
But what do I do for situation 2? If I add the following code:
// Handle JSON error (point 2)
$('main .content').hide();
$('#ajaxContent').html(response).show();
Nothing is written inside #ajaxContent
.
Is this because HTML is not being returned?
The Response Headers for each are different:
Content-Type: text/html; charset=UTF-8
Content-Type: application/json; charset=UTF-8
I looked at dataType
on the jquery ajax documentation but wasn't sure if this is relevant because I'm actually receiving 2 separate Content-Type's based on the outcome.
The reason JSON is being returned in scenario 2 is because there is some code (not shown) which can write the error message underneath each field, e.g.
`{rf_keywords: {length: "Search keywords must under 1500 characters in length."}}`
So HTML works better for situation 1, and JSON works better for 2.
Please can someone advise?