Jump to content

Reading data from jquery post


Imrana
Go to solution Solved by JD*,

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

Edited by Imrana
Link to comment
Share on other sites

  • Solution

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.