0

I try to make shopping cart with case below:

I have button onclick=addItem(action,cat_no) Will fire this function when click:

function addItem(action,cat_no) {
    switch(action) {
        case "adds":
            queryString = 'action='+action+'&cat_no='+cat_no;
             execute ajax adds...}
        break;
        case "drop":
            queryString = 'action='+action+'&cat_no='+cat_no;
             execute ajax drop...}

This function pass the value to php script.

I found that if I have the item with cat_no having '+' and '&' will fail.

For Example let say: cat_no = 'SS+03L',

I believe it is because when it puts this value into the queryString, the '+' became the operator instead of value:

queryString = 'action='adds'&cat_no='SS+03L; 

(When I check echo $_GET['cat_no'] I only get 'SS' instead of 'SS+03L')

In this case, what can I do to make sure the 'SS+03L' can be put correctly into the query and pass to the php?

P. Lau
  • 165
  • 1
  • 11

1 Answers1

1

First You require to encode that operator characters using encodeURIComponent() in javascript

encodeURIComponent( 'SS+03L') // will be "SS%2B03L" then pass to php

//in your case> queryString = 'action='+action+'&cat_no='+encodeURIComponent(cat_no);

and then 'if you require' to decode in php you can do it using urldecode() to get original string back

urldecode("SS%2B03L") /*you will get 'SS+03L' back and construct your query then*/

hope it helps!

DexJ
  • 1,264
  • 13
  • 24
  • I only use: queryString = 'action='+action+'&cat_no='+encodeURIComponent(cat_no); It already works, how come? no need to urldecode at php. – P. Lau Dec 14 '17 at 04:57
  • Do I really need urldecode in php? If not then what is that for? – P. Lau Dec 14 '17 at 04:59
  • I jsut check php manual says: The superglobals $_GET and $_REQUEST are already decoded. Using urldecode() on an element in $_GET or $_REQUEST could have unexpected and dangerous results. – P. Lau Dec 14 '17 at 05:04
  • well @P.Lau thank you for reading docs. actually i'm formally python guy now i and just forgot that part :P – DexJ Dec 14 '17 at 05:34