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

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
}
});

Related

How to return data from PHP to a ajax function

Hi I am currently learning php and I am trying to get data from php file using the below script but i am not getting any response
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " ); // not triggering
}
});
my php return stmt
There might be problems with File URL or file access. You can use complete callback to check request for errors like that:
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " );
},
// This method will be fired when request completes
complete: function(xxhr, status) {
alert("Status code: " + status);
}
});
If the status code is not success that means there is something wrong with your request.
You can check more callback options here.
It doesn't matter whether you use return or echo in your PHP file.
The success method must get a call if it's fine. However, if you use
return instead of echo, nothing will append to your request's data.
On the other hand, The PHP response will include in your 'data' variable in the function success.
You need use data in the assync function success
success: function(data) {
alert("Response : " + data);
},
Thanks for your Responses. I got the Solution to my problem. It seems since Ajax is asynchronous... its taking time to receive the resultant echo value from my php file. so I had to synchronize my Jquery using async : False.
$(function(){
$('#formID').on('submit',function(){
const data_set={
name:"Nipu chakraborty",
"phone":"01783837xxx"
}
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});

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!

Javascript send Json Data

How to send json string via ajax and convert json string to xml?
Error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
$.ajax({
async: true,
url: "WebForm1.aspx/btnSave",
type: "POST",
data: "{data: '" + "{'?xml': {'#version': '1.0'},'Card': { 'Main_Client_Information': {'Surname': '','Name': '','Middle_name': '','Full_name': '','Short_name': '','RNN': '','IIN': '','Birthday': '','Doc_Type': {'#code': ''}}}}" + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response.d);
},
error: function (error) {
debugger;
alert(error);
}
});
if send $.ajax data: '{data: "something"} - work perfect, how to put "json like string" instead "something"
WebForm.aspx.cs
[System.Web.Services.WebMethod]
public static string btnSave(string data)
{
string response = "";
try
{
XmlDocument xmlDocument = (XmlDocument)JsonConvert.DeserializeXmlNode(data);
xmlDocument.Save(Server.MapPath("output.xml"));
response = "success";
}
catch (Exception ex)
{
response = "error" + ex.Message;
}
return response;
}
I just want get this string ---------> "{'?xml': {'#version': '1.0'},'Card': { 'Main_Client_Information': {'Surname': '','Name': '','Middle_name': '','Full_name': '','Short_name': '','RNN': '','IIN': '','Birthday': '','Doc_Type': {'#code': ''}}}}" + "'}" ------------ in webmethod btnSave and convert it to xml format
the problem lies in the way you are telling jQuery which data to post :
You probably got confused, since the parameter passed on to $.ajax has a property named data.
You are now passing a string right into there, while you should be passing a Json dictionary which contains which variable names and values you want to send.
try this :
Your entire call should look something like this :
(i'm keeping the data you are trying to send in a separate variable for clarity)
var stringData ="{'?xml' : '#version': '1.0'},'Card': { 'Main_Client_Information': {'Surname': '','Name': '','Middle_name': '','Full_name': '','Short_name': '','RNN': '','IIN': '','Birthday': '','Doc_Type': {'#code': ''}}}}";
$.ajax({
async: true,
url: "WebForm1.aspx/btnSave",
type: "POST",
data: {data:stringData},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response.d);
},
error: function (error) {
debugger;
alert(error);
}
});
You can't send the data as the json string. You need to call JSON.parse (json_string_here_).
It is also possie that you might need put instead of post, but i cant be sure of that because i dont know if you are doing an insert or update.
Sorry, even after that ive got to say that id be a little more than impressed if you can send an xml file like that. I would imagine that doesnt work very well.

I am Unable to Parse a JSON in JQuery

I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});

jQuery YQL json parse trouble

I am trying to parse json from a request, but I keep getting null. When I do console.log(data), it prints null.
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
dataType: "jsonp",
success: function(content) {
var data = jQuery.parseJSON(content);
console.log(data);
}, data: {
q: 'select * from html where url="http://www.google.com"',
format: "json"
}
});
I think that your "content" is probably already parsed for you by jQuery. What happens when you:
console.log(content);
??
(Actually now that I think of it the content is parsed by the browser when it receives the response script body.)

Categories

Resources