Passing Value Including Spaces on Ajax Call - php

Trying to pass spaces along with ajax call.
'word' is been passed the same as 'word ' i believe so.
On the other hand two words need to be send completely with call.
'word second' but not the same as
'word second '
Should I trim before call or do this on server side script?
How can I send spaces as well?

To allow a parameter to include spaces, etc. you will want to use the javascript escape() [W3Schools] function.
escape( 'hello world ' ) = 'hello%20world%20';
The handling on the PHP side will automatically decode/unescape the parameter, restoring the spaces (along with any other characters which cannot be part of a parameter's value when sent through AJAX, such as "=" or "&".
Within PHP, if you are wanting to strip off any leading or trailing spaces, you can use the PHP trim() [PHP.net] function.
trim( 'hello world ' ) = 'hello world';

I know this is an old question, but I'd like to point out that the accepted answer is suggesting a function that is deprecated as of JavaScript version 1.5.
Instead, you should use either encodeURI() or encodeURIComponent() for sending spaces and other special characters.
var param = encodeURIComponent("word second ");
console.log(param); // outputs 'word%20second%20'
PHP on the other end will handle the decoding automatically. You should trim server side, as client side code can be edited by users to circumvent trimming, potentially causing bugs or vulnerabilities.

The simplest way, I think, is to encodeURIComponent string in javascript before sending xmlhttprequest, and then urldecode it in PHP

Related

How to find another way of using "&" in post request in Swift

I am doing a post HTTP request in swift 4.2 and in one of my Strings I put in the parameters contain "&" but apparently the requests gets cut off after this symbol. I thought about replacing every "&" symbol with a unique placeholder and convert it back in PHP.
But is there are more elegant or easy way of doing this?
URL encode your data (and decode it when you need to use it), that will make the ampersand into %26 which will stop it cutting off in your GET request.
You could replace the "&" with "%26" and then it's have to work :)
All Precent-encoding characters:
https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters
You should probably minimize how much manual percent escaping you do. You might, for example, use URLComponents to build your URL and percent escape it for you:
guard var components = URLComponents(string: "http://example.com") else { return }
components.queryItems = [URLQueryItem(name: "foo", value: "bar&baz")]
let url = components.url
That will result in:
http://example.com?foo=bar%26baz
The ampersand, as well as a few other characters, need to be encoded if they are within a query parameter otherwise they could be recognized as a delimiter of some sort.
You can encode a string for a query param in Swift like this:
let value = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let urlString = "https://example.com/?query=\(value)"
On the other side, your server will receive the encode param value but will need to decode it.
PHP includes the urlencode() and urldecode() functions, and stift includes the .addingPercentEncoding function.
This means you can replace with the encoded version of the '&' symbol which is '%26', or you can use swift's function
Then when you recieve this value you can use urldecode( $escapedString ), or just replace '%26' with '&', or just pull the values stright from the request with $_GET.

Javascript string/variable concatenation without space

while using a ajax script, I made the php part echo a value then in the jQuery part I alert it.
So we have something like this:
<?php echo "1"; ?>
//Javascript
alert("the value is"+phpvalue);
The alert shows up like "the value is 1". Now my question is how do I remove the space between the "the value is" and +phpvalue? So it show up like "the value is1". I tried trim() on the php part but it doesn't change anything.
Apreciate any help and sorry if it is a noob question =/
In http response can be some other caracters than what you print. For example, if there is spaces before php tag .. BOM character in the begining of the php file... so if you trim just the variable, that does not detemrimate, that you get purely the variable on client side without junk characters.
So you should use trim on client side in javascript:
For example jQuery trim (http://api.jquery.com/jQuery.trim/)
alert("the value is"+$.trim(phpvalue));
Or use nativ js trim function from phpjsorg (http://phpjs.org/functions/trim/):
alert("the value is"+trim(phpvalue));
Not sure exactly what you want but here are two situations
If you just are dealing with excess whitespace on the beginning or end of the string you can use trim(), ltrim() orrtrim() to remove that.
If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " "
$foo = preg_replace( '/\s+/', ' ', $foo );

Escape a url within a regular expression in a preg_replace

I am trying to redirect some tags to another page, passing its href as a url parameter. The code I'm using is something like this:
preg_replace(
"/<a(\s[^>]*)href=[\"\']??([^\" >]*?)[\"\']??([^>]*)>(.*)<\/a>/siU",
"<a$1href=\"".WWW."go.php?to=".urlencode("$2")."\"$3>$4</a>", $text
);
It is a modified version of the regexp found here. I use this code in this block:
$text = "<...some other tags...><a target=\"_blank\" href=\"http://www.google.com\" style=\"...\" class=\"...\">Google</a></...some other tags...>";
And it correctly gets captured, but when using urlencode("$2"), it recieves a "$2" string, and not the value stored in the preg variables (as I would). It is not limited to urlencode, but to passing this as a parameter to any other function. So I would not only want to encode this (I can always extend a little more the regexp to accept urls) but generally use variables inside methods.
Do you know any workaround to this? Thanks in advance.
this is totally normal as your are url encoding the string "$2" and then the urlencoded string is used for replacement so you end up with the same thing as writing
"<a$1href=\"".WWW."go.php?to=$2\"$3>$4</a>"
as second parameter. If you want the urlencode to be evaluated you have to use the e (for eval) flag like this:
preg_replace(
"/<a(\s[^>]*)href=[\"\']??([^\" >]*?)[\"\']??([^>]*)>(.*)<\/a>/seiU",
"'<a$1href=\"'.WWW.'go.php?to=\"'.urlencode('$2').'\"$3>$4</a>'", $text
);
another preferable solution may be to use preg_replace_callback to avoid relying on evaluating unknown strings

Replacing backslash with another symbol in PHP

Been struggling with replacing a backslash by another symbol such as '.-.' just to indicate the position of backslashes as I could not send a string such as 'C\xampp\etc.' through url as GET variable so I thought I'd first replace the backslashes in that string by another symbol, then send through url, and then replace them back to backslashes in the PHP file that handles it. Though would there be a better way to send such strings through url? Because when I try a script such as:
$tmp_name = preg_replace("\", ".-.", $_FILES['uploadfile']['tmp_name']);
It turns out into a php error as \ is also used as delimiter..
Could anyone help me out on this?
Thanks in advance!
Btw, if I'd be able to send a full array through url, this whole problem would be solved, but I don't think it's possible?
The regex used in preg_replace should be enclosed in a pair of delimiter and also Try using \\\ instead of \ as:
$tmp_name = preg_replace("{\\\}", ".-.", $_FILES['uploadfile']['tmp_name']);
EDIT:
To reverse the substitution you can do:
$str = preg_replace('{\.-\.}',"\\",$str);
You need to escape the . to match a literal dot.
use urlencode()/urldecode().
echo urlencode('C:\xampp\etc'); // C%3A%5Cxampp%5Cetc
BTW: This sounds like a huge security flaw (sending absolute paths by request)
PS: preg_replace() is for regular expressions. Try str_replace() next time.
Btw, if I'd be able to send a full array through url, this whole problem would be solved, but I don't think it's possible?
That's easy. PHP:
$url = 'http://example.com/?array=' . urlencode(serialize($array)); // html
$array = unserialize($_GET['array']); // server side
Or Javascript:
url = "http://example.com/?array=" + encodeURIComponent(JSON.stringify(array)); // client
$array = json_decode($_GET['array']); // server
(for Javascript you'll have to look up whether encodeURIComponent is correct, and you need the official JSON library as well)
If you're not using a regular expression (which you're not), you should use str_replace instead:
$tmp_name = str_replace('\\', '.-.', $_FILES['...']);
Note that you have to escape the \ with another \ (otherwise it'd escape the following ').
As for the delimiter error - regular expressions need to be enclosed in delimeters, for example /foo/ (/ is the delimiter, foo is the pattern). But, again, there's no need for you to use or worry about regexps

How do I post long strings that contain special characters (like '&' specifically) via an AJAX request?

I'm looking to make a Contact/Query form, wherein the end user can send an email to the webmaster. The form has a 'textarea' field, which captures long strings from the user, if I use AJAX to submit the form using GET method, my params tend to break if their is a special character, specifically '&' in the textarea's string..
I'm stuck please help!
Try calling encodeURIComponent in your javascript when posting the request.
You can make the string URL safe using JavaScript urlencode...
var textToSend = encodeURIComponent(myform.myfield.value);
This will convert all special characters into URL encoded characters.

Categories