user4607502
user4607502

Reputation:

Undefined error where it shouldn't be Jquery

enter image description here

I get this error when doing this:

var request = 'randomcode';
$.post('../php/forms/postrequest.php', 'type=' + request, function (response) {
    var accesscode = response;
});
alert(accesscode);

But it seems correct... What's the error?

Upvotes: 1

Views: 29

Answers (2)

Shyju
Shyju

Reputation: 218732

because you declared the variable accesscode inside the post callback method scope.

var request = 'randomcode';
$.post('../php/forms/postrequest.php', 'type=' + request, function (response) {
    var accesscode = response;
    alert(accesscode);
});

You may define it outside and use the variable outside of your callback method scope to alert. But the value from server may not be available as ajax is asynchronous and you may be accessing the variable value even before your ajax code received the response.

var request = 'randomcode';
var accesscode ='inital value';
$.post('../php/forms/postrequest.php', 'type=' + request, function (response) {
    var accesscode = response;

});
alert(accesscode);  // will alert('initial value')

If you try the above code, you might get the alert inital value because your alert line might get executed even before you $.post received a response from the server.

Upvotes: 1

Farhan
Farhan

Reputation: 1483

sometime $.post request took more time to success, and next code if depended of $.post body then we would face such condition, Do like this

var request = 'randomcode';
var accesscode = "";
$.post('../php/forms/postrequest.php', 'type=' + request, function (response) {
    accesscode = response;
});
alert(accesscode);

or like this

var request = 'randomcode';
$.post('../php/forms/postrequest.php', 'type=' + request, function (response) {
   var accesscode = response;
alert(accesscode);
});

Upvotes: 1

Related Questions