How to detect JSON object? - javascript

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!

Related

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

Ajax POST error (400 BAD REQUEST)

and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"

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.

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].

jQuery AJAX not evaluating JSON response

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

Categories

Resources