Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing HEX colors in an GET ajax call

I'm trying to pass some hex colours to a php script via an GET ajax call. PHP doesn't seem to like the hex colours though, I've tried replacing the # and using encodeURIComponent neither of which work.

here's the js (with each currentColors entry being a hex color)

var dataString = 'designName=test&mc1='+currentColors[1]+'&mc0='+currentColors[0]+'&sp='+currentColors[2];
var strippedString = encodeURIComponent(dataString);
like image 919
Infra Stank Avatar asked Oct 20 '25 10:10

Infra Stank


1 Answers

Use encodeURIComponent to encode URI components:

var strippedString = 
    "designName=test" + 
    "&mc1=" + encodeURIComponent(currentColors[1]) +
    "&mc0=" + encodeURIComponent(currentColors[0]) +
    "&sp="  + encodeURIComponent(currentColors[2]);

Example:

var strippedString = 
    "designName=test" + 
    "&mc1=" + encodeURIComponent("#FF0000") +
    "&mc0=" + encodeURIComponent("#00FF00") +
    "&sp="  + encodeURIComponent("#0000FF");
// "designName=test&mc1=%23FF0000&mc0=%2300FF00&sp=%230000FF"

On the server-side the query string will yield:

// parse_str("designName=test&mc1=%23FF0000&mc0=%2300FF00&sp=%230000FF", $my_GET);
// var_dump($my_GET);

array(4) {
  ["designName"]=>
  string(4) "test"
  ["mc1"]=>
  string(7) "#FF0000"
  ["mc0"]=>
  string(7) "#00FF00"
  ["sp"]=>
  string(7) "#0000FF"
}
like image 99
Salman A Avatar answered Oct 21 '25 23:10

Salman A