Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Monday, February 2

json_encode 'php array' to a 'json array'

Array in JSON are indexed array only, so the structure you're trying to get is not valid Json/Javascript.

PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.

If you want to get such structure you can do:

<?php
    $indexedOnly = array();
    
    foreach ($associative as $row) {
        $indexedOnly[] = array_values($row);
    }
    
    json_encode($indexedOnly);
?>

Will returns something like:

[
     [0, "name1", "n1"],
     [1, "name2", "n2"],
]

Tuesday, January 27

jQuery ajax, to send JSON instead of QueryString

You need to use JSON.stringify to first serialize your object to JSON, and then specify the content-type so your server understands it's JSON. This should do the trick:

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

Setting processData to false isn't necessary since JSON.stringify already returns a string.