views:

92

answers:

2

I have a real simple form with a textbox and a button, and my goal is to have an asynchronous request (jQuery: $.ajax) send the text to the server (PHP/mysql a la Joomla) so that it can be added to a database table.

Here's the javascript that is sending the data from the client:

var value= $('#myvalue').val();

$.ajax( {
    type:       "POST",
    url:        "/administrator/index.php",
    data:       {   option: "com_mycomponent",
                    task:   "enterValue",
                    thevalue: value,
                    format: "raw"},
    dataType:   "text",
    success:    reportSavedValue
} );

The problem arises when the user enters text with a space in it. The $_POST variable that I receive has all the spaces stripped out, so that if the user enters "This string has spaces", the server gets the value "Thisstringhasspaces".

I have been googling around, and have found lots of references that I need to use encodeURIComponent. So I have tried it, but now the value that I get from $_POST is "This20string20has20spaces".

So it appears to be encoding it the way I would expect, only to have the percent signs stripped instead of the spaces, and leaving the hex numbers.

I'm really confused. It seems that this sort of question is asked and answered everywhere on the web, and everywhere encodeURIComponent is hailed as the silver bullet. But apparently I'm fighting a different breed of lycanthrope. Does anyone have any suggestions?

A: 

Could I trouble you to try this, please?

var value = escape($('#myvalue').val());
GlenCrawford
Sure thing. I tried it and it has the same result as var value = encodeURIComponent($('#myvalue').val()); -- the server picks up a value with '20' in place of all the spaces.
J Jones
+1  A: 

It turns out that there was extra filtering I didn't realize I was performing. Because this was all running through Joomla, I was using JRequest::getCmd('thevalue') instead of $_POST['theValue]. This function, it turns out, filters out all those troublesome characters, like '%'.

So the final solution is to use encodeURIComponent on the client, as is unanimously suggested on the web:

var value = encodeURIComponent($('#myvalue').val());

And on the server, to trade getCmd() for getVar() which allows more control over the filtering, in combination with urldecode():

$value = urldecode(JRequest::getvar('thevalue', JREQUEST_ALLOWHTML));

Again, big thanks to Karim79 and Cesar. I dub thee Harker and Helsing -- my heroes for the day! :)

J Jones