0

I'm newbie with JQuery.

I got this function

function verify_at_bd() {
  var u = "foo";
  var p = "bar";

  return $.post('auth.php', {
      name: u,
      password: p,
      mobile: ''
    },
    function(result) {
      return result;
    }, 'json');
}

If I do a console.log(verify_at_bd()) I'm getting an xmlhttprequest but cannot access to responseText property. I'm using header("Content-Type: application/json") in the PHP script.

I'm using firefox 3.6 on OS X.

1
  • there is a structural flaw in this code: the function will never produce a result because $.post is asynchronous. if you include the code that calls the verify_at_bd function, somebody may show you how to get it working. Commented May 19, 2010 at 5:29

3 Answers 3

2

Here goes:

$.ajax({
  type: 'POST',
  url: 'auth.php',
  data: {name: 'foo', password: 'bar', mobile: ''},
  success: function(result, textStatus, xmlhttprequest){
        console.log( $.parseJSON(xmlhttprequest.responseText).status);
    },
  dataType: 'json'
});

That's all.

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

Comments

1

Well, firstly, the XHR must be in readyState 4 to get responseText.

Secondly, it looks to me like you are abusing $.post(). It is an asynchronous call, you do not process the result of $.post(), you deal with the result in your success method (function(result)).

If you really need the reponseText, then add a few more arguments to your success function and catch the xhr there.

See jquery docs for $.post to see which arg is the xhr.

Comments

0

As @code poet said, you're utilizing the $.post method in an awkward way. It is an asynchronous call, so you can't expect to see the result returned to you immediately until the AJAX POST request completes. If you could post the code you've written to handle the JSON you expect this function to return, it would be easier to advise you on a proper way to structure your $.post response.

Comments

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.