[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 119
  • Last Modified:

ajax, jquery and web method in asp.net

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
Tony Trapp
Asked:
Tony Trapp
  • 32
  • 12
  • 2
1 Solution
 
leakim971PluritechnicianCommented:
I see, client side : dataType : "json"
and server side : ..., ByVal EsName As String) As String
0
 
Tony TrappWeb and Mobile application develperAuthor 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
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
can you help me?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Tony TrappWeb and Mobile application develperAuthor Commented:
I think this line is the problem:

console.log(r.name);
0
 
leakim971PluritechnicianCommented:
could you expose your server to internet ? so I can test your page ?
0
 
leakim971PluritechnicianCommented:
try :
console.log(r.d);
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
this is from my own local server
0
 
leakim971PluritechnicianCommented:
for the success :
success: function(r) {
     console.log(r.d);
    alert( JSON.stringify(r.d) );
},
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
i tired console.log(r.d);

still undefined
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
good suggestion, I will try it now
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
I will show a screen shot attachscrn1
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
this is the other screen shotscreen 2
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
still undefined....sigh
0
 
leakim971PluritechnicianCommented:
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
 
Tony TrappWeb and Mobile application develperAuthor Commented:
I will try that, ahhh did see my 2nd screen shot?
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
now I got this error:

default?cat=994:305 Uncaught TypeError: Cannot read property 'name' of undefined
0
 
leakim971PluritechnicianCommented:
what did you change after the first screenshot ? the code was right
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
I did this:

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

thats it
0
 
leakim971PluritechnicianCommented:
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
 
Tony TrappWeb and Mobile application develperAuthor Commented:
screen shot again
scrn3.jpg
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
next screenshot show the result did not come fine anymore

why? thats my question
0
 
leakim971PluritechnicianCommented:
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
 
Tony TrappWeb and Mobile application develperAuthor 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

0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
I will try this
put it just after the success
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
this is the screen shotscrnshot4
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
its still doing it, sigh..............
0
 
leakim971PluritechnicianCommented:
Try this : console.log(typeof r);
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
ok i will right now
0
 
leakim971PluritechnicianCommented:
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
 
Tony TrappWeb and Mobile application develperAuthor Commented:
instead of saying undefined it says object
0
 
leakim971PluritechnicianCommented:
cool. let's see it with the following :

console.log( JSON.stringify(r) );
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
with this code:  console.log(typeof r);
0
 
leakim971PluritechnicianCommented:
no, replace the previous code, we don't need it anymore.
it was just to check the type of the object returned.
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
now it says:

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

with this code:

console.log(JSON.stringify(r));
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
leakim971 do you have skype?
0
 
Tony TrappWeb and Mobile application develperAuthor 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
0
 
Tony TrappWeb and Mobile application develperAuthor 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
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
ok I switched to .asax file instead and it works
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
thanks for help anyway
0
 
Kelvin McDanielSr. Developer/ConsultantCommented:
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
 
Tony TrappWeb and Mobile application develperAuthor Commented:
I did with .asmx instead and it works beauitfully, thank you anway
0
 
Tony TrappWeb and Mobile application develperAuthor 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

0
 
Tony TrappWeb and Mobile application develperAuthor 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
0
 
Tony TrappWeb and Mobile application develperAuthor Commented:
0
 
Kelvin McDanielSr. Developer/ConsultantCommented:
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
 
Tony TrappWeb and Mobile application develperAuthor Commented:
i got it guys thanks
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 32
  • 12
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now