Sending parameters in Jquery Ajax call with quotes, double or single - javascript

I am unable to send data through my ajax call if the user put quotes in the textarea. Is there a way to send text with quotes? I dont want to get rid of the quotes. I guess this is usually not a big problem, i found very little online about this situation.
var description = $('#Description').val();
var title = $('#Title').val();
var parameters = '{content:' + $('#ContentCheck').is(':checked') +
',title: "' + title + '",desciption:"' + description + '"}';

Checkout JSON.stringify(object) which is built into javascript.
The jist is, you create a javascript object, and call stringify to create a JSON string. With your information given above, you might do:
var jsonText = JSON.stringify({
'content': $('$('#ContentCheck').is(':checked'),
'title': title,
'description': description
});
Here we define a javascript hash using the curly braces, and then pass it to stringify.

same problem was with me.I tried this and completely working
xmlhttp.open("POST","test_test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+encodeURIComponent(name)+"&details="+encodeURIComponent(details)+"&r_price="+r_price+"&o_price="+o_price+"&id="+id);
and use urldecode($_REQUEST['details'])` when inserting.

You can convert parameters into a map -- basically an associative array -- instead of a string. That way, you can do string manipulation in the backend .NET without any changes in your frontend js; e.g.
var url = 'http://path/to/your/backend/script';
var parameters = {
contentCheck: $('#ContentCheck').is(':checked'),
title: title,
description: description
};
$.post(url, parameters);

You can encode quotes using js and decode it server side to get the original string
//js
function totalEncode(s){
str= s.replace(/\&/g,'&');
str= str.replace(/</g,'<');
str= str.replace(/>/g,'>');
str= str.replace(/\"/g,'"');
str= str.replace(/\'/g,''');
return(str);
}

Related

Get a string in a variable to create a dynamic link in Javascript

What I am trying to accomplish is to have a map that has a few locations. Whenever users click on each location, a popup will emerge with some information. I am trying to create a dynamic link inside that popup.
Below is my code in Javascript
function parseDescription(message){
var string=""
for(var i in message){
if (i=="CommunityPartner"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="WeitzCECPartner"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="PhoneNumber"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="Website"){
var link = "http://www."+message[i];
string+='<span style="font-weight:bold">'+i+'</span>'+": "+'<a href="{{link}}" >'+link+'</a>'+"<br>"
}
//string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+"<br>"
}
return string;
}
I keep getting this error. I think it's related to the value passed into "a href" :
Request Method: GET
Request URL: http://127.0.0.1:8000/%7B%7Blink%7D%7D
Please help
Instead of using {{link}} in the string, you can try this:
var link = "http://www." + message[i];
string += '<span style="font-weight:bold">' + i + '</span>: ' + link + '<br>';
The following syntax:
{{link}}
is incorrect, because this part was inside a string it was interpreted by the JS engine as a string.
You can use template strings (backticks `) to insert variables as string into another string. For example:
`<span style="font-weight:bold">${i}</span>:<a href="${link}" >${link}</a><br>`;
This example assumes that link and i are both variables which you want to insert dynamically into your string. If you have more questions leave a comment.
I think the problem lies in the {{link}}. Your code looks like native js and not angular or any other framework. Thus, the characters {{}} inside a string do not mean anything. The url that you get is exactly those characters, escaped. Use plain old string concatination to enter your href value.

Change the value of javascript variable dynamically

I have javascript variable var result as following which has java variable that have JSON data like this
var result = <%=JsonData1%> ;
alert(result.toSource());
Above code similar to this code as showing on alert message
var result= [{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}];
but I need to place a single quote on JSON data
'[{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}]'
and place it in new javascript variable like this
var json_pre = result;
alert(json_pre);
but when I change my result data that placed in new json_pre variable as in this link How to add single quote in the variable in Javascript?
var json_pre = "'" +result+ "'";
alert(json_pre.toSource());
then json data shows me like this on the alert message
'[{year:(new Date(-2208058200000)), value:6694}, {year:(new Date(-2207971800000)), value:50}, {year:(new Date(-2208403800000)), value:4776}, {year:(new Date(-2208317400000)), value:29006}, {year:(new Date(-2208231000000)), value:1751}]'
As I have tried every method that given me on that link.So anyone can help me in this?
result is not JSON, but a JavaScript object.
What you need to do is to stringify your object to JSON and then add the quotes:
var result = [{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}];
var result_pre = "'" + JSON.stringify(result) + "'";
console.log(result_pre);
But it is questionable why you would even need that.
You need to understand the single quotes does not make an object a string. When you are trying to store it in a variable I guess you are making the same mistake again.
when you do this
a={"key":"value"}
b="'" + a + "'";
You get a string representation for consoles, if you want a JSON string to be stored in a variable you need to do this
var json = JSON.stringify(result);
alert(json);
You don't need quotes for that.

Passing in a key results in extra characters in my firebase URL, how do I remove them?

When placing the "key" variable inside of this string, it displays 'simplelogin%3A5' instead of 'simplelogin:5'. Is there a way to just pass in the latter?
var populateTasks = function(date, key){
$scope.ref = new Firebase("https://myfirebase.firebaseio.com/users/"+key+"/tasks");
};
results in: https://myfirebase.firebaseio.com/users/simplelogin%3A5/tasks
I need: https://myfirebase.firebaseio.com/users/simplelogin:5/tasks
var uri = "//what you need to convert";
var uri_dec = decodeURIComponent(uri);
var res = uri_dec;
Where does the value of key come from? If you get it from a URL, it makes sense that you see %3A.
A : has a special meaning in a URL, so it is escaped. And the URL escape sequence for a : is %3A.
To convert the %3A back to : you simply unescape it like this:
unescape(key)
Or use decodeURIComponent, which in this case accomplishes the same. The best way to decode the value depends on why it was encoded in the first place, hence my initial question.
Have you tried trimming key before concatenating it to the URL?
key = key.trim();

Javascript & problems

I have the following code:
var artist = document.getElementById("txtBoxArtist").value;
When value is plain text, e.g. Biffy Clyro, artist = Biffy Clyro
When value contains &, e.g. Mumford & Sons, artist = Mumford
I the send artist value using AJAX, and recover the value on another php page like this:
var data = "nameTitle=" + title + "&nameArtist=" + artist;
[...]
$nameArtist=$_POST['nameArtist'];
Why does this happen and how to avoid it? It is giving me lots of problems this &symbol...
Thank you all!
You need to encode the values before sticking them on the URL.
var data = "nameTitle=" + encodeURIComponent(title) + "&nameArtist=" + encodeURIComponent(artist);
You should also see this.
Some characters are special and need 'escaping' to encode their values - as you are showing using & instead of &.
However, these escaping principles are different for HTML content and for URLs/URIs.
In URI, & is escaped as %26 and not as & - so you should either use that or the appropriate encoding/decoding functions, not the HTML entity encoding/decoding.
I guess you can encode valiables before sending them like this:
artist = encodeURIComponent(artist);
title = encodeURIComponent(title);
var data = "nameTitle=" + title + "&nameArtist=" + artist;
hope this helps.

Encoding URL (including characters like &) using jquery or native javascript function?

I have one one hidden paramter in form whose value is
custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
I want to encode it before sending it and so that characters like & can be replaced with %26 etch
i tried using javascript built-in encodeURI("urlToencode") but does not encode characters like &?
Try this code line,
encodeURIComponent("fisrtName=scott&lastName=Miles");
Use https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
You need to call that on each dynamic part (name and value) of the URL query string. So the question is what is the URI component in custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles That doesn't really look like a URL because you have the = before the ?
The most sense that I can make is that the full URL is something like
http://myserver/file.do?custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
In which case, you should build your URL like
var custAddress = "CustomerAddress.do?fisrtName=scott&lastName=Miles";
var initialPath= "/path/to/file.do?";
var url = initialPath + "custAddress=" + encodeURIComponent(custAddress);
Since you mentioned jQuery, you can use a $.param, looks cleaner and does the encoding for you, and you can give it multiple query parameters at once
var url = initialPath + $.param({
custAdrress: custAddress,
otherParam: "paramVal",
// Both the param name and value need to be encoded and $.param does that for you
"funny Name & Param": "funny & value ="
});

Categories