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
Related
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.
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.
I have different results by using filter_input(INPUT_POST, 'attribute') and $_POST['attribute'] and don't know why this happens.
The Post-Request is send by a JavaScript build with JQuery and looks like that:
// type javaScript
var formData = {
field_a: "valueA",
field_b: "",
field_c: undefined
};
$.ajax({
url: 'serverAddress',
data: {action: 99, formData: formData},
dataType: 'json',
method: 'post',
success: function(){
console.log(arguments)
}
});
My PHP-Script looks like that:
// type php
$requestMethod = INPUT_POST;
$response = [
"fi-result" => filter_input($requestMethod, 'formData'),
"direct-result" => $_POST['formData'];
];
echo json_encode($response);
the result what is coming back is not what i was awaiting because the access via filter_input returns falsein my tests and not an json object like the direct access on the super global $_POST.
// type json response
{
"fi_result": false,
"direct-result": {
"field_a": "valueA",
"field_b": ""
}
}
Why are there differences between using filter_input and direct access on $_POST?
I don't want to access the super global $_POST. Is there any way to use filter_input like above without encode formData to a String in JavaScript and decode it in PHP one simple step after encoding?
By the way. I'm using TypeScript to generate my JavaScript. That is not supporting the FormData Object (transpiler throws error on new FormData()). So i can't use this.
I found the answer deep in the PHP docs. POST is not build to transport deep object. And filter_input method tries to get simple datatypes like string or int. this method does not parse internal so i have to send it as JSON string and decode it or i can't use filter_input in my case.
i took the first and send now strings.
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");
I am trying to retrieve data from a web service using an ajax call. The call is succeeding, because I am able to successfully print the data in the console using console.log(). However when I attempt to take my data, and convert from a string into an array, the code fails. I am currently trying to use eval, but have also tried to use JSON.parse. Both fail with an error of Uncaught SyntaxError: Unexpected identifier. Any ideas on how to get around this?
$.ajax({
type: "POST",
url: (redacted)
data: (redacted)
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response.d);
var data = eval("[" + response.d + "]");
This is where my code fails. Like I said, console.log(response.d) works, with an output simlilar to this: { 'code':'1234', 'description':'Record 1'}, { 'code':'1234', 'description':'Record 2'}, { 'code':'1234', 'description':'Record 3'}
Is my problem the use of eval? Any input would be greatly appreciated
First, I would use JSON.parse() here instead of eval for decoding JSON strings.
However in this case I believe the return data has already been decoded by jQuery. console.log(response.d) returns a nice looking object and not a "{...}...." string correct?