1

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.

1
  • 1
    Cant reproduce, seems to work, is this the actual code? or pseudo : codepad.org/yAv7aX2J Commented Aug 23, 2012 at 5:18

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I have already tried this method. It works fine. But when displaying it to the ajax, it has no response.
What browser are you using? If you are using Chrome, you can inspect the request and response and see where it's going wrong.
0

Some things I would do that may improve your chances of success

  1. 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.

  2. Tell jQuery the data-type to expect

    $.ajax({
        dataType: 'json',
        // and the rest
    
  3. Add an error callback

    $.ajax({
        // snip
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(jqXHR, textStatus, errorThrown);
        }
    });
    

1 Comment

@KennethPalaganas So what was the problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.