JMan
JMan

Reputation: 1805

$.post always returns undefine

When I make the following jQuery call

$.post('/publish/comments', 
  parms,
  function(data, textStatus){
    console.log('textStatus: ' . textStatus);
    console.log('returned data: ' . data);
    console.log('nextPage: ' . data.nextPage);
  },
  "json"
); 

the console shows that data, textStatus, and data.nextPage are all undefined.

But in the Chrome dev tools (network tab) I can see that the following JSON data is being pass back from the server.

{success:true, nextPage: /go/page/requestId/182/src/publish}
nextPage: "/go/page/requestId/182/src/send"
success: true

Thoughts?

Upvotes: 2

Views: 95

Answers (3)

Aaron Digulla
Aaron Digulla

Reputation: 328566

Try this code pattern to log to the console:

console.log(['textStatus', textStatus]);

This allows to print a message and an object to the console.

That said, 'textStatus: ' . textStatus is undefined because JavaScript strings don't have a property textStatus (. is the "access property" operator not the PHP concat operator)

Upvotes: 1

Rafay
Rafay

Reputation: 31033

you need to concat using + operator not the . as used in php

$.post('/publish/comments', 
       parms,
       function(data, textStatus){
                            console.log('textStatus: ' + textStatus);
                            console.log('returned data: '+ data);
                            console.log('nextPage: ' + data.nextPage);    
       },
       "json"
       ); 

Upvotes: 3

Doug Molineux
Doug Molineux

Reputation: 12431

As Felix pointed out concats need "+"

Also, I have found that if you want to log an entire object, you don't want to include strings inside your console.log().

Try console.log(data) instead of putting strings before it (like "data: ") this will guarantee that the whole object can be seen in the console.

Upvotes: 7

Related Questions