Say I submit a form via Ajax and receiving a response from the servlet either in text or json so is there any way to handle both responses. As I have gone through this jquery/ajax documentation Jquery ajax and there I found the accept
and converter
to deal with it but after trying it I didn't get any expected result.So can anyone help me in this?
Asked
Active
Viewed 91 times
1

kunal
- 163
- 1
- 14
-
Possible duplicate of [How to use multiple values with jQuery ajax dataType?](https://stackoverflow.com/questions/25684026/how-to-use-multiple-values-with-jquery-ajax-datatype) – Zenoo Mar 23 '18 at 09:28
-
@Zenoo I think only problem subject are matching but the content is totally different.Because in my case I am getting data from servlet either in string or json – kunal Mar 23 '18 at 09:33
-
Meaning you're receiving different `datatypes`. Which is what the duplicate is about. – Zenoo Mar 23 '18 at 09:34
-
@Zenoo I had gone through the solution of your given question and there they had given 'JSONP' to handle with different responses but I have found the solution without using JSONP – kunal Mar 27 '18 at 06:30
1 Answers
1
As in my case, I have handled the different responses in javascript via ajax without using JSONP AND dataType
Here is my solution
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
error: function(theRequest, textStatus, errorThrown) {
alert('error');
alert(theRequest.responseText);
alert(errorThrown);
},
success: function(data) {
alert('sucess');
var result = data; // it may be string or json
alert(result);
if (result == 'error') { // if it is String
// do your stuff
} else { // if it is json
// convert in json
var jsondata = JSON.parse(result);
alert(jsondata);
// after converting it do your stuff
}
}
});
As you can see that I have handled different responses at different places according to usage.But there is a condition that
In javascript, almost everything is an object. But these objects are bit different from what we see in Java, C++ or other conventional languages. An object in JS is simply a hashmap with key-value pairs. A key is always a string, and a value can be anything including strings, integers, booleans, functions, other objects etc

Narendra Jadhav
- 10,052
- 15
- 33
- 44

kunal
- 163
- 1
- 14