Mootools Request Object not letting me have '+' signs in my query string - javascript

I have the following Javascript/Mootools code:
var str = self.tI.get('value').replace(/\s/g,'+'),
data = 'action=getplaces&str=' + str + '&latLng=' + $('coords').get('value'),
r = new Request({
url: 'action.php',
method: 'get',
link: 'cancel',
onSuccess: function (response) {
/* Do Stuff */
}
}).send(data);
console.log(str);
On the first line I replace any spaces with + signs. When I log the value of str in the console, I get the appropriate value (ie: 'blabla+bla')
However, when I send the request, my request fails. If I look at the headers and the query string, the + sign is simply replaced again with a space (ie: 'blabla bla')
What's up with that? And is there a way around it?

For anybody wondering, my problem ended up being server side. Once the data got to the server side, I was trying to incorporate it in another URL but the server had already parsed the %20 and the +'s to spaces. So had to do some string manipulation on the server side.

You need to escape plus as it's a reserved character in HTML Url's
replace it with +

Related

How to replace spaces in url with + instead of '%20'?

I am trying to convert my parameters into a string in order to send an api request.
However, my current function replaces the spaces in the parameters into '%20'. How do I change it to change spaces into +?
Example params:
{name: "joe walsh"}
Current result:
...endpoint?name=joe%20walsh
Wanted result:
...endpoint?name=joe+walsh
Here's my current function
stringifyParams(params: any) {
return queryString
.stringify(params)
.replace(/[^?=&]+=(&|$)/g, '')
.replace(/&$/, '')
}
You can use Regex to replace %20 with +.
Append this to the function:
.replace(/%20/g, '+');
Firs you should decode your url with decodeURIComponent and then replace space with plus symbol
Try this peace of code and please let me know if that was useful for you)
const param = "endpoint?name=joe walsh";
console.log(decodeURIComponent(param.replace(" ","+")));

Why does string not pass correctly to server when there is a '#' in my variable?

I am attempting to stringify an object but my url does not return correctly when there is a '#` in the object.
I've outputted the value of JSON.stringify($scope.parameter); and it is correct however the url is not.
$scope.parameter = '#' + parameter;
var url = $scope.url + '&functions=' + JSON.stringify($scope.parameter);
I expect it to be {"1":"i001::#11 object"}
but its actually {"1":"i001::
Because you're not encoding it correctly, so it's being interpreted as a fragment identifier (the # introduces a fragment identifier).
You must URI-encode things you put in URIs:
var url = $scope.url + '&functions=' + encodeURIComponent(JSON.stringify($scope.parameter));
// ------------------------------------^
Technically, you have to URI-encode functions in the above as well, but since the URI-encoded version of functions is, er, functions, I didn't bother above. But if it weren't necessarily safe, then:
var url = $scope.url + '&' + encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify($scope.parameter));
If the names you use in name=value pairs only have digits, letters, underscores, and dashes in them, you can safely omit the URI-encoding for them as I did in the first example above. (There are some other chars that are allowed too, but if you start getting into using those, just encode as in the second example for safety.)

how to filter "\" from a json string in javascript

I receive a json string at my node js server which looks like this:
{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}
The reason i put in the "\" is because the string is made in C and the \ is used to escape the " which otherwise ends the string.
The code i use now is:
app.get('/add/:jsonString', function(req, res){
var json = JSON.parse(req.params.jsonString);
});
Is there a way to only delete the \'s in my string?
Why do you want to remove it, it's not necessary ?
var a ="{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}";
console.log(JSON.parse(a));
// give Object { gID: 1, sID: 18, T: "Parking" }
EDIT
Use Url encode to pass your get json
var str = encodeURIComponent("{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}");
// send your request
request.get({uri:"website/api?data="+str}, ...
And in server, decode uri then parse
var string = decodeURIComponent(req.query.data);
var obj = JSON.parse(string);
If you want to remove the "\", try the replace method with a regex pattern:
str.replace(/\\/g, "")
The g flag is used to replace all occurences of the char "\", while the first "\" is an escape character.
For further details, consult MDN
I would suggest that you pass JSON into your application using a POST request, as there are plenty of characters that aren't URI-safe.
However, you can use the unescape method from the built in querystring module.
const qs = require('querystring');
app.get('/add/:jsonString', function(req, res){
const json = JSON.parse(qs.unescape(req.params.jsonString));
});

How do I pass a "#" in an URL using JS?

Why if using # in URL with JS it returns ''/false?
var el = '#string with number character -> #'
el = el.replace(/[']/g, ''');
el = el.replace(/[#]/g, ''');
xmlhttp.open("GET","process_add_article.php?&title=" + (el),true);
xmlhttp.send();
If you want to encode a string on the url there is a native method to do so:
var el = '#string with number character -> #';
el = encodeURI(el);
I am not sure this will accomplish what you are looking for though, the url will be:
xmlhttp.open("GET","process_add_article.php?&title=#string%20with%20number%20character%20-%3E%20#",true);
Which means the title parameter is empty, because the server will ignore the hash (#)
Because # specifies a fragment identifier. Fragment identifiers are entirely client side entities and as such are not sent to the server. See Wikipedia on the topic.
You are using Numeric Character Reference and not Percent-Encoding for URIs.
You may want to use encodeURIComponent instead.
var el = '#string with number character -> #';
xmlhttp.open("GET", "process_add_article.php?&title=" + encodeURIComponent(el), true);
xmlhttp.send();
Not to be confused with encodeURI which doesn't encode #, + and = characters.

AJAX POST and Plus Sign ( + ) -- How to Encode?

I'm POSTing the contents of a form field via AJAX to a PHP script and using JavaScript to escape(field_contents). The problem is that any plus signs are being stripped out and replaced by spaces. How can I safely 'encode' the plus sign and then appropriately 'decode' it on the PHP side?
Use encodeURIComponent() in JS and in PHP you should receive the correct values.
Note: When you access $_GET, $_POST or $_REQUEST in PHP, you are retrieving values that have already been decoded.
Example:
In your JS:
// url encode your string
var string = encodeURIComponent('+'); // "%2B"
// send it to your server
window.location = 'http://example.com/?string='+string; // http://example.com/?string=%2B
On your server:
echo $_GET['string']; // "+"
It is only the raw HTTP request that contains the url encoded data.
For a GET request you can retrieve this from the URI. $_SERVER['REQUEST_URI'] or $_SERVER['QUERY_STRING']. For a urlencoded POST, file_get_contents('php://stdin')
NB:
decode() only works for single byte encoded characters. It will not work for the full UTF-8 range.
eg:
text = "\u0100"; // Ā
// incorrect
escape(text); // %u0100
// correct
encodeURIComponent(text); // "%C4%80"
Note: "%C4%80" is equivalent to: escape('\xc4\x80')
Which is the byte sequence (\xc4\x80) that represents Ā in UTF-8. So if you use encodeURIComponent() your server side must know that it is receiving UTF-8. Otherwise PHP will mangle the encoding.
In JavaScript try:
encodeURIComponent()
and in PHP:
urldecode($_POST['field']);
The hexadecimal value you are looking for is %2B
To get it automatically in PHP run your string through urlencode($stringVal). And then run it rhough urldecode($stringVal) to get it back.
If you want the JavaScript to handle it, use escape( str )
Edit
After #bobince's comment I did more reading and he is correct.
Use encodeURIComponent(str) and decodeURIComponent(str). Escape will not convert the characters, only escape them with \'s
To make it more interesting and to hopefully enable less hair pulling for someone else.
Using python, built dictionary for a device which we can use curl to configure.
Problem: {"timezone":"+5"} //throws an error " 5"
Solution: {"timezone":"%2B"+"5"} //Works
So, in a nutshell:
var = {"timezone":"%2B"+"5"}
json = JSONEncoder().encode(var)
subprocess.call(["curl",ipaddress,"-XPUT","-d","data="+json])
Thanks to this post!
If you have to do a curl in php, you should use urlencode() from PHP but individually!
strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+")
If you do urlencode(strPOST), you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!
Example 1
$strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+") will give Item1=Value1&Item2=%2B
Example 2
$strPOST = urlencode("Item1=" . $Value1 . "&Item2=+") will give Item1%3DValue1%26Item2%3D%2B
Example 1 is the good way to prepare string for POST in curl
Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!
my problem was with the accents (á É ñ ) and the plus sign (+) when i to try to save javascript "code examples" to mysql:
my solution (not the better way, but it works):
javascript:
function replaceAll( text, busca, reemplaza ){
while (text.toString().indexOf(busca) != -1)
text = text.toString().replace(busca,reemplaza);return text;
}
function cleanCode(cod){
code = replaceAll(cod , "|", "{1}" ); // error | palos de explode en java
code = replaceAll(code, "+", "{0}" ); // error con los signos mas
return code;
}
function to save:
function save(pid,code){
code = cleanCode(code); // fix sign + and |
code = escape(code); // fix accents
var url = 'editor.php';
var variables = 'op=save';
var myData = variables +'&code='+ code +'&pid='+ pid +'&newdate=' +(new Date()).getTime();
var result = null;
$.ajax({
datatype : "html",
data: myData,
url: url,
success : function(result) {
alert(result); // result ok
},
});
} // end function
function in php:
<?php
function save($pid,$code){
$code= preg_replace("[\{1\}]","|",$code);
$code= preg_replace("[\{0\}]","+",$code);
mysql_query("update table set code= '" . mysql_real_escape_string($code) . "' where pid='$pid'");
}
?>

Categories

Resources