Sending and consuming JSON with Query String Variables (PHP)
Query String Variables (also called query string parameters or URL variables). You’ve seen them before, they look like this:
https://en.wikipedia.org/wiki/Query_string?title=Query_string&action=edit
They’re useful for linking users to some variation of a page. But they have other uses, like sending data to an <iframe>
, which is what I had to do in this scenario.
Here’s what an array looks like in PHP:
$arr = array(
'a' => 1,
'b' => 2,
'c' => array(
'd' => 'lorem',
'e' => 'ipsum'
)
);
// var_dump($arr):
array(3) {
["a"]=>
int(1)
["b"]=>
int(2)
["c"]=>
array(2) {
["d"]=>
string(5) "lorem"
["e"]=>
string(5) "ipsum"
}
}
It’s not the prettiest thing ever and it’s a long way from being safe to send as a query string variable.
Luckily PHP includes some default methods that can help with that. First is json_encode()
:
$json = json_encode($arr);
// output
=> "{"a":1,"b":2,"c":{"d":"lorem","e":"ipsum"}}"
So that already looks like something you could use in JavaScript, but it’s not ready to be used in a URL yet, because URLs will only accept certain symbols and characters. And that is where PHP’s urlencode()
comes in:
$url_encoded_json = urlencode($json);
// output
"%7B%22a%22%3A1%2C%22b%22%3A2%2C%22c%22%3A%7B%22d%22%3A%22lorem%22%2C%22e%22%3A%22ipsum%22%7D%7D"
So that’s been significantly uglified, but we can fix that soon. The important thing is it’s ready to use like so:
https://myiframehost.com/form?title="Lorem Ipsum"&data="%7B%22a%22%3A1%2C%22b%22%3A2%2C%22c%22%3A%7B%22d%22%3A%22lorem%22%2C%22e%22%3A%22ipsum%22%7D%7D"
Then to decode the query string data in JavaScript, use:
function getUrlVar(str, val) {
var result = new RegExp(val + "=([^&]*)", "i").exec(str);
return (result && unescape(result[1])) || null;
}
var data = getUrlVar(document.URL, "data");
if (data) {
var decodedData = JSON.parse(decodeURIComponent(data));
}
This should give you some nice valid JSON. Lovely jubbly.