Daniel Anderson Daniel Anderson - 2 months ago 16
Javascript Question

Can't get jQuery and web service to play nice

I've built a simple Bootstrap login form in an ASP.NET WebForms app, like so:

<%@ Page Title="" Language="C#" MasterPageFile="~/Main.master" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript">
$(document).ready(function () {
$('#signInBtn').click( function () {
if ($('#MemberName').val() == "" || $('#Password').val() == "") {
e.preventDefault();
return false;
}

var $btn = $(this);
$btn.button('loading');

var formData = {};
formData['MemberName'] = $('#MemberName').val();
formData['Password'] = $('#Password').val();

var json = JSON.stringify({ Member: formData });
$.ajax({
url: "members.asmx/ValidateLogin",
timeout: 30000,
type: 'POST',
data: json,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
var response = JSON.parse(data.d);
alert(response);
},
error: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(jqXHR.responseText);
alert(obj);
}
})
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMain" Runat="Server">
<div id="frm">
<div class="form-inline form-group-sm">
<div class="input-group">
<label for="MemberName" class="sr-only">Email Address :</label>
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="email" required id="MemberName" placeholder="Email Address" class="form-control">
</div>
<div class="input-group">
<label for="Password" class="sr-only">Password :</label>
<input type="password" required id="Password" placeholder="Password" class="form-control">
</div>
<button id="signInBtn" class="btn-sm btn-primary" autocomplete="off" data-loading-text="Wait...">Login</button>
</div>
</div>
</asp:Content>


It connects to a web service, with the following code:

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Script.Services;
using Newtonsoft.Json;
using MCV.Data;


[WebService(Namespace = "http:/myproject.temp.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Members : System.Web.Services.WebService
{

public Members()
{ }

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string ValidateLogin(Member NewMember)
{
string name = NewMember.MemberName;
SignInResponse r;
try
{
bool status = MemberDB.SignIn(NewMember.MemberName, NewMember.Password);
if (status)
r = new SignInResponse("1", "OK");
else
r = new SignInResponse("0", "ERR");
}
catch (Exception ex)
{
r = new SignInResponse("-1", ex.Message);
}
return JsonConvert.SerializeObject(r);
}
}


This is not complicated code. The web service simply calls a method in another class to validate the user's email and password and returns a JSON string containing a custom class with the result of the validation.

The problem is, the code fails silently. It doesn't appear to fail, because the Chrome console shows no errors. I added a breakpoint in the web service code to see what it was doing, but the breakpoint is never hit. I don't know where the error is, but it's driving me loopy.

Any thoughts on this?

Answer

Two issues:

  1. You're not passing through the NewMember parameter correctly from $.ajax
  2. Pay attention to the spelling of the .asmx file, in your javascript you call it members.asmx/ValidateLogin but in the C# code behind it's called Members with a capital M.Make sure that the case matches.

I just made a change to correctly build up the NewMember from javascript and made sure that the .asmx file in my solution is called members.asmx and it's working now:

$('#signInBtn').click(function () {

    if ($('#MemberName').val() == "" || $('#Password').val() == "") {
        e.preventDefault();
        return false;
    }

    var json = {
        "MemberName": $('#MemberName').val(),
        "Password": $('#Password').val()
    };

    $.ajax({
        url: "members.asmx/ValidateLogin",
        timeout: 30000,
        type: 'POST',
        data: JSON.stringify({ NewMember: json }),
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            var response = JSON.parse(data.d);
            alert(response);
        },
        error: function (data, textStatus, jqXHR) {
            var obj = jQuery.parseJSON(jqXHR.responseText);
            alert(obj);
        }
    })
});
Comments