Pass parameter containing `&` with AJAX - javascript

I am passing my string to PHP through AJAX using $.Ajax.
I'm trying to pass this string:
action=abc&parameter=C&W
The AJAX splits the C&W on the basis of &, so the request comes in this format:
$action = "abc";
$parameter = "C";
How can I pass it as C&W, without it being split into a different parameter?

You should let jQuery do the encoding for you :
$.ajax({
url: someUrl, // <- no parameter here
data: {action:'abc', parameter:'C&W'},
...

Using bog-standard JavaScript (no jQuery), you can use encodeURIComponent:
var url = "action=" + encodeURIComponent(action) + "&parameter=" + encodeURIComponent(param);

Related

Passing an argument into a URL

I have a function, which takes a number as an argument. I was wondering how I could use this number to pass into a url which will then be used in a GET request.
Below is some of my code, the {{}} brackets below didn't work, I also tried template literals which for some reason also didn't work 'https://www.mywebsite.com/api/v2/${urlID}/fonts.json'
function getID (ID) {
var urlID = this.ID;
var request = require("request");
var options = {
method: 'GET',
url: 'https://www.mywebsite.com/api/v2/{{urlID}}/fonts.json',
};
For your template to work, you'll need backticks.
`string ${someVariable} another string`
Since you're putting data in a URL, you should also take care to use encodeURIComponent() so that any data is escaped properly for the URL.
Putting it all together:
url: `https://example.com/api/v2/${encodeURIComponent(ID)}/fonts.json`

How do I send the operator "&" via an Ajax query?

I'm currently using the following ajax function to send ajax queries.
$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function (htmltwo) {},
error: function (htmltwo) {}
});
The problem is when i send the text which include the operator "&", the items on the right of the operator is deleted. The following is my dataString.
var dataString = 'id=' + id + '&dateoccur=' + dateoccur + '&timeoc=' +
timeoc + '&hitype=' + hitype + '&hid=' + hid;
So e.g if hid is text containing "EEEE&LLLLL", the items on the right of & will be removed when receiving it on the server side. So on the server end, will receive "EEEE". I assume ajax recognizes this because it's part of the dataString variable. How would I be able to solve this issue ?
You could use encodeURIComponent in Javascript to encode characters such as & and then decode them back at the server.
var hidValue = "EEEE&LLLLL";
var hidValueEncoded = encodeURIComponent(hidValue);
console.log(hidValueEncoded);
I always recommend using an object rather than a string. jQuery will then automatically encode everything properly.
var dataString = {
id: id,
dateoccur: dateoccur,
timeoc: timeoc,
hitype: hitype,
hid: hid
};
It's also much more readable, IMHO.
But if you really want to build the string yourself, use encodeURIComponent as in Nisarg Shah's answer. You should do this for all parameters, unless you're sure they don't contain any special characters.

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

send encoded string back to server asp.net mvc

I build the following encoded url:
actionUrl = "MyAction?Vendors=A*A,A%26A,A%2CA"
I want to send this back to my server via an ajax call:
$.ajax({
url: actionUrl,
cache: false,
dataType: "HTML",
success: function (data) {
alert('hooray');
},
error:function(data) {
alert(data.responseText);
}
});
But when this reaches my action on the server, the string is this:
Vendors = "A*A,A&A,A,A"
I need to parse by a comma before i decode the string, but its coming to my server decoded. How do I send an encoded string to my action method via ajax? I'm using asp.net MVC4 but i think thats moot. Thanks
Send the data as JSON like this:
var values = ["A*A","A&A","A,A"];
actionUrl = "MyAction?Vendors=" + JSON.stringify(values);
Then in ASP.net you could use system.Web.Script.Serialization.JavaScriptSerializer to serialize this into an object.
using System.Web.Script.Serialization;
var json = "[\"A*A\",\"A,A\",\"A&A\"]"; //this is the received JSON from the ajax call
var jss = new JavaScriptSerializer();
var values = jss.Deserialize<dynamic>(json);
var value1 = values[0].ToString(); //A*A
var value2 = values[1].ToString(); //A,A
var value3 = values[2].ToString(); //A&A
This way no further (unwanted) conversion takes places between the client and the server. JavaScript converts it to JSON, ASP.net converts it back to its native object notation. Thus eliminating the need to encode your characters, this will be done automatically by the browser and the server decodes it back, as you have seen.

Messaging system jquery sends jQuery514109241_1210239812938 when I put :)) in the message

When I put ":))" in my textarea and send via ajax, it inputs into the database a value like
"jQuery172039628539560362697_1345324072488", how can I stop this? Should I parse my text in some way in javascript first to make it recognize it's text, and not part of the javascript coding?
This is how i get my text
var message = $("textarea.message_thread").val();
var dataString = 'id=' + id + '&message=' + message;
// make ajax call
sending with
$.ajax(
{
type: "POST",
url: "/inbox/instsend",
data: dataString,
dataType: 'json',
success: function(results) {}
}
See the comments under the question; the problem is that what has been submitted in dataString is actually a url-encoded string, and not a JSON-izable or JSON literal variable.
Hence:
dataString = {id: id, message: message};
Will fix this problem, here. jQuery will take that object-initialized variable and encode it for you to JSON.
This is done automatically by jQuery when you're using JSONP for cross-domain AJAX calls. It should be sending this string as the value of the callback parameter.
You need to sanitise the input and escape any control codes - e.g. : and )
Since you are doing POST here. This would work
var dataString = '{'+'id:' + id + 'message:' + message +'}'

Categories