Shahab Maboud
Shahab Maboud

Reputation: 45

using eval to parse the JSON string

function ajaxFunction(){
var ajaxRequest;  // The variable that makes Ajax possible!

try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser is too old to run me!");
            return false;
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {

$("#resultTXT").val(data);

var response = data;

var parsedJSON = eval('('+response+')');
alert('parsedJSON:'+parsedJSON);

var result=parsedJSON.result;

var count=parsedJSON.count;

alert('result:'+result+' count:'+count);




},'json'

);      }
}
    ajaxRequest.open("POST", "userfind.php", true);
    ajaxRequest.send(null); 
}

Blockquote so I have got my above code, with your guys help. the above code will fill out the txtbox with a string, but i am not able to access each element of the string. The string is an array paged from a PHP file using Jsone_encode.

the array is something like this. [{"user_id":"2790","freelancer_name":"","order_id":"9121","orderamount":"0.00"

What I wanna do is to write a code like this :

    document.getElementById("_proId").value = user_id;
document.getElementById("_buyerSt").value = freelancer_name;
document.getElementById("_buyerDesc").value = order_id;
document.getElementById("_mngSt").value = orderamount;
  ... etc

Blockquote so my problem is how to split the string and fetch the data. these 2 vars

var result=parsedJSON.result;

    var count=parsedJSON.count;
    alert (""+result);
    alert (""+count);

only alert me undefined.

Please help me to fetch the data from the string.

the array is fetched from a mysql table and it's big

Upvotes: 0

Views: 638

Answers (1)

leewin12
leewin12

Reputation: 1446

1 . Looks there is no good reason to use eval to parse json by yourself.

You can use proven JSON library as json2.js or JSON-js

2 . Your JSON [ {"user_id":"123", ... }, {... }, {...} ] will be parsed as Array.

Use for each to iterate objects in Array.

Upvotes: 2

Related Questions