jQuery AJAX not evaluating JSON response - javascript

i have an array which i can see in the console.log(response) which is:
{"status":"success","message":"Success! You will get an email shortly, please confirm your email address and you will then recieve your 50% discount coupon a few days before launch!"}
My AJAX is:
$.ajax({
url: 'includes/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(response) {
console.log(response);
console.log(response.status);
console.log(response.message);
if(response.status == "success"){
$('#note').html(response.message);
}
}
});
however the console.log .status and .message returns undefined. Im most likely missing something simple here but if anyone can spot why would be great
Thanks in advance

Add dataType: 'json'
"json": Evaluates the response as JSON and returns a JavaScript
object. The JSON data is parsed in a strict manner; any malformed JSON
is rejected and a parse error is thrown. As of jQuery 1.9, an empty
response is also rejected; the server should return a response of null
or {} instead. (See json.org for more information on proper JSON
formatting.)
$.ajax({
url: 'includes/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(response) {
console.log(response);
console.log(response.status);
console.log(response.message);
if(response.status == "success"){
$('#note').html(response.message);
}
},
dataType: 'json' //Add this
});

Related

Ajax error getting called instead of success

<script>
function editComment(id) {
var content = $('#Content').val();
var modelData = { 'Id': id, 'Content': content };
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("EditC", "Comment")',
data: JSON.stringify({ model: modelData }),
contentType: 'application/json',
success: function () {
alert("YES");
},
error: function () {
alert("Error");
}
});
}
</script>
Here the server is returning 200 OK, but for some reason the error function is getting called. Both type and contentType seem to be correct. Any idea how to fix this?
Edit:
After adding
error: function (xhr, textStatus, error) {
console.log(xhr.responseText);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
this is what is being logged:
parsererror
parsererror
SyntaxError: Unexpected end of JSON input
at parse (<anonymous>)
at ajaxConvert (jquery-3.4.1.js:9013:19)
at done (jquery-3.4.1.js:9483:15)
at XMLHttpRequest.<anonymous> (jquery-3.4.1.js:9785:9)
Moving to an answer for future readers...
The server is indeed returning a successful response, but an empty successful response:
return new HttpStatusCodeResult(200);
However, the client-side code is expecting valid JSON:
dataType: 'json',
As a result, after the successful response is received, internally the jQuery code attempts to parse that response as JSON and that fails, resulting in triggering the error callback.
Since there's no response body (and in most cases even when there is, as long as the server returns the correct MIME type), you don't need or want to specify a dataType in the jQuery AJAX operation. Simply remove this part:
dataType: 'json',

Stumped why Javascript AJAX Success: JSON data is "invalid"

I'm stumped why my Flask called JSON data is not being read by ajax success wait statement that works very well elsewhere. I realize the Success: statement is supposed to wait for data to returned and it does, but then the data returned isn't accessible as any JSON. There are no console nor browser console errors to indicate why data is considered 'invalid'
Flask Function
#blueprint.route('/target_liner')
def target_liner():
ind_id = int(request.args.get('ind_id'))
label = "1508 Loss Correction"
data = '[{"Program_Name":"' + label + '"}]'
return data
JSON Data
[{"Program_Name":"1508 Loss Correction"}] // This is confirmed legal JSON
Javascript
function updates() {
$.ajax({
url: "/target_line",
method: "GET",
data: {
ind_id: 1508
},
success: function (data) {
console.log(data);
alert(data); // This shows the JSON string correctly in Chrome Inspect console
alert(data.Program_Name);
alert(data[0]['Program_Name']);
alert(data[0].Program_Name );
}
});
};
updates();
The data retuned is a String. You can either do a JSON.parse(data) after the success or you can use dataType: 'json' in your ajax request. you might get a parse error if your JSON String is not formed properly when you use dataType: 'json' .
You have three possibilities:
in your flask change return data to return jsonify(data);
add dataType: "json", to your ajax call as per comment by #Rocket Hazmat;
add to the succes response a conversion from string to json: data = JSON.parse(data);
$.ajax({
url: "/target_line",
method: "GET",
data: {
ind_id: 1508
},
success: function (data) {
data = JSON.parse(data);
console.log(data);
console.log(Object.keys(data[0])[0]); // print: Program_Name
console.log(data[0].Program_Name ); // print: 1508 Loss Correction
}
});

How to detect JSON object?

Can I detect a JSON object and according to its object show a message?
I tried like this but it is not working :(
$.ajax({
type: "POST",
url: "example.php",
data: form_data,
success: function(data) {
if(data.has("error")){
alert('Invalid data')
} else {
alert('Correct data')
};
}
});
If the data entered is wrong, data shows in the console something like this:
{"object":"error","type":"wrong_number"...
If this object contains error, I want to show error message. Otherwise, continue
Be sure to set the dataType as 'json' on the ajax request so that the data will be parsed as json before being passed to the success handler.
$.ajax({
type: "POST",
url: "example.php",
data: form_data,
dataType: "json",
success: function(data) {
if(data.has("error")){
alert('Invalid data')
} else {
alert('Correct data')
};
}
});
A json object is of type Object, since you will receive whatever, if typeof(jsonObj) == Object, you will not know if its a json object or just an object, but what you can do, is , read the headers in the request, and if its application/json, it will be a json object.
Another thing is, you can add a property in the json object like
var obj = {
customProp: 'Whatever property you want',
data: {
childData: childData
}
}
I just understood your question correctly.
In a request theres a Success response, and an Error response
Success responses are response.status < 200 < 300 (generally they are 200)
what you can do, is, in the response of the function on your server, detect the object, if its correct just send the response, if it's not, send an error object
error = {errorText: 'Your form is not correct'}
Hope this helps!

Invalid Json Primitive on Ajax Post

I am posting my form using AJAX:
$(function () {
$("#Compare").click(function (e) {
$.ajax({
url: '#Url.Action("_Compare","API")',
dataType: 'application/json',
data: {
model: $("#CompareForm").serialize()
},
type: "post",
success: function(response) {
alert (response);
}
});
e.preventDefault();
});
});
I am trying to deserialize my JSON result but I am getting an 'Invalid Json Primitive Exception'.
My Json Result:
"%5B0%5D.Id=1&%5B0%5D.Description=Sutherland+Silver+Plans+offers+you...&%5B0%5D.Price=30&%5B0%5D.Title=Silver+Plan&%5B0%5D.isSelected=true&%5B0%5D.isSelected=false&%5B1%5D.Id=2&%5B1%5D.Description=Sutherland+Gold+Plans+offers+you...&%5B1%5D.Price=50&%5B1%5D.Title=Gold+Plan&%5B1%5D.isSelected=true&%5B1%5D.isSelected=false&%5B2%5D.Id=3&%5B2%5D.Description=Sutherland+Platinum+Plans+offers+you...&%5B2%5D.Price=80&%5B2%5D.Title=Platinum+Plan&%5B2%5D.isSelected=false"
You seem confused about what JSON is, and whether the issue is with the request or the response.
The issue is with the request. You are attempting to put the querystring that serialize() creates in to the model parameter of an object, which itself will be serialised and encoded again. Instead, just pass the querystring that serialise generates to the action:
$("#Compare").click(function (e) {
$.ajax({
url: '#Url.Action("_Compare","API")',
dataType: 'application/json',
data: $("#CompareForm").serialize(),
type: "post",
success: function(response) {
console.log(response);
}
});
e.preventDefault();
});
You have specified the response will be JSON. If this is the case, use console.log to inspect it, otherwise the alert() will only show [object Object].

Jsonp returned from ajax doesn't show on console

I'm calling a page (external, on other domain), with this code:
var instagram_container = $('div#instagram-answer');
if (instagram_container.length>0)
{
var url = 'http://www.xxxx.it/admin/get_instagram_token';
$.ajax({
type : 'GET',
url : url,
async : false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(response)
{
console.log(response);
instagram_container.html(response.client_id);
},
error: function(e)
{
console.log(e);
}
});
}
I have answer with console.log(e) (basically it recognizes as error)?
Object { readyState=4, status=200, statusText="success", altri elementi...}
But in Firebug, under NET tab, I have the right answer...
This is the console. Line 19 is exactly the
console.log(e);
in error section.
My goal is obtain that Json. Thank you
Is your server returning plain text, or an actual JSON file? Jquery will ignore the response if the server returned a string instead of JSON.
The response type should be: "application/json"
EDIT:
I'd recommend you to use the basic jquery ajax call:
$.ajax({
url: "test.html",
cache: false
})
.done(function( response ) {
console.log(response);
});

Categories

Resources