CalG CalG - 22 days ago 5
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();

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

book.title=title;
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();

page.links.push(link);
}
book.pages.push(page);
}

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


Here is the PHP:

<?php
$dbhost = 'localhost';
$dbname = 'story';

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

$collection = $db->stories;

$story=$_POST['json'];

if (isset($story)){
$collection->save($story);
}
?>


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

Notice: Undefined index: json

Answer

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:

book.owner=data.username;

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:

$.get().done(function(data){
    /// 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.

Comments