IE11 inteprets AJAX POST reply as string, despite being JSON array - javascript

From an JQuery AJAX post request the server sends me an reply that just says Hello, and I want to get that Hello as a string.
I wrote this code to get the text value:
var posting = $.post(
"https://server/bla",
{
input: theinput
}
);
posting.done(function( reply ) {
console.log(reply);
console.log(typeof reply);
console.log(reply[0]);
}
It works perfectly on Firefox 55:
Array [ "Hello" ]
object
Hello
... but IE11 seems to believe it is a string (same code):
["Hello"]
string
"[\"Hello\"]"
I wrote a hackish workaround that just uses substring to remove the brackets and quotes at the beginning and end if the variable is a string, but it does not handle well quotes within the reply (Hell"o becomes Hell\"o).
Is there a cleaner solution?
By the way, here is the server side Java code:
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
jsonArray.put("Hello");

As tipped by Rory, the datatype parameter helps here.
dataType Type: String The type of data expected from the server.
Default: Intelligent Guess (xml, json, script, text, html).
I rewrote the query part to this:
var posting = $.ajax({
type: "POST",
url: "<%=addResUrl%>",
data: {
input: theinput
},
dataType: "json"
});
Note the dataType: "json".
And now it works in IE11 the same way as in Firefox: The JSON is recognized as JSON.

Related

POST JsonArray using Ajax

I have a JSON Array that I am trying to post to SENDGRID using Ajax. Using Postman I am able to post with no issues however when I post the data in my .js file I keep getting an error (bad request = missing parameters).
Any help is appreciated.
Note: The values are in fact valid. I have removed the identifying information for safety.
CHROME PAYLOAD:
AJAX Call:
var mailUrl = "https://api.sendgrid.com/v3/mail/send";
var postdata = '{"personalizations": [{"to":[{"to email"}],"from": {"email":"from email"},"subject":"Hello, World!" , "content" : [{ "type":"text/plain" , "value":"TestMessage!" }]}]}'
$.ajax({
type: 'POST',
headers: {Authorization: "Bearer APIKEY"},
url: mailUrl,
contentType: "application/json",
data: JSON.stringify(postdata),
success: function (res) {
alert('ok');
},
error: function (res) {
alert('problems');
}
});
The problem seems to be with this part of json [{"to":[{"to email"}].You can use jsonlint to validate the json. Also JSON.stringify() method converts a JavaScript value to a JSON string.
But in your case postdata is already a string .
The string stored in the variable is a valid JSON. Calling JSON.stringify() on a JSON will escape all the special characters like " and that escaped string will not be deserialized to the object you intended.
While a string is still a valid JSON according to some specifications, The specifications for application/json stated in RFC4627
An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members).
make the returned string invalid for post.
Sending the string itself without serializing it again will likely work.

Convert C# model to plain json-string

Is there any simple way to convert an C#-object into a plain string that is escaped and can be used by javascript?
I try to pass the string into a jQuery-function which will replace some parts of this string with real values to pass them as request-object via $.ajax.
Whatever I tried (found in the internet) doesn't work.
Currently I have:
var jsVariable = "#Html.Raw(Json.Encode(new MyClass()))"
but this throws an Uncaught SyntaxError: Unexpected identifier as of the " are not escaped correctly.
Update 1
At the end I would like to have the JSON-string like
"{"Prop1": "{0}", "Prop2":"{1}"}"
on which I can (in javascript) call
var request = string.Format(jsVariable, value1, value2);
to enable
$.ajax({
type: "POST",
url: "someUrl",
data: $.parseJson(request),
success: function(data) {
console.log("success");
},
dataType: "JSON"
})
Just get rid of the double quotes.
Make sure this is added in the script tag of your view.
var jsVariable = #Html.Raw(Json.Encode(new MyClass()))
you'd then get a javascript object with its properties - provided MyClass is defined, and is accessible in your CSHTML.
jsVariable.myProp, jsVariable.myOtherProp . . etc

Javascript json parsing of php response

I'm working on a project and use ajax to update some informations in forms.
Here is my ajax function :
function update_ad() {
var project_name = document.getElementById("mol_project").value;
if (project_name !== '') {
$.ajax({
type: 'POST',
url: "controllers/get_project.php",
data: {project_name: project_name},
dataType: 'text',
success: function (data) {
var result = JSON.parse(data);
}
});
}
}
On my development environement everything works fine. The function get the json text from php server and parse it so I can use data after that.
But on my production environement, I receive a parsing error :
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Here is the received Json :
{"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"project_abbr":"JR","project_mol_index":"2","project_comment":null}
Jquery, apache and php version are the same on both environements. I guess it's a server configuration issue but I can't figure out where it is.
replace dataType: 'text' to dataType: json,
Look at the spec for JSON (easily understood version here: http://json.org/). There is nowhere that says that parenthesis are valid. ({"foo": true}), for example will never parse. It may be evaled as it is valid javascript, but javascript is not JSON.
Okay, in your JSON, there's a UTF-8 BOM in the front. Can you find the difference between:
{"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"project_abbr":"JR","project_mol_index":"2","project_comment":null}
And:
{"project_name":"Jaguar","project_ORB_code":null,"project_manager":null,"project_abbr":"JR","project_mol_index":"2","project_comment":null}
Where the latter is a valid JSON. Check it out with JSONLint. You need to make sure that the output you are receiving is free of UTF-8 BOM.
When I tried using the encodeURI() function on the JSON, it gave me this output:
encodeURI(' {"pr'); // "%20%EF%BB%BF%7B%22pr" - Wrong one!
encodeURI(' {"pr'); // "%20%7B%22pr" - Correct one!
We can make use of encodeURI to detect the anamolies and fix it in the client side. I am working on a solution.
The unicode signature, if you see, is EF BB BF, which is explained in this article. We can make use of this signature and try to correct it.
If you have the access to the PHP source, try setting the right headers:
header("Content-type: application/json; charset=utf-8");

how to decode serialize url from javascript in php

please consider following snippet
i have submited a form which contains a background image url , i have serialize the form data . in php the URL is not decoding , how to get orignal url
$("#slider_settings_form").submit(function(e) {
var postData = $(this).serialize();
submited form
$.ajax({
url: ajaxurl,
data: {
"params": postData,
"action": "saveFormSettings"
},
method: "POST",
success: function(response) {
alert(response);
},
});
Use string urldecode( string $str ) function to decode your encoded URL data
for more follow this link
A successful parsing could be done by adding urldecode like this:
parse_str(urldecode($_REQUEST['params']), $params);
urldecode is important because it converts url encoded string into parsable string.
If you want to achieve it from javascript you can use these methods:
var uri = "http://stackoverflow.com/questions/30587877/how-to-decode-serialize-url-from-javascipt-in-php"
var uri_enc = encodeURIComponent(uri); //for encoding
var uri_dec = decodeURIComponent(uri_enc); //for decoding
Here is the link for more details:
Url decode and encode
Have a look at this related question.
We need to see how you're decoding the data in PHP to help you, but in addition to the answer ahead of mine (suggesting the use of urldecode), you should also make sure postData actually has data in it.
Only "successful controls" are serialized to the string [...] - second answer
It's entirely possible postData is nil. You should test it by alerting it and go from there. The question I linked to has a more thorough answer with code examples.
var postData = $(this).serialize(); -- this would create a query string like 'a=1&b=2', where a and b are form fields. You might want to fetch the value of a or b -- the following code will help you:
parse_str($_GET['params'], $params);
// then you can use $params['a'] to fetch form field 'a'
print_r($params);
// =>
//Array
//(
// [a] => 1
// [b] => 2
//)
For more about parse_str, see http://php.net/manual/en/function.parse-str.php

JSON.parse not parsing Json string. Serializing with JavaScriptSerializer

I have a serialized string comming from the controller to a view:
Controller:
var serialize = new JavaScriptSerializer();
return Json(new
{
data = serialize.Serialize(obj)
}, JsonRequestBehavior.AllowGet);
Json string:
[{"indiceName":"Caracter","indiciId":24,"indiceId":1,"tamanhoIndice":10,"mask":null,"indiceObr":1},
{"indiceName":"Numérico","indiciId":25,"indiceId":2,"tamanhoIndice":10,"mask":null,"indiceObr":0},
{"indiceName":"AlfaNumérico","indiciId":26,"indiceId":3,"tamanhoIndice":10,"mask":null,"indiceObr":0}]
As far as I know, modern browser should be able to parse that string with a simple
Json.parse()
View:
success: function (data)
{
$('.dinamic').remove();
console.log(data);
var obj2 = JSON.parse(data);
console.log(obj2);
}
I am able to see that string in the first console.log, but I get nothing from the second.
Is there any thing else I should be looking at because all the post I have read people only do it as simple as it is with a single JSON.parse.
I am using latest version of google chrome ,firefox and IE so it should work.
Although your success function is not shown in context of the other AJAX options being given, I would guess you are passing a dataType option of "json", or are using $.getJSON or something similar.
If that is the case, jQuery has already parsed the JSON for you by the time it passes it into success so you do not need to (and cannot) parse it again. You can simply use your data structure (data[0]. indiceName and etc).
(The below code is running live at http://jaaulde.com/test_bed/GuilhermeLongo/ )
Consider the following PHP (stored in json.php):
<?php
exit('[{"indiceName":"Caracter","indiciId":24,"indiceId":1,"tamanhoIndice":10,"mask":null,"indiceObr":1},{"indiceName":"Numérico","indiciId":25,"indiceId":2,"tamanhoIndice":10,"mask":null,"indiceObr":0},{"indiceName":"AlfaNumérico","indiciId":26,"indiceId":3,"tamanhoIndice":10,"mask":null,"indiceObr":0}]');
And the following JS:
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$.ajax({
url: 'json.php',
type: 'get',
dataType: 'json',
success: function (data) {
console.log(data[0]);
console.log(data[0].indiceName);
},
error: function () {
throw new Error('AJAX request error occurred.');
}
});
</script>
It results in the following outputted log info:
GET http://jaaulde.com/test_bed/GuilhermeLongo/json.php
200 OK
99ms
jquery.min.js (line 3)
Object
{indiceName="Caracter", indiciId=24, indiceId=1, more...}/test_...eLongo/
(line 8)
Caracter

Categories