Odyss3us
Odyss3us

Reputation: 6635

Sending JSON via AJAX to PHP using jQuery

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!

Upvotes: 12

Views: 25975

Answers (5)

Guilherme
Guilherme

Reputation: 1990

Don't use an array.
use a simple string like this:

var o = '[';
selects.each(function(){
    var id = $(this).attr('id');
    var val = $(this).val();
    o += '{ "id": "'+id+'", "value": "'+val+'" },';    
});
o = o.substring(0,o.length-1);
o += ']';

and in the ajax just send the string 'o'

        data: { json: newArray }

in the php file just make a json_decode($json, true);
it will return an array of array that you can access by a foreach
if you want to see the array, use var_dump($person);

Upvotes: 2

phx_zs
phx_zs

Reputation: 147

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.

Upvotes: 1

Z. Zlatev
Z. Zlatev

Reputation: 4820

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

Upvotes: 1

Marthin
Marthin

Reputation: 6543

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

Upvotes: 1

mattbasta
mattbasta

Reputation: 13709

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

Upvotes: 19

Related Questions