Link to home
Create AccountLog in
Avatar of Tony Trapp
Tony TrappFlag 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
Avatar of leakim971
leakim971
Flag of Guadeloupe image

I see, client side : dataType : "json"
and server side : ..., ByVal EsName As String) As String
Avatar of 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
can you help me?
I think this line is the problem:

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

still undefined
good suggestion, I will try it now
I will show a screen shot attachUser generated image
this is the other screen shotUser generated image
still undefined....sigh
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

I will try that, ahhh did see my 2nd screen shot?
now I got this error:

default?cat=994:305 Uncaught TypeError: Cannot read property 'name' of undefined
what did you change after the first screenshot ? the code was right
I did this:

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

thats it
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
screen shot again
scrn3.jpg
next screenshot show the result did not come fine anymore

why? thats my question
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
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

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

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

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

with this code:

console.log(JSON.stringify(r));
leakim971 do you have skype?
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
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
ok I switched to .asax file instead and it works
thanks for help anyway
ASKER CERTIFIED SOLUTION
Avatar of Kelvin McDaniel
Kelvin McDaniel
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
I did with .asmx instead and it works beauitfully, thank you anway
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

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
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.
i got it guys thanks