• 0

jQuery AJAX Json help?


Question

I have some code that's not working for me...

JavaScript:

function getPasswordStrength(iPassword){
	var strength;
	returnVals = $.post(
		"/ajaxHandlers/checkPassword.php",
		{iWord:iPassword},
		function(returnData){
			alert(returnData.strength);
			return [returnData.strength,returnData.warning];
		},
		"json"
	);
	alert(returnVals.strength);
}

The url returns the following JSON:

{"strength":0,"warning":"Please enter a password."}

The area I am strugling with is the final alert although the error could be elsewhere...

The alert within the ajax function shows the integer value 0.

The alert at the bottom shows "undefined"... I need to access the value 0 here...

Help?

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

I think your problem is the code racing against itself.

Despite being farther down in the script, the final alert is actually getting called before the Ajax request has had a chance to finish.

If you replace the final alert with this, I'd wager you'll see that the XMLHttpRequest state is no where close to 4 (complete).

alert(returnVals.readyState);

Basically, whatever you need to do with the response should be done within the $.post() callback function.

Link to comment
Share on other sites

  • 0

Yeah, Hot is on the right lines, what would be happening is that you are expecting a return value from the $.post. Because the $.post is an asynchronous operation, the $.post function will not return anything, but if you work your function to include a callback, you can then delegate what will happen with the response:

function GetPasswordStrength(password, callback)
{
  $.ajax({
    url: "/ajaxHandlers/checkpassword.php",
    type: "POST",
    data: { iWord: password },
    dataType: "json",
    success: function(result) { if (callback) callback(result); }
  });
}

$("#password").change(function() {
  var password = $(this).val();
  GetPasswordStrength(password, function(result) {
    alert(result.strength + " - " + result.warning);
    // In this callback function is where you would update your UI.
  });
});

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.