Hi,
In my code behind file, I called Soap web reference and retreive data and diplay in grid view and it worked. But when I convert retreived data to Json text and send back to java script and on client side, convert json text to java script object and when try to display it, its displaying nothing. I dont know if i m doing something wrong here. please check my code and give me suggestions, I really need help.

Below is the javascript file:

$.ajaxSetup({
    cache: false,
    timeout: 5000
});
var ajax_load = "<img src='loading.gif' alt='loading...' />";

//  load() functions
var loadUrl = "test.txt";

var the_object = {};

function concatObject(obj) {
    str = '';
    for (prop in obj) {
        str += prop + " value :" + obj[prop] + "\n";
    }
    return (str);
}


$(document).ready(function() {
    $("button").ajaxStart(function() {
        alert('Triggered ajaxStart handler.');
    });
    $("button").click(function() {
        $.ajax({
            type: "POST",
            dataType: 'JSON',
            url: "Testing.aspx/SendMessage",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            },
            success: function(result, txtStatus, httpRequest) {
                alert("success");
                the_object = httpRequest.responseText;
            }
        });
        //alert(concatObject(the_object));
        $('#result').html(concatObject(the_object));

    });
});

and here is code behind file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Web.Services.Protocols;
using System.Data;
using System.Text;
using System.IO;
using Newtonsoft.Json;


public partial class Testing : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //al2c00.ldap lp = new al2c00.ldap();

        //DataTable dt = lp.GetEmployeeDetailsBy_NTID("650FA25C-9561-430B-B757-835D043EA5E5", "stephen.gilroy1");
        //GridView1.DataSource = dt;
        //GridView1.DataBind();
    }

    public static string SendMessage()
    {
        al2c00.ldap lp = new al2c00.ldap();

        return JavaScriptConvert.SerializeObject(lp.GetEmployeeDetailsBy_NTID("auth_code", "amby"));
    }
}

and below is the main file:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Testing.aspx.cs" Inherits="Testing" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery.js" type="text/javascript"></script>

    <script src="Testing.js" type="text/javascript"></script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Employee's NTID: <input type="text" id = "Eid" name="Employee_NTID" />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
<br />
<br />
    <button type = "button" id = "callingMethod">Search</button> 
    <p id = "result"></p>
       
    </div>
    
    </form>
</body>
</html>

Amby,

I think you will stand more chance by moving $('#result').html.... inside the success handler and JSON decode it, like this :

String.prototype.parseJSON = JSON.decode;//make sure you have the JSON lib loaded.

$(document).ready(function() {
    $("button").ajaxStart(function() {
        alert('Triggered ajaxStart handler.');
    });
    $("button").click(function() {
        $.ajax({
            type: "POST",
            dataType: 'JSON',
            url: "Testing.aspx/SendMessage",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            },
            success: function(result, txtStatus, httpRequest) {
                $('#result').html(concatObject(httpRequest.responseText.decode()));
            }
        });
    });
});

This may not be 100% correct yet but should be a step in the right direction.

And concatObject would be less memory hungry if it were written :

function concatObject(obj) {
    strArray = [];//new Array
    for (prop in obj) {
        strArray.push(prop + " value :" + obj[prop]); 
    }
    return strArray.join("\n");
}

Successive string concatenations using += are inefficient because at each concatenation, a complete new string has to be created and returned. Meanwhile, an increasing number of discarded component strings accumulates in memory waiting to be cleaned up by javascript's automatic garbage collection at some unknown point in the future. In Javascript the array.push ... array.join approach is efficient because not only does it overcome the inherent memory hungriness but also, Javascript arrays are very cheap (low overherad).
Airshow

Thanks Airshow,
I changed concatObect like yours. using json.decode didnt work but after making some changes to .ajax it is displaying this line given below:

toJSON value :function (key) { return this.valueOf(); }

and changes i have made are:

$.ajax({
            type: "POST",
            dataType: 'JSON',
            //data: "{'ntid':'stephen.gilroy1'}",
            //contentType: "application/json; charset=utf-8",
            //processData: false,
            url: "Testing.aspx/SendMessage",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            },
            success: function(result, txtStatus, httpRequest) {
                alert(txtStatus);
                the_object = result;
                $('#status').html(concatObject(the_object));
            }

can you please tell me why its not displaying the whole data and if i m using the correct way to display it? please reply me soon. Thanks

Amby,

I think this script seems to be working in that the displayed response toJSON value :function (key) { return this.valueOf(); }
is of the right format for something processed by your concatOnject function.

Two things to try :

  1. The jQuery API says to use dataType: 'json' , rather than dataType: 'JSON', . Probably no difference but worth a try.
  2. Use the following code to look at the raw, undecoded response to see if it is what you expect :
$.ajax({
            type: "POST",
            //dataType: 'JSON',
            url: "Testing.aspx/SendMessage",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            },
            success: function(result, txtStatus, httpRequest) {
                alert(txtStatus);
                $('#status').html(result);
            }

Airshow

Thanks airshow for quick reponse. I really appreciate it. when i try datatype: 'json' instead of 'JSON' it is giving parseerror. and when i see raw data using the code u given, it is showing the asp page result in the bottom of the page ( i mean displaying Testing.aspx again in the bottom). u have also seen my C# file in this thread. I also tried sending "hello world" string without convert it to json object but still got the same result. I think in ajax call, url "Testing.asp/sendMessage" is returning the whole script instead of sending just one string "Hello world". I am wondering that if it is calling just Testing.asp and not calling its method sendMessage.

one thing i forgot to put in C# file was to write
[WebMethod()] above the sendMessage method.
but still showing the same result:(

Amby,

From what you say, it seems that your problem is server-side. The server appears not to be running the .aspx script. If you have other .aspx pages that run correctly, then the most likely thing is that the file extension is incorrect. Otherwise, check that the server is configured to run .aspx and that the script contained therein is of the correctly formed (see this for example).

To test the script, try running it directly by typing its URL into the browser's address bar rather than having it as an AJAX call. That will remove one level of uncertainty.

Airshow

.aspx script is running fine. Problem is when i call server method from .ajax. That server method calls web service and convert returning data to json text and send back to java script. that web service is also working fine because i saw its result on page_load method. also i tried return just simple "Hello world" string(after converting it into json) but it gave the same result.

Amby,

"Hello world" not coming through worries me.

Try making a very simple "test.aspx" test script that serves "Hello world" with everything else deleted. See what comes back.

If it still fails, try changing the file name to "test.html" and see if the response is any different.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.