Solved

jquery function returning undefined

Posted on 2014-02-28
13
1,174 Views
Last Modified: 2014-03-01
Hi,

I have a jscript function which I call;

var $text = runUsernameAjax('CheckUsername', 'username', $("#<%=UsernameTextbox.ClientID%>").val());
alert($text);

Open in new window


function runUsernameAjax(webmethod, fieldname, fieldtext) {

            //alert('in ajax method' + webmethod + ":" + fieldname + ":" + fieldtext);

            $(function () {
                $.ajax({
                    type: "POST",
                    url: "default.aspx/CheckUsername",
                    data: JSON.stringify({ username : fieldtext }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            if (data) {
                                $text = "Congratulations " + fieldtext + " is available.";
                                //return text;
                            }
                            else {
                                alert("Unfortunately " + fieldtext + " is not available.");
                                return "Unfortunately " + fieldtext + " is not available.";                               
                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            return thrownError;
                        }
                    });
            });

        }

Open in new window


Now am I doing something wrong as it is always returning undefined? also as I have a number of webmethods which take different values I was going to add the following but it would not work, any ideas why?

function runUsernameAjax(webmethod, fieldname, fieldtext) {

            //alert('in ajax method' + webmethod + ":" + fieldname + ":" + fieldtext);

            $(function () {
                $.ajax({
                    type: "POST",
                    url: "default.aspx/" + webmethod,
                    data: JSON.stringify({ fieldname : fieldtext }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            if (data) {
                                $text = "Congratulations " + fieldtext + " is available.";
                                //return text;
                            }
                            else {
                                alert("Unfortunately " + fieldtext + " is not available.");
                                return "Unfortunately " + fieldtext + " is not available.";                               
                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            return thrownError;
                        }
                    });
            });

        }

Open in new window

0
Comment
Question by:flynny
  • 6
  • 6
13 Comments
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 39895115
Did you look in the console to see what is undefined.  Maybe give us a link to your sample page.  

If you surf to the url here will you get data?   url: "default.aspx/CheckUsername",
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39895136
Just add : async:false
Short :
function runUsernameAjax(webmethod, fieldname, fieldtext) {

	//alert('in ajax method' + webmethod + ":" + fieldname + ":" + fieldtext);
	var $text = "";
	$.ajax({
		type: "POST",
		async: false,
		url: "default.aspx/" + webmethod,
		data: JSON.stringify({ fieldname : fieldtext }),
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (data) {
			if (data) {
				$text = "Congratulations " + fieldtext + " is available.";
			}
			else {
				alert("Unfortunately " + fieldtext + " is not available.");
				$text "Unfortunately " + fieldtext + " is not available.";                               
			}
		},
		error: function (xhr, ajaxOptions, thrownError) {
			return thrownError;
		}
	});
	return $text;
}

Open in new window


But you should use promise : https://api.jquery.com/promise/
0
 

Author Comment

by:flynny
ID: 39895143
sorry I was messing with the code and i realise that the success doesnt return anything in the code i posted above;

the commented out //return text was returning the string in $text.

Also I have tried alerting the text before it was returned and it was valid. It seems to be losing focus of the variable when returning from the AJAX call?

The /CheckUsername is webmethod in my ASPX.CS file. This is being called as I have add breakpoints to test this.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39895158
You need to learn abou Asynchonous and Synchronous operation to understand
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
0
 

Author Comment

by:flynny
ID: 39895223
sorry leakim971,

I missed your first post due to typing my post after you commented. I have the following code now;

$text = runUsernameAjax('CheckUsername', 'username', $("#<%=UsernameTextbox.ClientID%>").val());

alert($text);

Open in new window


function runUsernameAjax(webmethod, fieldname, fieldtext) {

            $(function () {
                $.ajax({
                    type: "POST",
                    async: false,
                    url: "default.aspx/CheckUsername",
                    data: JSON.stringify({ username : fieldtext }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            if (data) {
                                return "Congratulations " + fieldtext + " is available.";
                               
                            }
                            else {
                                return "Unfortunately " + fieldtext + " is not available.";                               
                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            return thrownError;
                        }
                    });
            });

        }

Open in new window


but still it returns undefined?

would you still recommend promise() in this instance?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39895229
I have the following code now;

What about MY code?
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:flynny
ID: 39895323
sorry didn't see that post either;

function runUsernameAjax(webmethod, fieldname, fieldtext) {

            //alert('in ajax method' + webmethod + ":" + fieldname + ":" + fieldtext);
            var $ajaxtext = "";
            $.ajax({
                type: "POST",
                async: false,
                url: "default.aspx/CheckUsername" ,
                data: JSON.stringify({ username : fieldtext }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data) {
                        $ajaxtext = "Congratulations " + fieldtext + " is available.";
                    }
                    else {
                        alert("Unfortunately " + fieldtext + " is not available.");
                        $ajaxtext = "Unfortunately " + fieldtext + " is not available.";                               
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    return thrownError;
                }
            });
            return $ajaxtext;

        }

Open in new window


this is working thank you.

why do I need this to be asyncronous as should it not return at the end of the call?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39895340
I added an link too
0
 

Author Comment

by:flynny
ID: 39896045
Ok thanks for the link.

 that how would I use the .promise() in this case. i.e.

function runUsernameAjax(webmethod, fieldname, fieldtext) {

            //alert('in ajax method' + webmethod + ":" + fieldname + ":" + fieldtext);
            var exists;

            var promise = $.ajax({
                type: "POST",
                url: "default.aspx/CheckUsername" ,
                data: JSON.stringify({ username : fieldtext }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    exists = data;
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    return thrownError;
                }
            });

            promise.promise().done(function () {
                //alert('here');
                var $ajaxtext = "";

                if (exists) {
                    $ajaxtext = "Congratulations " + fieldtext + " is available.";
                    highlightFieldMessage($('#<%=UsernameTextbox.ClientID%>'), true, $ajaxtext);
                    highlightField($('#<%=UsernameTextbox.ClientID%>'), true);
                }
                else {
                    $ajaxtext = "Unfortunately " + fieldtext + " is not available.";
                    highlightFieldMessage($('#<%=UsernameTextbox.ClientID%>'), false, $ajaxtext);
                    highlightField($('#<%=UsernameTextbox.ClientID%>'), false);
                }

            })

        }

Open in new window


am i missing something here? as far as I can see this should trigger at the end of the successful call?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39896055
runUsernameAjax('CheckUsername', 'username', $("#<%=UsernameTextbox.ClientID%>").val()).done(function(__text__) {
      alert(__text__);
});

Open in new window

0
 

Author Comment

by:flynny
ID: 39896229
thanks for that I the alert isn't firing?

I have the following;

runUsernameAjax('CheckUsername', 'username', $("#<%=UsernameTextbox.ClientID%>").val()).done(
                        function (__exists) {
                            alert('done');
                            $ajaxtext = "";
                                if (__exists) {
                                    $ajaxtext = "Congratulations " + $("#<%=UsernameTextbox.ClientID%>").val() + " is available.";
                                    highlightFieldMessage($('#<%=UsernameTextbox.ClientID%>'), true, $ajaxtext);
                                    highlightField($('#<%=UsernameTextbox.ClientID%>'), true);
                                }
                                else {
                                    $ajaxtext = "Unfortunately " + $("#<%=UsernameTextbox.ClientID%>").val() + " is not available.";
                                    highlightFieldMessage($('#<%=UsernameTextbox.ClientID%>'), false, $ajaxtext);
                                    highlightField($('#<%=UsernameTextbox.ClientID%>'), false);
                                }
                        });

Open in new window


        function runUsernameAjax(webmethod, fieldname, fieldtext) {

            $.ajax({
                type: "POST",
                url: "default.aspx/CheckUsername",
                data: JSON.stringify({ username: fieldtext }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    return data;
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    return thrownError;
                }
            });

        }

Open in new window


Do I still need to return the variable compltely outside and keep the promise in the method?
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39896244
runUsernameAjax('CheckUsername', 'username', $("#<%=UsernameTextbox.ClientID%>").val()).done(function(__text__) {
      alert(__text__);
});

Open in new window


        function runUsernameAjax(webmethod, fieldname, fieldtext) {

           return  $.ajax({
                type: "POST",
                url: "default.aspx/CheckUsername",
                data: JSON.stringify({ username: fieldtext }),
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });

        }

Open in new window

0
 

Author Closing Comment

by:flynny
ID: 39897761
I really appreciate both the help and quick replies.

Many thansk I now understand much more clearly.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SSRS ReportViewer report timeout 7 103
SQL Login 17 38
ASP.net Javascript use multiple sliders 2 18
how to avoid redundand ajax calls 5 6
OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

29 Experts available now in Live!

Get 1:1 Help Now