Solved

ajax, jquery and web method in asp.net

Posted on 2016-09-01
46
55 Views
Last Modified: 2016-09-12
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
0
Comment
Question by:Tony Trapp
  • 32
  • 12
  • 2
46 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 41780480
I see, client side : dataType : "json"
and server side : ..., ByVal EsName As String) As String
0
 

Author Comment

by:Tony Trapp
ID: 41780506
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
0
 

Author Comment

by:Tony Trapp
ID: 41780510
can you help me?
0
 

Author Comment

by:Tony Trapp
ID: 41780537
I think this line is the problem:

console.log(r.name);
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780545
could you expose your server to internet ? so I can test your page ?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780552
try :
console.log(r.d);
0
 

Author Comment

by:Tony Trapp
ID: 41780556
this is from my own local server
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780563
for the success :
success: function(r) {
     console.log(r.d);
    alert( JSON.stringify(r.d) );
},
0
 

Author Comment

by:Tony Trapp
ID: 41780566
i tired console.log(r.d);

still undefined
0
 

Author Comment

by:Tony Trapp
ID: 41780569
good suggestion, I will try it now
0
 

Author Comment

by:Tony Trapp
ID: 41780582
I will show a screen shot attachscrn1
0
 

Author Comment

by:Tony Trapp
ID: 41780584
this is the other screen shotscreen 2
0
 

Author Comment

by:Tony Trapp
ID: 41780589
still undefined....sigh
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780591
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

0
 

Author Comment

by:Tony Trapp
ID: 41780597
I will try that, ahhh did see my 2nd screen shot?
0
 

Author Comment

by:Tony Trapp
ID: 41780607
now I got this error:

default?cat=994:305 Uncaught TypeError: Cannot read property 'name' of undefined
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780619
what did you change after the first screenshot ? the code was right
0
 

Author Comment

by:Tony Trapp
ID: 41780631
I did this:

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

thats it
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780635
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
0
 

Author Comment

by:Tony Trapp
ID: 41780648
screen shot again
scrn3.jpg
0
 

Author Comment

by:Tony Trapp
ID: 41780649
next screenshot show the result did not come fine anymore

why? thats my question
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780652
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
1
 

Author Comment

by:Tony Trapp
ID: 41780682
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

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:Tony Trapp
ID: 41780688
I will try this
put it just after the success
0
 

Author Comment

by:Tony Trapp
ID: 41780694
this is the screen shotscrnshot4
0
 

Author Comment

by:Tony Trapp
ID: 41780710
its still doing it, sigh..............
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780841
Try this : console.log(typeof r);
0
 

Author Comment

by:Tony Trapp
ID: 41780851
ok i will right now
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780852
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
0
 

Author Comment

by:Tony Trapp
ID: 41780854
instead of saying undefined it says object
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780855
cool. let's see it with the following :

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

Author Comment

by:Tony Trapp
ID: 41780857
with this code:  console.log(typeof r);
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41780858
no, replace the previous code, we don't need it anymore.
it was just to check the type of the object returned.
0
 

Author Comment

by:Tony Trapp
ID: 41780862
now it says:

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

with this code:

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

Author Comment

by:Tony Trapp
ID: 41780872
leakim971 do you have skype?
0
 

Author Comment

by:Tony Trapp
ID: 41780875
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
0
 

Author Comment

by:Tony Trapp
ID: 41780926
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
0
 

Author Comment

by:Tony Trapp
ID: 41780939
ok I switched to .asax file instead and it works
0
 

Author Comment

by:Tony Trapp
ID: 41780955
thanks for help anyway
0
 
LVL 11

Accepted Solution

by:
azarc3 earned 500 total points
ID: 41782365
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!
0
 

Author Comment

by:Tony Trapp
ID: 41787037
I did with .asmx instead and it works beauitfully, thank you anway
0
 

Author Comment

by:Tony Trapp
ID: 41787038
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

0
 

Author Comment

by:Tony Trapp
ID: 41787042
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
0
 

Author Comment

by:Tony Trapp
ID: 41787045
0
 
LVL 11

Expert Comment

by:azarc3
ID: 41788186
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.
0
 

Author Comment

by:Tony Trapp
ID: 41794611
i got it guys thanks
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…

708 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

15 Experts available now in Live!

Get 1:1 Help Now