CalG CalG - 2 months ago 12
Ajax Question

Post JSON to PHP in AJAX for MongoDB Querying

I am constructing a Javascript object. I am using the id of user who is logged in (from a session variable) and storing it as an attribute with AJAX.

I wanted to post the resulting object as JSON via AJAX to a PHP file which then inserts the document into a MongoDB database:

var numpages=$('.page').length;

var book=new Object();

type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(data){
var user=JSON.parse(data);

book.pages=new Array();

var page;
var link;

for (var i=0;i<numpages;i++){
var numlinks=$('#p'+i+' .link').length;
page=new Object();
page.text=$('#p'+i+' .textarea').text();
page.links=new Array();

for (var j=0;j<numlinks;j++){
link=new Object();
link.text=$('#p'+i+'l'+j+' .linktext').text();
link.locale=$('#p'+i+'l'+j+' .locale').text();


data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
success: function(msg) {
//var story=JSON.parse(msg);

Here is the PHP:

$dbhost = 'localhost';
$dbname = 'story';

$m = new MongoClient("mongodb://$dbhost");
$db = $m->$dbname;

$collection = $db->stories;


if (isset($story)){

The document is being inserted into the database but I get this:

Notice: Undefined index: json


You have two problem, first being that ajax is async unless you specify the async flag to false which you probably don't want to do so:


Is likely to actually be empty when you come to JSON encode in the second ajax call.

To solve this you can use JQuery promises like so:

    /// extra processing
}).then(function(){ $.get() // etc });

This will ensure that one Ajax calls runs after the other.

As for the missing index you don't actually need to stringify your data at all instead you can just do:

$.get('some_url', {book: book})

And JQuery will actually serialize it for you ready for PHP.