Reputation: 1816
I have a problem when returning an array object and then display it to the user, please look at the demo code. A basic snippet but it has the same idea has been, I just can't post the very long code here.
Class foobar{
public function foo()
{
return array( 'bar' => 'value' );
}
}
This php code was used by another class
Class foobar_fetcher{
public function getFoo()
{
$fb = new foobar();
$result = $fb->foo();
return $result;
}
}
foobar_fetcher is again called by a main executioner file( ajaxdispatcher.php ) - with a json header.
if( isset( $_POST['fetch'] ) ){
$httpresponse = new stdClass();
$fb_fetch = new foobar_fetcher();
$httpresponse->data = $fb_fetch->getFoo();
}
echo json_encode( $httpresponse );
Finally this ajaxdispatcher was called by a jquery ajax.
$.ajax({
url: 'ajaxdispatcher.php',
type: 'post',
data: {fetch:'fetch'},
success: function( data ){
if( data ) console.log( data );
}
});
Now, the when I try to print out the data , it has no response from the server. But when I change the return value of the foo() under foobar Class to an integer or string. Things will work fine.
Upvotes: 1
Views: 87
Reputation: 164901
Some things I would do that may improve your chances of success
Set appropriate HTTP headers and exit
immediately after sending your JSON code
header('Content-type: application/json');
echo json_encode($httpresponse);
exit;
Also make sure you haven't sent any data to the output buffer prior to this.
Tell jQuery the data-type to expect
$.ajax({
dataType: 'json',
// and the rest
Add an error
callback
$.ajax({
// snip
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}
});
Upvotes: 0
Reputation: 2056
You should try to change you ajaxdispatcher to accept a GET request and navigate there from a browser to see what is returned.
if( isset( $_GET['fetch'] ) ){
$httpresponse = new stdClass();
$fb_fetch = new foobar_fetcher();
$httpresponse->data = $fb_fetch->getFoo();
}
echo json_encode( $httpresponse );
Navigate to /ajaxdispatcher.php?fetch=fetch
Upvotes: 2