Avatar of Tony Trapp
Tony Trapp
Flag for United States of America asked on

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
ASP.NETAJAXjQuery

Avatar of undefined
Last Comment
Tony Trapp

8/22/2022 - Mon
leakim971

I see, client side : dataType : "json"
and server side : ..., ByVal EsName As String) As String
Tony Trapp

ASKER
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 Trapp

ASKER
can you help me?
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Tony Trapp

ASKER
I think this line is the problem:

console.log(r.name);
leakim971

could you expose your server to internet ? so I can test your page ?
leakim971

try :
console.log(r.d);
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Tony Trapp

ASKER
this is from my own local server
leakim971

for the success :
success: function(r) {
     console.log(r.d);
    alert( JSON.stringify(r.d) );
},
Tony Trapp

ASKER
i tired console.log(r.d);

still undefined
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Tony Trapp

ASKER
good suggestion, I will try it now
Tony Trapp

ASKER
I will show a screen shot attachscrn1
Tony Trapp

ASKER
this is the other screen shotscreen 2
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Tony Trapp

ASKER
still undefined....sigh
leakim971

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 Trapp

ASKER
I will try that, ahhh did see my 2nd screen shot?
Your help has saved me hundreds of hours of internet surfing.
fblack61
Tony Trapp

ASKER
now I got this error:

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

what did you change after the first screenshot ? the code was right
Tony Trapp

ASKER
I did this:

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

thats it
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
leakim971

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 Trapp

ASKER
screen shot again
scrn3.jpg
Tony Trapp

ASKER
next screenshot show the result did not come fine anymore

why? thats my question
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
leakim971

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 Trapp

ASKER
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 Trapp

ASKER
I will try this
put it just after the success
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Tony Trapp

ASKER
this is the screen shotscrnshot4
Tony Trapp

ASKER
its still doing it, sigh..............
leakim971

Try this : console.log(typeof r);
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Tony Trapp

ASKER
ok i will right now
leakim971

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 Trapp

ASKER
instead of saying undefined it says object
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
leakim971

cool. let's see it with the following :

console.log( JSON.stringify(r) );
Tony Trapp

ASKER
with this code:  console.log(typeof r);
leakim971

no, replace the previous code, we don't need it anymore.
it was just to check the type of the object returned.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Tony Trapp

ASKER
now it says:

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

with this code:

console.log(JSON.stringify(r));
Tony Trapp

ASKER
leakim971 do you have skype?
Tony Trapp

ASKER
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
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Tony Trapp

ASKER
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 Trapp

ASKER
ok I switched to .asax file instead and it works
Tony Trapp

ASKER
thanks for help anyway
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER CERTIFIED SOLUTION
Kelvin McDaniel

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Tony Trapp

ASKER
I did with .asmx instead and it works beauitfully, thank you anway
Tony Trapp

ASKER
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 Trapp

ASKER
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
âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Tony Trapp

ASKER
Kelvin McDaniel

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 Trapp

ASKER
i got it guys thanks
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck