ajax, jquery and web method in asp.net

Tony Trapp
Tony Trapp used Ask the Experts™
on
I dont know what I am doing wrong, in the jquery it looks fine and I had a alert(data) i see everything going to the server side page, but the response is undefined, any way this is client side code and server side code:

Client side:
            $("#listingerrorSnd").click(function () {
                   var GenName = document.getElementById("<%: anonName.ClientID %>").value;
                   var fromEmail = document.getElementById("<%: anonEmail.ClientID %>").value;
                   var GenSubject = document.getElementById("<%: typeErr.ClientID %>").value;
                   var GenMsg = document.getElementById("<%: TMNmsg.ClientID %>").value;
                   var Esname = document.getElementById("<%: escortName.ClientID %>").value;
                   var data = "{'name': '" + GenName + "', 'fromEmail': '" +
                               fromEmail + "','subject': '" + GenSubject + "','msg': '" + GenMsg + "'}";
                //,'EscortName':" + Esname +
                alert(data)
              $.ajax({
              type: "POST",
              url: "../serv.aspx/SendEsError",
              cache: false,
              data: JSON.stringify(data),
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function (r) {
                  //if(r.length > 0)
                  
                  //    // do something
                  //    console.log(r.data);
                  
                  //{
                  //else
                  //{
                  //              console.log("no result");
                  //}
                  //complete: function (transport) {
                  // for testing purposes
                  // $('#formcontainer').hide().html('<h1>The status is: ' + transport.status + '</h1>').fadeIn(800);
                  //if (transport.status == 200) {
                  $('#reportError').fadeOut(950);
                  $('#formcontainer').hide().html('<h1>Success</h1>').fadeIn(800);
                  $('#listingerrorsntmsg').hide().fadeIn(1000);
                  //$('#listingerrorsntmsg').html('<br /><br /><blockquote>Thank you <strong>' + GenName + '</strong> the report has been sent to TMN and we will look into it ASAP to fix any errors with <strong>' + Esname + 's</strong> listing. ' + r.d)
                  $('#listingerrorsntmsg').html(r.GenName);
                  //console.log(r.Esname);
                  alert(r.d)
                  //}
              },
              error: function (data, status, error) {
                  //$("#errorDiv").fadeIn(800);
                  //$("#errorDiv").html('error occured: ' + error + '<br /><br />');
                  $('#reportError').fadeOut(950);
                  $('#formcontainer').hide().html('<h1><span>Please try again later ' + GenName + '</span></h1>').fadeIn(1500);
                  console.log(error);
              }
                  //else {
                      //alert("Please try again later");
                      //$('#reportError').fadeOut(950);
                      //$('#formcontainer').hide().html('<h1><span>Please try again later ' + GenName + '</span></h1>').fadeIn(1500);
                 // }
              //}
            });

Open in new window


Server side:

   
<WebMethod()>
    Public Shared Function SendEsError(ByVal GenName As String, ByVal fromEmail As String, ByVal GenSubject As String, ByVal GenMsg As String, ByVal EsName As String) As String

        Return "Hello " & GenName & DateTime.Now.ToString()

    End Function

Open in new window


what I am doing wrong?

Thanks guys
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
leakim971Multitechnician
Top Expert 2014

Commented:
I see, client side : dataType : "json"
and server side : ..., ByVal EsName As String) As String
Tony TrappWeb and Mobile application develper

Author

Commented:
Leakim971 I changed the server side code to this:

    Public Shared Function SendEsError(ByVal name As String, ByVal fromEmail As String, ByVal subject As String, ByVal msg As String) As String

        Return name

    End Function

in the client side it is json, so
Tony TrappWeb and Mobile application develper

Author

Commented:
can you help me?
Tony TrappWeb and Mobile application develper

Author

Commented:
I think this line is the problem:

console.log(r.name);
leakim971Multitechnician
Top Expert 2014

Commented:
could you expose your server to internet ? so I can test your page ?
leakim971Multitechnician
Top Expert 2014

Commented:
try :
console.log(r.d);
Tony TrappWeb and Mobile application develper

Author

Commented:
this is from my own local server
leakim971Multitechnician
Top Expert 2014

Commented:
for the success :
success: function(r) {
     console.log(r.d);
    alert( JSON.stringify(r.d) );
},
Tony TrappWeb and Mobile application develper

Author

Commented:
i tired console.log(r.d);

still undefined
Tony TrappWeb and Mobile application develper

Author

Commented:
good suggestion, I will try it now
Tony TrappWeb and Mobile application develper

Author

Commented:
I will show a screen shot attachscrn1
Tony TrappWeb and Mobile application develper

Author

Commented:
this is the other screen shotscreen 2
Tony TrappWeb and Mobile application develper

Author

Commented:
still undefined....sigh
leakim971Multitechnician
Top Expert 2014

Commented:
you get a nice response.
where do you get "undefined" ?
To display the name, just use :
success : function(r) {
    console.log( r.d.name);
},

Open in new window

Tony TrappWeb and Mobile application develper

Author

Commented:
I will try that, ahhh did see my 2nd screen shot?
Tony TrappWeb and Mobile application develper

Author

Commented:
now I got this error:

default?cat=994:305 Uncaught TypeError: Cannot read property 'name' of undefined
leakim971Multitechnician
Top Expert 2014

Commented:
what did you change after the first screenshot ? the code was right
Tony TrappWeb and Mobile application develper

Author

Commented:
I did this:

alert(JSON.stringify(r.d.name));

thats it
leakim971Multitechnician
Top Expert 2014

Commented:
in the first screenshot this alert worked fine, that why you see the popup
and the next screenshot show the result did not come fine anymore
Tony TrappWeb and Mobile application develper

Author

Commented:
screen shot again
scrn3.jpg
Tony TrappWeb and Mobile application develper

Author

Commented:
next screenshot show the result did not come fine anymore

why? thats my question
leakim971Multitechnician
Top Expert 2014

Commented:
I don't see the beginning of your success function anymore
why do you place the console.log or alert after all your code ?
put it just after the success and show me (post the code) you currently have + screenshot
Tony TrappWeb and Mobile application develper

Author

Commented:
here it is again:

 $("#listingerrorSnd").click(function () {
                   var GenName = document.getElementById("<%: anonName.ClientID %>").value;
            <%--       var fromEmail = document.getElementById("<%: anonEmail.ClientID %>").value;
                   var GenSubject = document.getElementById("<%: typeErr.ClientID %>").value;
                   var GenMsg = document.getElementById("<%: TMNmsg.ClientID %>").value;
                   var Esname = document.getElementById("<%: escortName.ClientID %>").value;--%>
                   //var data = "{'name': '" + GenName + "', 'fromEmail': '" +
                //            fromEmail + "','subject': '" + GenSubject + "','msg': '" + GenMsg + "'}";
                var data = "{'name':'" + GenName + "'}";
                //,'EscortName':" + Esname +
                alert(data)
              $.ajax({
              type: "POST",
              url: "../serv.aspx/SendEsError",
              async: true,
              cache: false,
              data: JSON.stringify(data),
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function (r) {
                  //if(r.length > 0)
                  
                  //    // do something
                  //    console.log(r.data);
                  
                  //{
                  //else
                  //{
                  //              console.log("no result");
                  //}
                  //complete: function (transport) {
                  // for testing purposes
                  // $('#formcontainer').hide().html('<h1>The status is: ' + transport.status + '</h1>').fadeIn(800);
                  //if (transport.status == 200) {
                  $('#reportError').fadeOut(950);
                  $('#formcontainer').hide().html('<h1>Success</h1>').fadeIn(800);
                  $('#listingerrorsntmsg').hide().fadeIn(1000);
                  //$('#listingerrorsntmsg').html('<br /><br /><blockquote>Thank you <strong>' + GenName + '</strong> the report has been sent to TMN and we will look into it ASAP to fix any errors with <strong>' + Esname + 's</strong> listing. ' + r.d)
                  $('#listingerrorsntmsg').html(r.name);
                  console.log(r.d);
                  alert(JSON.stringify(r.d));
                  //}
              },
              error: function (data, status, error) {
                  //$("#errorDiv").fadeIn(800);
                  //$("#errorDiv").html('error occured: ' + error + '<br /><br />');
                  $('#reportError').fadeOut(950);
                  $('#formcontainer').hide().html('<h1><span>Please try again later ' + GenName + '</span></h1>').fadeIn(1500);
                  console.log(error);
              }
                  //else {
                      //alert("Please try again later");
                      //$('#reportError').fadeOut(950);
                      //$('#formcontainer').hide().html('<h1><span>Please try again later ' + GenName + '</span></h1>').fadeIn(1500);
                 // }
              //}
            });

Open in new window

Tony TrappWeb and Mobile application develper

Author

Commented:
I will try this
put it just after the success
Tony TrappWeb and Mobile application develper

Author

Commented:
this is the screen shotscrnshot4
Tony TrappWeb and Mobile application develper

Author

Commented:
its still doing it, sigh..............
leakim971Multitechnician
Top Expert 2014

Commented:
Try this : console.log(typeof r);
Tony TrappWeb and Mobile application develper

Author

Commented:
ok i will right now
leakim971Multitechnician
Top Expert 2014

Commented:
not sure what happen after #41780582
you said you add : alert(JSON.stringify(r.d.name));
but this is not the issue that stopped to return you a valid JSON, you change something else
Tony TrappWeb and Mobile application develper

Author

Commented:
instead of saying undefined it says object
leakim971Multitechnician
Top Expert 2014

Commented:
cool. let's see it with the following :

console.log( JSON.stringify(r) );
Tony TrappWeb and Mobile application develper

Author

Commented:
with this code:  console.log(typeof r);
leakim971Multitechnician
Top Expert 2014

Commented:
no, replace the previous code, we don't need it anymore.
it was just to check the type of the object returned.
Tony TrappWeb and Mobile application develper

Author

Commented:
now it says:

{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}

with this code:

console.log(JSON.stringify(r));
Tony TrappWeb and Mobile application develper

Author

Commented:
leakim971 do you have skype?
Tony TrappWeb and Mobile application develper

Author

Commented:
I modified the server side code to this
    <WebMethod()>
    Public Shared Function SendEsError(ByVal GenName As String) As String

        Return GenName

    End Function

Open in new window


btw
Tony TrappWeb and Mobile application develper

Author

Commented:
this message means I don't have permission and i changed the web.config as well

message: {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}

web.config:

  <authorization>
        <allow users="*"/>
      </authorization>

Still the same message

now I changed the RouteConfig.vb

settings.AutoRedirectMode = RedirectMode.Off but with this code now I have a 500 error so I change it back like this

settings.AutoRedirectMode = RedirectMode.Permanent

now I get the same message:
{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}

this is driving me crazy
Tony TrappWeb and Mobile application develper

Author

Commented:
ok I switched to .asax file instead and it works
Tony TrappWeb and Mobile application develper

Author

Commented:
thanks for help anyway
There's a few things "going wrong" here...

1. You can use WebForms to act as Webservice endpoints but they're not really made for that. WebForms have lots of unnecessary overhead and worse still you have to account for the entire page lifecycle. Consider using a Generic Handler instead.

2. If you're only doing a simple post and result display, don't dig into the bowels that the framework authors have already abstracted away for you; use the simpler constructs/functions instead.

3. Whenever you start to thrash about, go back to the most basic starting point that you can and build up from there.

With all that said, here's what I've got as my solution to simply get things working:
Simple solution for the answer.
Here's my server side code in its entirety. Notice that I've used a Generic Handler (.ashx) instead of a WebForm (.aspx).
<%@ WebHandler Language="VB" Class="serv" %>

Imports System
Imports System.Web

Public Class serv : Implements IHttpHandler

	Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
		Dim request = context.Request.Form
		Dim GenName = request("name")

		Dim serializer = New Script.Serialization.JavaScriptSerializer
		Dim result = serializer.Serialize(New With {.d = String.Format("Hello {0}", GenName)})

		context.Response.ContentType = "application/json; charset=utf-8"
		context.Response.Write(result)
	End Sub

	Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
		Get
			Return False
		End Get
	End Property

End Class

Open in new window


Here is my client side code in its entirety. Notice that I've used the MUCH simpler $.post() function instead of the $.ajax() function. Also, note that since you're posting the data there's no requirement to .stringify it (though you might want to for security concerns). In that case you'll want to turn the individual values into strings, not the entire data element (which I don't do at all here):
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<title></title>
	<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.0.min.js"></script>
</head>
<body>
	<form id="form1" runat="server"></form>

	<div>
		<p>
			<input type="text" id="GenName" value="Who Am I?" />
		</p>
		<p>
			<button id="listingerrorSnd">Send Error</button>
		</p>
	</div>

	<script>
		$(document).ready(function () {

			$("#listingerrorSnd").click(function () {
				var data = { 'name': $("#GenName").val() };
				var url = "../serv.ashx";

				$.post(url, data)
					.done(function (r) {
						alert('SUCCESS!\n' + r.d);
					})
					.fail(function (data, status, error) {
						console.log("error: " + error);
					});
			});

		});
	</script>

</body>
</html>

Open in new window


And that is it. Now clicking Send Error in the screenshot below...
The page with "stuff" to be sent.
... results in the following sent back from the server:
The post-processing dialog.

I hope this helps!
Tony TrappWeb and Mobile application develper

Author

Commented:
I did with .asmx instead and it works beauitfully, thank you anway
Tony TrappWeb and Mobile application develper

Author

Commented:
i will show you this is the server side code:

   <WebMethod()>
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
    Public Function SendReport(name As String, fromEmail As String, subject As String, msg As String) As String

        If Not String.IsNullOrEmpty(name) And Not String.IsNullOrEmpty(fromEmail) And subject <> "Please choose one" Then

            Dim listingerror_mailclient As SmtpClient = New SmtpClient()
            Dim listingerror_plainView As AlternateView

            Using message = New MailMessage()

                With message

                    .From = New MailAddress(fromEmail, name)
                    .To.Add(New MailAddress("tony@themalenude.com", "Tony Trapp"))
                    .Subject = String.Concat("TMN listing error report: ", subject)
                    .Priority = MailPriority.High
                    .IsBodyHtml = False

                    listingerror_plainView = AlternateView.CreateAlternateViewFromString(String.Concat("Tony an escort listing report has been made by ", name, " and you can read the problem below", vbCrLf, vbCrLf,
                    "Reason is: ", subject, vbCrLf, vbCrLf,
                    "Escorts Name is: ", name, vbCrLf, vbCrLf,
                    "Escorts profile page is: http://www.themalenude.com/gay/escorts/?cat=", HttpContext.Current.Request.QueryString("cat"), vbCrLf, vbCrLf,
                    "Additonal comments if any: ", msg, ""), Nothing, "text/plain")

                    .AlternateViews.Add(listingerror_plainView)

                End With

                Try

                    listingerror_mailclient.Send(message)

                    Return String.Concat("Report ", subject, " was sent ", name)

                Catch ex As Exception

                    Return ex.Message

                End Try

            End Using

        Else

            Return "Name, Email, and subject is required, try again please"

        End If

        'Dim inputString As String = Server.HtmlEncode(Input)
        'If Not String.IsNullOrEmpty(name) Then
        '    Return String.Concat("Hi there ", name, " this is from the server, this is the email: ", fromEmail, " this is the subject: ", subject, " this is the message ", vbCrLf, vbCrLf, msg)
        'Else
        '    Return "The input string was null or empty."
        'End If

    End Function

Open in new window


and this from the client side code:

            $("#listingerrorSnd").click(function () {
                var GenName = document.getElementById("<%: anonName.ClientID %>").value;
                var fromEmail = document.getElementById("<%: anonEmail.ClientID %>").value;
                var GenSubject = document.getElementById("<%: typeErr.ClientID %>").value;
                var GenMsg = document.getElementById("<%: TMNmsg.ClientID %>").value;
                var Esname = document.getElementById("<%: escortName.ClientID %>").value;
                var data = "{'name': '" + GenName + "', 'fromEmail': '" +
                         fromEmail + "','subject': '" + GenSubject + "','msg': '" + GenMsg + "'}";
                // alert(data)
                var over = '<div id="overlay">' + '<div id="loading">Sending<br /><img src="../images/ajax-loader.gif">' + '</div></div>';
                $(over).appendTo('#reportError').hide().fadeIn('slow');
                $.ajax({
                    type: "POST",
                    url: "../tmnser.asmx/SendReport",
                    async: true,
                    cache: false,
                    data: data,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {

                        console.log(JSON.stringify(r.d));

                        $('#reportError').fadeOut(950);
                        $('#overlay').remove();

                        if (r.d == "Failure sending mail.")
                        {
                      
                            $('#formcontainer').hide().html('<h1><span>Error ' + GenName + '</span></h1>').fadeIn(925);
                            $('#btngen').hide().html('<br /><input id="tryagain" type="button" value="Try again" class="btn btn-default"  />').fadeIn(925);
                        }
                        else if (r.d == "Name, Email, and subject is required, try again please")
                        {
                            $('#formcontainer').hide().html('<h1><span>Error ' + GenName + '</span></h1>').fadeIn(925);
                            $('#btngen').hide().html('<br /><input id="goback" type="button" value="Go Back" class="btn btn-default"  />').fadeIn(925);
                        }
                        else
                        {
                            $('#formcontainer').hide().html('<h1>Success</h1>').fadeIn(925);
                        }
                  
                        $('#listingerrorsntmsg').hide().fadeIn(825);
                        $('#listingerrorsntmsg').html(r.d);
                        // try again
                        $("#tryagain").click(function () {
                            $('#formcontainer').fadeOut(950);
                            $('#reportError').fadeIn(850);
                            $('#listingerrorsntmsg').empty();
                            $('#btngen').empty();
                        });
                        // go back to the form
                        $("#goback").click(function () {
                            $('#formcontainer').fadeOut(950);
                            $('#reportError').fadeIn(850);
                            $('#listingerrorsntmsg').empty();
                            $('#btngen').empty();
                        });
                    },
                    error: function (data, status, error) {
                        $('#reportError').fadeOut(950);
                        $('#formcontainer').hide().html('<h1><span>Please try again later ' + GenName + '</span></h1>').fadeIn(1500);
                        $('#overlay').remove();
                        console.log(error);
                    }
                });
            });

Open in new window

Tony TrappWeb and Mobile application develper

Author

Commented:
But now I have another question what I want to do is reload the comments section its a <asp:repeater but I don't want the page reload only the section, how can I do that.

This is the client side code:

                    $("#pstcmt").click(function () {
                //window.location.reload();
                var Cmt = document.getElementById("<%: Txtcomment.ClientID %>").value;
                var datacmt = "{'comment':'" + Cmt + "', 'EsId':'<%: HttpContext.Current.Request.QueryString("cat") %>','uname':'<%: Context.User.Identity.Name  %>'}"
                //alert(datacmt);
                console.log(datacmt);
                var overcmt = '<div id="overlay">' + '<div id="loading">Loading<br /><img src="../images/ajax-loader.gif">' + '</div></div>';
                $(overcmt).appendTo('#pstcmtES').hide().fadeIn('slow');
                $.ajax({
                    type: "POST",
                    url: "../tmnser.asmx/postEscortComment",
                    async: true,
                    cache: false,
                    data: datacmt,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {

                        console.log(JSON.stringify(r.d));

                        $('#overlay').remove();

                        if (r.d == "comments are required") {

                            $('#ErrorCmt').hide().html('<h1><span>Error ' + $.parse(r.d) + '</span></h1>').fadeIn(925);
                            //$('#btngenCmt').hide().html('<br /><input id="goback" type="button" value="Go Back" class="btn btn-default"  />').fadeIn(925);
                        }
                        else {

                            var Cmt2 = document.getElementById("<%: Txtcomment.ClientID %>").value = '';
                            
                           // $('#commemtFrm').fadeOut(950);
                            $('#ErrorCmt').hide().html('<h1>Success</h1>').fadeIn(925);
                            // this is the asp.net repeater
                            $('<%: tmnescortscomments.ClientID %>').bind()
                        }

                    },
                    error: function (data, status, error, message) {
                        $('#ErrorCmt').hide().html('<h1><span>Please try again later</span></h1>').fadeIn(1500);
                        $('#overlay').remove();
                        console.log(data, status, error, xhr.responseText);
                    }
                });
            });

Open in new window


I tired everything with no luck
Tony TrappWeb and Mobile application develper

Author

Commented:
Assuming that the comments section is the tmnescortscomments you're speaking of and it actually corresponds to a DIV in the emitted HTML you should have the basis for what you need. I don't see your JavaScript bind() function (on line 35) so I don't know what it does. Unless it has code to manipulate tmnescortscomments then that bind() isn't going to do what you think.
Tony TrappWeb and Mobile application develper

Author

Commented:
i got it guys thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial