Mike Hofer
Mike Hofer

Reputation: 17022

Invoking WebMethods with XmlHttpRequest and Pure JavaScript

I have what should be a relatively simple task that's frankly got me stumped. I've researched it until my brain is fried, and now I'm punting, and asking you guys for help.

Here's the scenario:

However, when I view the HTML page in a browser, the following occur:

It appears that the JavaScript code is largely set up correctly, but for some reason that is completely escaping me at this point, the HTML page will simply not execute the WebMethod on the ASPX page, and simply returns the page as though it were a plain HTML GET request. Clearly, an HTML document can't be evaluated by JavaScript's eval function, which brings me to my problem. (Also note that the JSON data appears nowhere in the HTML that's returned.)

I am, frankly, baffled. I've looked at dozens of Microsoft articles, StackOverflow posts, CodeProject articles, and who knows what else. My code looks like it's okay. But I know better. I'm missing something simple, stupid, and obvious. I just need someone to point it out to me.

Below you'll find the ASPX page code and the HTML code, in the hope that they'll shed some light.

ASPX Code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Q2.aspx.cs" Inherits="Satuit.Q2" enablesessionstate="False" %>
<html>
    <body>
        <form runat="server" id="frmMain"/>
    </body>
</html>
-- Codebehind
using System.IO;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace Satuit
{
    [WebService(Namespace="http://tempuri.org")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [ScriptService]
    public partial class Q2 : Page
    {

        [WebMethod]
        public static string GetAllContacts()
        {
            return LoadJsonData();
        }

        private static string LoadJsonData()
        {
            using (var stringWriter = new StringWriter())
            {

                string xmlUri = HttpContext.Current.Server.MapPath("\\XmlData\\Contacts.xml");
                string xslUri = HttpContext.Current.Server.MapPath("\\XmlData\\Q2.xsl");

                using (var xmlTextReader = new XmlTextReader(xmlUri))
                {
                    var xpathDocument = new XPathDocument(xmlTextReader);
                    var xslTransform = new XslCompiledTransform();

                    xslTransform.Load(xslUri);
                    xslTransform.Transform(xpathDocument, null, stringWriter);

                    return stringWriter.ToString();
                }
            }
        }
    }
}

HTML Code

    var objectData; // Receives the objectified results of the JSON request.

    var xmlhttp;
    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }

    xmlhttp.open("GET", "/Q2.aspx/GetAllContacts", true);
    xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    xmlhttp.onreadystatechange = function () 
    {
        if (xmlhttp.readyState == 4) 
        {
            if (xmlhttp.status == 200)
            {
                var jsonResultBuffer = xmlhttp.responseText;
                objectData = eval(jsonResultBuffer);
                DisplayTable();
            }
        }
    };
    xmlhttp.send(null);

    function DisplayTable()
    {       
        var sHtml = "";     
        sHtml = "<table><tr><th>ID</th><th>First</th><th>Last</th><th>Address</th></tr>";           
        for(i = 0; i < objectData.length; i++)
        {
            sHtml += "<tr>";
            sHtml += "<td>" + objectData.ID;
            sHtml += "<td>" + objectData.firstName + "</td>";
            sHtml += "<td>" + objectData.lastName + "</td>";
            sHtml += "<td>" + objectData.address + "</td>"; 
            sHtml += "</tr>"
        }
        sHtml += "</table>"         
        document.getElementById("divTable").innerHTML = sHtml;
    }    
</script>

Dev Environment Details

Upvotes: 1

Views: 8912

Answers (2)

khagesh
khagesh

Reputation: 948

I think we need to call web method with POST request try changing this part of code

xmlhttp.open("POST", "/Q2.aspx/GetAllContacts", true);
xmlhttp.setRequestHeader("content-type", "application/json");
xmlhttp.setRequestHeader("Accept", "application/json");
xmlhttp.onreadystatechange = function () 
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
    {
            var jsonResultBuffer = JSON.parse(xmlhttp.responseText);
            objectData = jsonResultBuffer.d;
            DisplayTable();
    }
};

Response is returned in JSON format with "d" as the key in xmlhttp.responseText

Upvotes: 4

Thurein
Thurein

Reputation: 6895

Pls try the following using jquery to see the web service is accessible or not.

$.ajax({
        type: "POST",
        url: "Q2.aspx/GetAllContacts",
        data: "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
           alert("success");
        },
        error: function(response, aa) {
            alert("fail");
        }
    });

Thurein

Upvotes: 0

Related Questions