Jump to content

Reading data from jquery post


Imrana

Recommended Posts

Hi all,

 

Thank you for taking your time to read my post. I am using php, ajax(jQuery) and json to save data to a database.

 

Here is my JavaScript code:

<script>
var jsonList = [
    {"type":"sw"},
    {"points":[
        {"lat":51.51429786349476,"lng":-0.14556884765625},
        {"lat":51.51435127755925,"lng":-0.1393890380859375},
        {"lat":51.51221466612502,"lng":-0.14277935028076172}
    ]}
];

$.post("save.inc.php",
        jsonList,
        function(res) {
            alert(res);
        }
</script>

I have created a javascript array which holds two json objects. I want to pass this to a php file. The php file needs to save the two json objects seperately. I dont know how to access the data when its gets sent to php. I am new to ajax and json, I have looked for hours on google and cannot find how to read multidimensional $_POST array. Please help.

 

This is what I tried to access the json objects but it does not work.

<?php
//This is save.inc.php

$type = $_POST[0];
$points = $_POST[1];

echo(json_encode($type));
?>

kind regards,

Imran

Link to comment
https://forums.phpfreaks.com/topic/281367-reading-data-from-jquery-post/
Share on other sites

This is a bit more jquery than php, but here's what wrong.

 

First, in your javascript, you need a closing ); and you need to pass your object inside some type of POST variable and stringify it, like this:

$.post("save.inc.php",
        "stuff=" + JSON.stringify(jsonList),
        function(res) {
            alert(res);
        }
);

Then, in your PHP, do the following:

$array = json_decode($_POST['stuff'], TRUE);
print_r($array);

That should get you where you want to go

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.