Click here to Skip to main content
14,937,306 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Friends,
I'm fetching data from webservice using ajax and trying to deserialise the data using eval function. I have tried following

success: function(response) 
{
    alert("Begin");
    var myObject = eval('(' + eval(response) + ')');
    alert("End");
    Bind(response);
}


I'm getting Begin alert but End alert is not coming.

Something is going wrong with
var myObject = eval('(' + eval(response) + ')');
this line.

Any help to sort out that issue?

Thanks in advance
Posted

In order to understand what's going wrong you can also split the statement in two lines. That may give some more information.

JavaScript
alert("Begin");
var result1 = eval(response);
alert("Step 1");
//or alert(result1);
var myObject = eval(result1);
alert("End");


Perhaps it is the syntax. try this:
JavaScript
var myObject = eval(eval(response));
   
v3
Comments
dhage.prashant01 7-Jun-11 9:08am
   
Its giving error, its not even alert Step 1
[no name] 7-Jun-11 9:09am
   
start with the line:
alert(response);

What is the result? It seems like response does not have a valid value.
dhage.prashant01 8-Jun-11 0:33am
   
Output is [object Object]
Let me tell you,
I'm getting string from webservice which I get in response.
String is of format
foreach (DataRow dr in table.Rows)
{
sb.Append("<tr><td>");
sb.Append((dr["jobno"]));
sb.Append("</td><td>");
sb.Append((dr["commenttext"]));
sb.Append("</td></tr>");
}

Everything Working Fine, the result is not getting displayed.
What I get output is [object Object]

Is response not getting formated by eval()??
I don't think you use the eval function for this, see this link for more information on the eval function.
http://www.w3schools.com/jsref/jsref_eval.asp[^]

Instead try this approach:

HTML
<body>

<script type="text/javascript">
function updateTable() {
  var oP1 = document.getElementById('div1');
  oP1.innerHTML = "<table><tr><td>test</td></tr></table>";
}

</script>

<input type="button" value="Update table"  önclick="updateTable()" />
<div id="div1"></div>

</body>


Selecty the container object (div with id div1) and write the response string to innerHTML. You may need to add table tags to your output string.
   
v2
Comments
dhage.prashant01 8-Jun-11 1:23am
   
I paste my entire code here, that will give brief understanding
Code for aspx.cs
public static string getWIPComments()
{
DataTable objDT = new DataTable();
//objDT.TableName = "mydt";
try
{
StringBuilder strQuery = new StringBuilder();
strQuery.Append("select jobno,commenttext from tbl_workinprogress_comments where jobno in ( ");
strQuery.Append(" select jobno from tbl_planning P ");
strQuery.Append(" inner join tbl_mechanicalbrief on tbl_mechanicalbrief.mechanicalid= P.mechanicalid ");
strQuery.Append(" where statusid in (10)) ");
SqlConnection objCon = new SqlConnection("server=xxxx;Initial Catalog=xxxx;User ID=xx;Password=xxxx;pooling='true'; Max Pool Size=200;Connect Timeout=2000000;enlist=false;");
SqlCommand objCmd = new SqlCommand();
objCmd.CommandText = strQuery.ToString();
objCmd.CommandType = CommandType.Text;
objCmd.Connection = objCon;
objCon.Open();
SqlDataAdapter objDA = new SqlDataAdapter("", objCon);
objDA.SelectCommand = objCmd;
objDA.Fill(objDT);
}
catch(Exception e) { }
//return ToJson(objDT);
return ToString(objDT);
}

private static string ToString(DataTable table)
{
StringBuilder sb = new StringBuilder();
if (table != null)
{
if (table.Rows.Count > 0)
{
foreach (DataRow dr in table.Rows)
{
sb.Append("<tr><td>");
sb.Append((dr["jobno"]));
sb.Append("</td><td>");
sb.Append((dr["commenttext"]));
sb.Append("</td></tr>");
}
}
}
return sb.ToString();
}

Code for aspx page
$(document).ready(function() {
try {
$('#imgComment').click(function() {
$('#msg').slideToggle("fast", "");
try {
$.ajax({
type: "Post",
url: "WIPCommentsNotification.aspx/getWIPComments",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
try {
// alert(data);
// alert("Begin");
// var result1 = eval(data);
// alert(result1);
// var myObject = eval(result1);
// Bind(myObject);
// alert("End");

alert("Begin");
var myObject = eval('(' + data + ')');

Bind(myObject);
alert("End");
//Bind(myObject);

}
catch (e) {
alert("Error!!");
}
},
error: function(event, request, settings) {
alert(msg);
}
});
}
catch (e) {
alert("Error");
}
})
[no name] 8-Jun-11 1:26am
   
Remove your connection information from your comment.
dhage.prashant01 8-Jun-11 1:32am
   
Connection Info??
[no name] 8-Jun-11 1:34am
   
Yes the password and userid in SqlConnection.
dhage.prashant01 8-Jun-11 1:39am
   
Yes done, do i need to use eval() to serialize string return from webserivce?
[no name] 8-Jun-11 1:47am
   
No, you don't need to use it. I think you'll find the answer here:

http://www.zachhunter.com/2010/04/json-objects-to-html-table/


$('#details').append(CreateTableView(data)).fadeIn();
dhage.prashant01 8-Jun-11 1:55am
   
What he is trying to do in CreateTableView function, is what I'm getting from my webservice. String in format <tr><td>data</td></tr>

This string I want to append to div and i have use this function for it
function Bind(msg) { alert("Hello"); alert(msg); var table = "<table id=tblResult border='1' style='width:100%;'><thead> <tr><th>JobNo</th> <th>Comment</th> </thead> <tbody>"; table += msg; table += '</tbody></table>'; $('#details').html(table); }

Problem is while appending, actual data is not visible. What visible is [object Object] on screen
[no name] 8-Jun-11 2:18am
   
Please take a look at the answer here:

http://stackoverflow.com/questions/6235972/problem-with-parsing-json-return-object
dhage.prashant01 8-Jun-11 2:44am
   
I'm getting output

{"":[{"jobno":210330,"commenttext":"FILE DOWNLOAD START BUT ITS TAKE MORE TIME.\r\nPLEASE CHECK ATTACH SNAP."},{"jobno":210330,"commenttext":"pfa project form"},{"jobno":210482,"commenttext":"in the translation sheet attached. please take text from the sheet name \"Day cream SPF15\". in this sheet take option 2 text . the conservative copy. which is marked in yellow."},{"jobno":210502,"commenttext":"Create cld for all four AP,KA,KE ,TN"},{"jobno":210518,"commenttext":"Create cld for all four AP,KA,KE ,TN"}]}

can i use it like this to get value?
for (var i = 0; i <= msg.length - 1; i++) {
row = '<tr>';
row += '<td>' + msg[i].jobno + '</td>';
row += '<td>' + msg[i].commenttext + '</td>';
row += '</tr>';
table += row;
}

I tried it gives undefined in table values
[no name] 8-Jun-11 2:58am
   
data contains the collection. So you should use jQuery.each(data, function (rec) { ...

Like the example.

And inside the loop address your fields with this.jobno and this.commenttext
dhage.prashant01 8-Jun-11 3:14am
   
In loop alert this.jobno, it gives undefined
dhage.prashant01 8-Jun-11 3:00am
   
JSON.parse(msg);
Is not working, because when i alert the output of JSON.parse(msg);
it gives output [object Object]
dhage.prashant01 8-Jun-11 2:14am
   
Check out this link, i have used this in webservice to return data
http://usmanshabbir.blogspot.com/2010/10/simplest-way-to-use-jquery-datatable-in.html
Here is final Solution:
aspx.cs file code
private static string ToString(DataTable table)
    {
        StringBuilder sb = new StringBuilder();
        StringBuilder sb1 = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        if (table != null)
        {
            if (table.Rows.Count > 0)
            {
                foreach (DataRow dr in table.Rows)
                {
                    sb.Append("<table><tbody><tr><td>");
                    sb.Append((dr["jobno"]));
                    sb.Append("</td><td>");
                    sb.Append((dr["commenttext"]));
                    sb.Append("</td></tr></tbody></table>");
                }
            }
        }
        //js.Serialize(sb, sb1);
        return sb.ToString();
    }


aspx file code (JQuery with AJAX Code)
$.ajax({
                            type: "Post",
                            url: "WIPCommentsNotification.aspx/getWIPComments",
                            data: "{}",
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            success: function(data) {
                                try {
                                    data = data.hasOwnProperty("d") ? data.d : data;
Bind(data);
}
                                catch (e) {
                                    alert("Error!!");
                                }
                            },
                            error: function(event, request, settings) {
                                alert(msg);
                            }
                        });

function Bind(msg) {
            //alert("Hello");
//            var response = JSON.parse(msg);
            //            alert(response);
            try {
                var table = "<table id="tblResult" border="1" style="width:100%;"><thead> <tr><th>JobNo</th>  <th>Comment</th>  </tr></thead>  <tbody>";
                table += msg;
                table += '</tbody></table>';
                $('#details').html(table);
            }
            catch (e){alert("Table Error!!");}
        }


Happy Coding..!!
Special thanks to RUARD..
   
Comments
[no name] 8-Jun-11 3:42am
   
You're welcome. I'm glad you solved the problem.
dhage.prashant01 8-Jun-11 3:51am
   
Yes after 4 days of research, well also came to know what actually JSON is and why it is used.
Nice Experience...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900