17

I am very new to web development, but have a lot of experience in development in general. I have an ASP page that has a few input fields and a submit button. This submit button purely calls $.ajax, which I intended to have call a method in the code-behind file. However, I've noticed two interesting things. First, the ajax call succeeds regardless of what data is provided to it. Secondly, the responseText field is the entire page's html source.

I've read this and other articles that point to the webconfig, but these solutions do not seem to resolve my issue.

Here is the asp page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="TesScript.js"></script>
    <link rel="Stylesheet" type="text/css" href="TestStyle.css" />
</head>
<body>
    <div>
        <ul class="tempList">
            <li>Name:
                <input id="nameText" type="text" />
            </li>
            <li>Attending:
                <input id="yesButton" type="radio" name="attending" />
                Yes
                <input id="noButton" type="radio" name="attending" />
                No </li>
            <li>Return Address:
                <input id="returnAddressText" type="text" />
            </li>
            <li>
                <input id="submitButton" type="button" onclick="submit()" value="Submit" />
            </li>
        </ul>
    </div>
    <ul id="errorContainer" class="errorSection" runat="server" />
    <ul id="messageContainer" class="messageSection" runat="server" />
</body>
</html>

The code behind:

using System;
using System.Web.Services;
using System.Web.UI;

namespace TestAspStuff
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }


        [WebMethod]
        public static string OnSubmit(string name, bool isGoing, string returnAddress)
        {
            return "it worked";
        }
    }
}

And the JavaScript:

function submit() {

    var name = "my name";
    var isAttending = true;
    var returnAddress = "myEmail@gmail.com";

    SendMail(name, isAttending, returnAddress);
}

function SendMail(person, isAttending, returnEmail) {

    var dataValue = { "name": person, "isGoing": isAttending, "returnAddress": returnEmail };

    $.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        complete: function (jqXHR, status) {
            alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
        }
    });

}

Now, I noticed I can change the url property to anything I want and the error method is never called, and the status is success, with the responseText being the entire html page. My webconfig has all of the appropriate sections (including the htmlModule section). I am working in .Net 3.5. I appreciate any help and, again, I'm really new to this so what's obvious to others is most likely not obvious to me. And if there's a better way to do this (calling asp.net code-behind methods from JavaScript, that is) please feel free to post that. Thanks!!!

Community
  • 1
  • 1
Will Custode
  • 4,576
  • 3
  • 26
  • 51
  • 3
    Since you have asked for a better way, IMO you should use Mvc, Web API or a web service to get json response. Though you can do this with aspx pages, but that is a hacky solution. aspx pages are designed, for, well, rendering web pages! – Varun K Aug 14 '13 at 16:03
  • 1
    creating a web service is probably the most simple of those...this kind of thing is what they were made for. – Nick Aug 14 '13 at 16:06
  • Thank you both. I've looked into that a little bit and will probably try that when I get a better understanding here. I'd like to know how it works at this level, too. Thanks! – Will Custode Aug 14 '13 at 16:43

3 Answers3

20

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });
wilso132
  • 829
  • 5
  • 10
  • Thank you. This hasnt't solved the problem, although it has provided more detail. Not including the contentType and dataType fields, the success method is executed and the result is the entire HTML page. Adding those two fields, the error event is raised with an internal server error. Also, what did you mean when you said " I've never made the signature methods match yours"? – Will Custode Aug 14 '13 at 16:54
  • 1
    Fixed! The data that was passed didn't match in type to the arguments it was expecting. – Will Custode Aug 14 '13 at 17:02
8

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});
Neil
  • 54,642
  • 8
  • 60
  • 72
user3824922
  • 91
  • 1
  • 3
  • As far as I can see, you've just changed your `dataValue` and added `contentType` and `dataType`? Are you able to use the passed variables in the method this way? – Wouter Vanherck Jul 26 '18 at 07:06
2

I know it's an old thread. One possible solution is to use JSON.stringify( ) to convert it to a proper JSON string. This will resolve any data parameter values related issue.

function SendMail(person, isAttending, returnEmail) {

    var dataValue = { "name": person, "isGoing": isAttending, "returnAddress": returnEmail };

    $.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: JSON.stringify(dataValue),
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        complete: function (jqXHR, status) {
            alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
        }
    });

}
Kristian
  • 2,456
  • 8
  • 23
  • 23
Imran
  • 21
  • 1