views:

119

answers:

4

Hi guys, I am trying to send JSON to a PHP file using jQuery AJAX, basically what I am trying to do is get the values and id's of a bunch of child elements and then assign them to a JSON object and then send that object via ajax to the PHP file which would then process it and enter it into a database.

Here is my code,

Javascript/jQuery:

function test(){
    var selects = $('#systems_wrapper').find('.dropDowns');
    var newArray = new Array();

    selects.each(function(){
        var id = $(this).attr('id');
        var val = $(this).val();
        var o = { 'id': id, 'value': val };

        newArray.push(o);
    });

    $.ajax({
            type: "POST",
            url: "qwer.php",
            dataType: 'json',
            data: { json: newArray }
        });

}

PHP:

<?php
    $json = $_POST['json'];
    $person = json_decode($json);

    $file = fopen('test.txt','w+');
    fwrite($file, $person);
    fclose($file);

    echo 'success?';
?>

It creates the file, but it is completely blank, any idea what it could be?

Thanx in advance!

A: 

You could try using the JSON.stringify() method to convert your array into JSON automagically. Just pass the output from this.

data:  { json: JSON.stringify(newArray) }

Hope this helps

mattbasta
A: 

You should set a contentType on your ajax POST. I would use contentType: "application/json";

Marthin
A: 

You should use json_encode() not json_decode()! This way you will get the json string and be able to write it.

Zlatev
A: 

No need to use json_decode if you're saving it to a text file. jQuery is encoding your array in JSON format, PHP should then just write that format right to the text file. When you want to open that file and access the data in a usable way, read its contents into a variable and THEN run json_decode() on it.