Snupas Snupas - 3 months ago 8
Javascript Question

Transferring hash maps over ajax and converting to php array

I'm making an interpreter for a mini language, and I'm storing related information in hash maps. I'm convering those hash maps with JSON stringify, to send them over via ajax to the server side.

This is is the post-JSON stringify code I'm sending over to the server side:

{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}


On the server side, how could I easily make a php array out of the
"kv":["24","23","20"]
bit without searching for certain characters?

Before sending it over ajax the output of json array is:

{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}


After receiving it, the data is:

{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}


after the
htmlspecialchars_decode
function, it becomes:

{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}


json_decoding
that gives me null

The ajax code:

function addValues(jsonArray) {

alert(jsonArray);

$.ajax({

url: 'insertTree.php',
type: 'POST',
data: 'dataToReceive=' + jsonArray,
success: function(data) {
//called when successful
alert(data);
window.location.reload();
},
error: function(e) {
//called when there is an error
console.log(e.message);
}
});

}


the php receiving code:

$dataReceived = htmlspecialchars(strip_tags($_POST["dataToReceive"]));

$dataRefined = htmlspecialchars_decode($dataReceived);

$var = json_decode($dataRefined, true);

var_dump($var['kv']); //null

Answer

Use json_decode to get the value. Since your base string isn't valid JSON, I massaged it a bit to get it to be

$string = '{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}';
$data = explode('|', str_replace('},{', '}|{', $string));

foreach($data as $str) {
    $var = json_decode($str, true);
    if(isset($var['kv'])) var_dump($var['kv']);
}
Comments