views:

284

answers:

2

Hey guys,

Really appreciate any help someone might be able to offer!

I've been trying to set up a JQuery Ajax call to a web service, and the little debugging I've done so far shows that the web service will return parameters and from the client side I've use the alert function to show that data is going to the data string, but then I changed it to not take any parameters at all and it's still not working,ie; nothing happens, nothing moves. I wonder if could be some type of syntax error on the 'url:' or 'data:' entries since I've seen them in a variety of ways looking at examples.

Project set up using AJAX enabled web page.

Like I said before--HELP!!

The page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="_Default" %>
<%@ Import Namespace = "System.Web.Services" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
    <title>Check User Name Page</title>
    <script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">

//function ShowAvailability() {

    $(document).ready(function() {
    $("#btnCheck").click(function(event){
    //alert(" '{" + userName: "' + $('#txtUserName').val() + "'}")
     // alert('{userName: "musser"}')
   $.ajax({
        type: "POST",
        url: "WebService.asmx/CheckUserName",
        data: "{}",

     //   data: '{userName: "musser"}',
        //data: '{userName: "' + $('#txtUserName').val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response);

          }
      });
    });
 });
//}


function OnSuccess(response) {
    var mesg = $("#mesg")[0];

    switch (response) {
        case "true":
            mesg.style.color = "green";
            mesg.innerHTML = "Available";
            break;
        case "false":
            mesg.style.color = "red";
            mesg.innerHTML = "Not Available";
            break;
        case "error":
            mesg.style.color = "red";
            mesg.innerHTML = "Error occured";
            break;                     
    }
}
function OnChange(txt) {
   $("#mesg")[0].innerHTML = "";
}


</script>
</head>
<body>
    <form id="form1" runat="server">

        <div>
         UserName : 
    <asp:Textbox ID="txtUserName" runat="server" ></asp:Textbox>
    <input id="btnCheck" type="button" value="Show Availability"/>
    <br />
    <span id = "mesg"></span>
        </div>
    </form>
</body>
</html>

web service

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Collections.Generic;






/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://localhost:1252/ChkUserNamesSite/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]

public class WebService : System.Web.Services.WebService
{
    public WebService()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat= ResponseFormat.Json)]

    public static string CheckUserName(string userName)
    {
        string returnValue = string.Empty;
        try
        {
            string consString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            SqlConnection conn = new SqlConnection(consString);
            SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@UserName", userName.Trim());
            conn.Open();
            returnValue = cmd.ExecuteScalar().ToString();
            conn.Close();
        }
        catch
        {
            //returnValue = "error";
            returnValue = userName;

        }
        return returnValue;

The Web config

<?xml version="1.0"?>
 <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"&gt;
 <configSections>
  <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
   <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
    <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
     <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
     <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
     <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    </sectionGroup>
   </sectionGroup>
  </sectionGroup>
 </configSections>
  <connectionStrings>
    <add name ="conString" connectionString ="Server=Pandora;Database=dbUsers;Integrated Security=true"/>
  </connectionStrings >
 <system.web>

  <pages>
   <controls>
    <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   </controls>
  </pages>
  <!--
          Set compilation debug="true" to insert debugging
          symbols into the compiled page. Because this
          affects performance, set this value to true only
          during development.
    -->
  <compilation debug="true">
   <assemblies>
    <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   </assemblies>
  </compilation>
  <httpHandlers>
   <remove verb="*" path="*.asmx"/>
   <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
  </httpHandlers>
  <httpModules>
   <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </httpModules>
 </system.web>
 <system.web.extensions>
  <scripting>
   <webServices>
    <!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
    <!--
      <jsonSerialization maxJsonLength="500">
        <converters>
          <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
        </converters>
      </jsonSerialization>
      -->
    <!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
    <!--
        <authenticationService enabled="true" requireSSL = "true|false"/>
      -->
    <!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
           and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
           writeAccessProperties attributes. -->
    <!--
      <profileService enabled="true"
                      readAccessProperties="propertyname1,propertyname2"
                      writeAccessProperties="propertyname1,propertyname2" />
      -->
   </webServices>
   <!--
      <scriptResourceHandler enableCompression="true" enableCaching="true" />
      -->
  </scripting>
 </system.web.extensions>
 <system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules>
   <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </modules>
  <handlers>
   <remove name="WebServiceHandlerFactory-Integrated"/>
   <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </handlers>
 </system.webServer>
</configuration>
A: 

It looks like you are returning a string, not a JSON object. This should do what you want:

$(document).ready(function() {
    $("#btnCheck").click(function(e){
        $.post("WebService.asmx/CheckUserName", {userName: "something"}, function(data, textStatus){
            OnSuccess(data); // Call your success method
        }, "text");
        e.preventDefault(); // Cancel any default actions on this button
    });
});

I would recommend using Firebug and Firefox to troubleshoot. Leaving the console open, click the #btnCheck. If the request fails for some reason (or if it succeeds) you can open the request details, see what was sent and what was returned.

Edit: The only thing you may need to change was the missing parameter as @Toji suggested (and I have since added to my answer). However, I would still check the responses to see if you are getting a JSON string ("username") or just a string of text (username).

Doug Neiner
+2  A: 

Goodness, that's a lot of code! In the future, I would recommend you focus on one or two small bits of code (in this case I would say the AJAX call and the webservice function definition.) It makes it easier to read and more likely to get a response.

As for the problem, your webservice definition indicates that it takes in a string (username) but you're sending it nothing. This is an error, and will prevent the webservice from being called. You must send the appropriate data-types for all function arguments for it to work. If you intend to send null, do so explicitly: { userName: null }

Toji
I knew I should have left this to .NET guys. Tried to tackle from the jQuery angle, but missed the absent parameter.
Doug Neiner