Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Value Including Spaces on Ajax Call

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?

like image 387
Codex73 Avatar asked Sep 23 '10 00:09

Codex73


People also ask

What is processData in Ajax?

processData. If set to false it stops jQuery processing any of the data. In other words if processData is false jQuery simply sends whatever you specify as data in an Ajax request without any attempt to modify it by encoding as a query string.

What is difference between success and complete in Ajax?

success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.

What are required attributes for AJAX call?

type: It is used to specify the type of request. url: It is used to specify the URL to send the request to. username: It is used to specify a username to be used in an HTTP access authentication request. xhr: It is used for creating the XMLHttpRequest object.

Do Ajax calls pass cookies?

Basically, ajax request as well as synchronous request sends your document cookies automatically.


2 Answers

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';
like image 193
Luke Stevenson Avatar answered Oct 01 '22 05:10

Luke Stevenson


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.

like image 30
Adrian Wiik Avatar answered Oct 01 '22 05:10

Adrian Wiik