Here is my code
var jsonpath;
function loginFromDef() {
var a = grantAccess($('#login :input').serialize());
if (a.Msg) {
$('#msg').html(a.Msg).attr('class', 'error');
}
else if (a.done) {
var returnUrl = getQueryString('ReturnURL');
if (returnUrl)
window.location = returnUrl;
else
window.location = 'Home.aspx';
}
return false;
}
function grantAccess(dataToPost) {
$.ajax({
type: "POST",
url: jsonpath + 'Json.ashx?method=GrantAccess',
async: false,
data: dataToPost,
success: function (data) {
return data;
}
});
}
function getQueryString(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var jsonPath is being defined in Default.aspx page where from I m calling function loginFromDef() on onclick event of submit button.
I am getting error TypeError: a is undefined
Don’t worry about my .ashx handler. It is working fine. I’d test it.
I think var a in function loginFromDef is not being initialized. Because may be jQuery is making asynchronous call. Even I have set async:false in options.
Whats wrong with me..?? Please suggest a solution to this.
You don’t have any return statement in
grantAccess. The return statement inside the callback does not have any effect (since it is called by$.ajaxinternally).The Ajax call is synchronous but you are not returning any data from
grantAccess.You could do:
Maybe you have to use
$.parseJSONbefore you return that value.$.ajaxreturns ajqXHRobject, which you can find more information for in the documentation.However, I strongly suggest to not use synchronous Ajax calls and I don’t see any reason why you would need one here. Synchronous request can potentially block the browser (including its UI) until the response was received, making the browser unresponsive which leads to a bad use experience.
Change your code so that you can use callbacks to handle the response. For example:
where
grantAccesssimply returns thejqXHRobject returned by$.ajax: