Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 299
Odyss3us Avatar asked Sep 08 '10 12:09

Odyss3us


People also ask

How to send JSON data in AJAX request using jQuery to PHP?

jQuery / AJAX Basic AJAX function to pass the JSON data to the server-side script. $. ajax({ type: "POST", url: targetURL, async: false, data: JSON. stringify($('#form').

How to get JSON response using AJAX?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

Can you use AJAX with JSON?

According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.

Can AJAX be used with PHP?

Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.


1 Answers

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

like image 153
mattbasta Avatar answered Sep 17 '22 14:09

mattbasta