Page 1 of 1

Jquery PostBody Won't Submit Var With "&" Included

Posted: Tue Sep 29, 2009 3:29 pm
by jbh
What is the best way to remedy this? The exact code that I use to post to a PHP/Mysql script, in the background, is below.
It works perfectly so long as ''&' is not included in the form submission. Should I just declare this var as a qstring and then sanitize it? I am new to this so forgive me if this seems obvious.

For Reference, if I add a value to the form (where I am adding categories to a db) "Test & Test" it will only show 'Test" while omitting the '& Test'. Just fyi.

Code: Select all

function sendRequest() {
                new Ajax.Request("page_I_submit_to.php", 
                    { 
                    method: 'post', 
 
                postBody: '[b]category='+ $F('category'[/b]),
                    onComplete: showResponse 
                    });
                }
 
            function showResponse(req){
                $('show').innerHTML= req.responseText;
            }

Re: Jquery PostBody Won't Submit Var With "&" Included

Posted: Wed Sep 30, 2009 12:01 pm
by kaszu
You need to escape category value, you can use encodeURIComponent to do it:

Code: Select all

postBody: 'category='+ encodeURIComponent($F('category')),
Problem is because & is a delimiter for GET parameters, so having "Test & test" as value produces "category=Test & test", which results in

Code: Select all

$_POST = Array(
    "category" => "Test ",
    " test" => ""
);
encodeURIComponent will escape string for use in uri: "Text%20%26%20test", PHP will 'unescape' it automatically

Re: Jquery PostBody Won't Submit Var With "&" Included

Posted: Wed Sep 30, 2009 1:06 pm
by jbh
Thank you. I wasn't sure how to use the function to clean up the var. THe demos I saw weren't using Postbody and, since Jquery is new (and Ajax)
I was sure I'd muck it up.

Much appreciated.