user3309885 user3309885 - 6 months ago 82
Javascript Question

ajax call not working in external js file

I have a Registration page having only UserName and Password field. I want to submit new User Details on Click event of Submit button. PLease tell me how do I use ajax call using jquery. I have defined Insert function on button click in ASP.net. But it's not working.

function Insert() {
alert("Insert");

var uname = $('#txtRUserName').val();

alert(uname)
var password = $('#txtRPassword').val();
$.ajax({type: "POST",
url: "login.aspx/Insert",
data: "{'uname:'" + uname + ",'password:'" + password + "}",
datatype: "text/html",
cache: false,
async: false,
contentType: "text/html",
success: function processData(r) {
var myItem = r.d.split('#');
alert(myItem)
}
//error: errorAlert
});
alert("jqajax")
}

Answer

Valid json, ContentType and DataType

You could change your call to be valid json i.e.

data: "{uname:'" + uname + "',password:'" + password + "'}",

Your content type needs to be:

contentType: "application/json; charset=utf-8"

And your data type needs to be:

dataType: "json"

So your javascript would become:

function Insert() {
    alert("Insert");

    var uname = $('#txtRUserName').val();

    alert(uname)
    var password = $('#txtRPassword').val();
    $.ajax({type: "POST",
            url: "login.aspx/Insert",
            data: "{uname:'" + uname + "',password:'" + password + "'}",
            datatype: "json",
            cache: false,
            async: false,
            contentType: "application/json; charset=utf-8",
            success: function processData(r) {
                var myItem = r.d.split('#');
                alert(myItem)
            }
            //error: errorAlert
        });
    alert("jqajax")
}

EnablePageMethods

You need to enable page methods in your script manager like so:

<asp:ScriptManager runat="server" EnablePageMethods="true">

Page behind code

You also need to make sure that your method has the [WebMethod] attribute and is also static i.e. something like this:

[WebMethod]
public static bool Insert(string uname, string password)
Comments