Eae
Eae

Reputation: 4321

jQuery .ajax pass the whole JavaScript array to PHP

tdata = new Array();  
tdata['id'] = "helloid";  
tdata['name'] = "helloname";  
tdata['location'] = "hellolocation";  
tdata['about'] = "helloabout";  
tdata['company'] = "hellocompany";  
tdata['website'] = "hellowebsite";  

$.ajax({
    url: 'export.setsession.php',
        data: { tdata: tdata.id 
    },
    type: 'post',
    success: function (output) {
        //$(location).attr('href', 'index.php');
        alert("girdsposted");
    }
});

The above is working just fine but I would like to pass the array as a whole if that is possible like data: { tdata: tdata } as opposed to only passing the id. Is this possible to do or is there an alternative? I have not yet been able to get the whole array into PHP is some form I can read...

Thanks in advance...

Upvotes: 1

Views: 102

Answers (2)

Thomas Johnson
Thomas Johnson

Reputation: 96

Have you considered using the JSON.stringify() method, which will transform your tdata element into a JSON string :

data: JSON.stringify(tdata)

Upvotes: 2

Shoe
Shoe

Reputation: 76270

Create a JSON string with:

JSON.stringify({ json: tdata });

and then convert it to a PHP array with:

json_decode($data);

Upvotes: 4

Related Questions