Can't send '+' character over ajax - ajax

I have a script that makes an ajax request passing 3 different data : eventName / ticketsToWin / totalWinners.
My whole process was working perfectly until I had this case : "SCi+Tec" as the eventName variable. Here is what looks like the data of the request just before sending :
name=Sci+Tec&ticketsToWin=1&totalWinners=2
But then, on the PHP side, if I dump the _GET array, I have this :
array(4) {
["name"]=> string(7) "Sci Tec"
["ticketsToWin"]=> string(1) "1"
["totalWinners"]=> string(1) "2"
["_"]=> string(13) "1372359516001"
}
The '+' character is missing in the name, which breaks everything that comes after. Any idea why ?!
Thans!

encode your string:
name=Sci%2BTec&ticketsToWin=1&totalWinners=2
Or easier:
var str = 'name=Sci+Tec&ticketsToWin=1&totalWinners=2';
var encoded = encodeURIComponent(str);
see the docs or this Question

I'm pretty sure that the plus sign in URLs is used instead of a space, like in a google search, you give the following query:
"How to send an email",
It will show in the URL as:
"How+to+send+an+email".
Try POSTing it.

In Urls, spaces in query strings are automatically replaced by plus signs. So when the server gets Sci+Tec, it thinks there is supposed to be a space there. You will need to escape it with its url encoding: %2B.
More on Url encoding: http://www.w3schools.com/tags/ref_urlencode.asp

you could either use a java url encode or a javascript encoder
URLEncoder.encode(yourString)

Related

How to make Get Request with Request param in Postman

I have created an endpoint that accepts a string in its request param
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression") String expression) {
System.out.println(expression);
// code to validate the input string
}
While sending the request from postman as
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606/Curr_month:Y07608
// lets say this is a valid input
console displays as
Y07607=Curr_month:Y07606/Curr_month:Y07608 Valid
But when i send
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606+Curr_month:Y07608
//which is also an valid input
console displays as
Y07607=Curr_month:Y07606 Curr_month:Y07608 Invalid
I am not understanding why "+" is not accepted as parameter.
"+" just vanishes till it reaches the api! Why?
I suggest to add this regular expression to your code to handle '+' char :
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression:.+") String expression) {
System.out.println(expression);
// code to validate the input string
}
I didn't find any solution but the reason is because + is a special character in a URL escape for spaces. Thats why it is replacing + with a " " i.e. a space.
So apparently I have to encode it from my front-end
Its wise to encode special characters in a URL. Characters like \ or :, etc.
For + the format or value is %2. You can read more about URL encoding here. This is actually the preferred method because these special characters can sometimes cause unintended events to occur, like / or = which can mean something else in the URL.
And you need not worry about manually decoding it in the backend or server because it is automatically decoded, in most cases and frameworks. In your case, I assume you are using Spring Boot, so you don't need to worry about decoding.

Search Query Parameter

I want to search email which contains '+' in it. for example
something like this myemail.subdomain+1#domain.com.
URL - https://example.com?searchKey=myemail.subdomain+1#
I am using Laravel, this parameter is fetched from route using
$request->get('searchKey');
but it's converting '+' to ' ' ,
as a result i am getting
searchKey as myemail.subdomain 1#
which leads to improper result.
Any help?
PHP assumes that + from GET request is a space. Right encoded plus symbol is %2B.
You have to just prepare string from request to save plus symbol:
$searchKey= urlencode(request()->get('searchKey'));
In your case you'll get # as %40. Then you can replace plus with correct code and decode it. But then be careful with usual spaces!
$searchKey = urlencode(request()->get('searchKey'));
$searchKey = urldecode(str_replace('+', '%2B', $searchKey));
https://www.php.net/manual/en/function.urlencode.php
https://www.php.net/manual/en/function.urldecode.php
P.S. I suppose it is not the best soulution, but it should work.
P.P.S. Or, if you can prepare plus as a %2B before it will be at search parameter, do it

Jsonp request with Swedish character gives null response

I'm using jsonp to request data from a web server to my application (built in sencha). The request has a dynamic parameter called 'sokt'. Sometimes the parameter has a swedish character (å, ä, ö) and sometimes it doesn't.
As long as there's no swedish charachter the server returns the expected result: for example:
http://mywebsite.se/jsonnew.php?sokt=test&_dc=1370095960312&page=1&start=0&limit=25&callback=Ext.data.JsonP.callback31
But if there's a swedish character in the request, the server returns nothing. Example:
http://mywebsite.se/jsonnew.php?sokt=enastående&_dc=1370096101366&page=1&start=0&limit=25&callback=Ext.data.JsonP.callback39
But then if i manually url encode the request enastående to enast%E5ende I get the expected result.
So, to summarize, the problem seems to be that the request from jsonp doesn't url encode the query string, it sends the unicode string which is not accepted by the php script that formats the response (which has a utf_8-header). If this really is the reason this is not working, which I'm not sure of, how would I solve this?
EDIT with code:
This is my request:
Ext.getStore('storen').setProxy({ type: 'jsonp', url: 'http://mywebsite.se/synonymer/jsonnew.php?sokt=' + param}).load()
And this is php script:
<?php
header('Content-Type: text/javascript; charset=utf8');
include("config.php");
$dbh = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$sokt = $_GET['sokt'];
$stmt = $dbh->prepare("SELECT * FROM table WHERE w1 = :sokt");
$stmt->bindParam(':sokt', $sokt);
$stmt->execute();
$output = array();
while ( $row = $stmt->fetch() ) {
$output[] = array("key" => utf8_encode($row['w2']));
}
$callback = $_REQUEST['callback'];
// Create the output object.
//start output
if ($callback) {
echo $callback . '(' . json_encode($output) . ');';
} else {
echo json_encode($output);
}
?>
You are attaching the value of sokt in the url of the proxy, hence the proxy want change anything. So you have to care about this yourself. There is a native method for that encodeURIComponent()
Ext.getStore('storen').setProxy({ type: 'jsonp', url: 'http://mywebsite.se/synonymer/jsonnew.php?sokt=' + encodeURIComponent(param)}).load()
As I can see someone other already answered this but deleted his answer cause you told him this want work, so here are some additional infomation:
Now your request should be send encoded like this
http://mywebsite.se/jsonnew.php?sokt=enast%C3%A5ende&_dc=1370096101366&page=1&start=0&limit=25&callback=Ext.data.JsonP.callback39
Verify that by using your browsers developer tools. If that is so the frontend has done anything right and you will have to check the backend.
There you have to check if the param is URLdecoded and if not decode it
$sokt = urldecode($_GET['sokt']);
and you have to ensure that your database is really storing all the correct way. So use some tool like PHPMyAdmin (MySQL), ManagementStudio (MS SQL) or any query tool to see if your database behaves correct and the that the Data is stored in the correct format.
Checking all this should lead you to the error
When dealing with utf-8, first make sure everything is configured for utf-8
HTML
PHP, file store (file encoding)
Web Server
Database Columns (Collation)
Database Connection (Client and Server)
If done so, you're almost close to entirely forget about troubles with äöüß (No swedish chars here ;-) ).
And obviously you don't need any utf8_en|decode functions which do not work properly anyway, see the comments on php.net to these functions.
I've recently switched from ISO-8859-1 to utf-8 and it was a hell of work, but afterwards any "char conversion" was necessary any longer at all.
So: leaveing those äöü in an URL unencoded may still lead to problems. I don't kno Ext but assume that their doing a proper UTF-8 encoding of the extraParams as json requires that!
Have you tried
Ext.getStore('storen').setProxy({
type: 'jsonp'
,url: 'http://mywebsite.se/synonymer/jsonnew.php'
,extraParams: {
sokt: encodeURIComponent(params)
}
}).load();
Try using the extraParams option of the proxy instead of hardcoding it in the URL:
Ext.getStore('storen').setProxy({
type: 'jsonp'
,url: 'http://mywebsite.se/synonymer/jsonnew.php'
,extraParams: {
sokt: param
}
}).load();
Or, even simple, the params option of the load() method:
Ext.getStore('storen').load({params: {sokt: param});
Try decoding your param on the server side:
$sokt = urldecode($_GET['sokt']);
Try forcing your database connection to UTF8 before executing your query:
$dbh->prepare("SET NAMES 'utf8'")->execute();
Maybe one of these or the combination of both will work.

CodeIgniter: Disallowed Key Characters

I have the same problem as the people below, but the solutions offered for them does not work for me.
CodeIgniter - disallowed key characters
CodeIgniter Disallowed Key Characters
Disallowed key characters error message in Codeigniter (v2)
I get "Disallowed Key Characters" when I submit a form.
I have CSRF protection enabled, and I am using arrays in my form field names (i.e., search[] as the name as there are multiple selection dropdown options). I have a feeling it is the "[]" in the form name that bothers this form.
I have followed all advice I could see in the posts above.
I disabled CSRF temporarily,
I disabled XSS temporarily,
I edited $config['permitted_uri_chars'] and
I edited Input.php where this message is generated.
Anybody has any additional ideas of what could cause this problem on form submission?
Thanks!
Like my answer here — you just need to update the regex in MY_Input->_clean_input_keys() to allow more characters (eg escaped JSON, or escaped HTML/XML)
Allow just 'English': !preg_match("/^[a-z0-9\:\;\.\,\?\!\#\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)
Allow Chinese Characters: !preg_match("/^[a-z0-9\x{4e00}-\x{9fa5}\:\;\.\,\?\!\#\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)
My full working function looks like this:
public function _clean_input_keys($str) {
// NOTE: \x{4e00}-\x{9fa5} = allow chinese characters
// NOTE: 'i' — case insensitive
// NOTE: 'u' — UTF-8 mode
if (!preg_match("/^[a-z0-9\x{4e00}-\x{9fa5}\:\;\.\,\?\!\#\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)) {
/**
* Check for Development enviroment - Non-descriptive
* error so show me the string that caused the problem
*/
if (is_env_dev()) {
var_dump($str);
}
exit('Disallowed Key Characters.');
}
// Clean UTF-8 if supported
if (UTF8_ENABLED === TRUE) {
return $this->uni->clean_string($str);
}
return $str;
}
my_helper.php
if (!function_exists('is_env_dev')) {
function is_env_dev() {
return (
defined('ENVIRONMENT') && strtolower(ENVIRONMENT) == 'development' ||
defined('ENVIRONMENT') && strtolower(ENVIRONMENT) == 'testing'
);
}
}
Thanks, but I found a comment hidden way below (right at the bottom at the time of this writing) on another post here: CodeIgniter Disallowed Key Characters
The comment suggested that I add $str to the exit() comment to test. This indicated that I had a missing double quote in my form fields. It is a very complex form built up dynamically, with 300 lines of code, so easy to miss.
Hope this answer (and the comment that inspired it) helps someone else.
Validating the source of the output could prevent problems such as this one :-)
Regards

How to pass & (ampersand symbol) in ajax get or post method?

I have a text box to enter description
If i submits that need to be send through ajax and store in db.
Problem:-
Example text in textbox:- "Hi all & solve my problem"
in the next page i am getting till "Hi all"
Remaining text is missing, If I pass through get or post method using ajax.
Give me the solution. How to get all the content I placed in text box along with "&"
You need to urlencode string with escape or encodeURIComponent functions.
Yes, I have faced same type issue and find out solution that we need to pass data as a key value pair,
I had passed data in Ajax like:
data : email=" + email + "&name='" + name
But right way for passing data in Ajax is :
data: {
email : email,
name : name
}

Resources