I am trying to pull random string from database, and then transfer it via json.
But, I am clearly stuck here.
<?php
print_r ($return['user_id']);
json_encode($return);
?>
And the ajax/js
$(document).ready(function() {
$.getJSON('initiate.php', function(data) {
$("#chat-area").html(data);
});
});
It cannot work with:
print_r
dumping garbage (i.e. non-JSON) to the client and thus the JSON parserecho
ing the JSON data.So, what you want, is this:
<?php
// obviously $return needs to contain something. otherwise
// you'll most likely get a notice which is "garbage" too
echo json_encode($return);
?>
After fixing the server-side code you also need to fix your JavaScript. data
is an object and thus it does not make much sense to set it as some element's HTML content. You probably want some property of that object:
$.getJSON('initiate.php', function(data) {
$("#chat-area").html(data.whatever);
});
This is wrong:
print_r ($return['user_id']); // invalidates the json output
json_encode($return); // does not do much...
// should be:
echo json_encode($return);
Be sure to set content-type and to echo the json only.
<?php
//fill $whatever_you_want
header('content-type: application/json');
echo json_encode($whatever_you_want);
?>