Employing eval for parsing the JSON data

function ajaxFunction(){
var ajaxRequest;  // The variable that enables the use of Ajax technology!

try{
    // Compatible with Opera 8.0+, Firefox, and Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // For 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 for this script!");
            return false;
        }
    }
}
// Define a function to handle data received 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 With your assistance, I have successfully implemented the code above that populates a text box with a string received from a PHP file using Json_encode. However, I am facing difficulties in accessing individual elements within the string, which is an array.

The structure of the array is as follows:

[{"user_id":"2790","freelancer_name":"","order_id":"9121","orderamount":"0.00"

My goal is to write a code snippet 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 My issue lies in how to parse the string and extract the data contained within. Specifically, these two variables:

var result=parsedJSON.result;

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

Only return 'undefined' when alerted.

I kindly seek assistance in extracting the data from the string, as the array retrieved from a MySQL table is extensive.

Answer №1

It seems unnecessary to resort to eval for parsing JSON on your own.

Consider using a reliable JSON library such as json2.js or JSON-js

Instead of reinventing the wheel, simplify the process by utilizing existing libraries like these.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing React with file system and path dependent packages

Is there a way to utilize the quick.db package in my ReactAPP with hooks, even though React does not allow the use of FS & Path which are required for this package? I am encountering the following errors: ERROR in ./node_modules/file-uri-to-path/index.js ...

Can the client side version of expressjs routes be utilized?

Can you create client-side routes in the style of expressjs to trigger a callback function for specific routes? For example: app.get('/dogs', function(req, res, next) { // do stuff }); Is there a way to achieve this functionality on the cli ...

Adjustable height for text input field

Is it possible to adjust the height of a textarea dynamically based on user input, rather than relying on scrollbars when content exceeds the width and height of the field? <textarea class="form-control"></textarea> For instance, if a user ty ...

Transforming jQuery into pure Javascript code

UPDATE SUCCESS! I've cracked the code. The solution was to include jQuery by adding it in Joomla through the template/index.php file with this line under "//Add Javascript Frameworks" JHtml::_('jquery.framework');. PROGRESS I'm seekin ...

the specified computed property does not have a value assigned

Issue with the Computed name Property in a Component <template> <div class="person"> <p>{{name}}</p> </div> </template> <script> export default { name: 'person', data () { return ...

Add several converted links as variables in each section

The title may not be the clearest, but I am facing a challenge with an ecommerce site that has unmodifiable HTML. My goal is to include additional links for each product displayed on a page showcasing multiple products. Each link should be unique to its re ...

Does the gltf loader in three.js have compatibility issues with Internet Explorer 11?

Despite the claims on the official website that gltf files should load in three.js scenes using IE11, I have been experiencing issues with the loader. Even the examples provided by three.js fail to work on Internet Explorer when it comes to loading gltf fi ...

Javascript callback function

Greetings everyone! I've developed a simple nodesjs server using express. The server includes a login page where users enter their credentials to be checked against an Sqlite3 DB. My concern lies in the fact that the callback function only executes on ...

The functionality of sending a response to a client in Node.js Express seems to be malfunctioning

I am facing an issue with sending a response back to the client. Despite not receiving any errors, it seems like the response is not working as expected. Can anyone help me figure out why? Below is my code snippet: exports.login = function (req, res, next ...

"What is the proper way to add a new row to a database utilizing AJAX and the MVC framework in C#

I am currently facing an issue with adding a new row into my database using C# MVC AJAX. Despite seeing the textbox value as a parameter in the URL, when I attempt to submit by clicking the button, it fails to work and I am unsure of how to proceed in reso ...

I am searching for a Nodejs library that has the ability to serialize and deserialize paths composed of named components, such as URL pathnames. Can

Here is an example: formatPath("/:item1/:item2/:item3", {item1: "apple", item2: "banana", item3: "cherry"}) => /apple/banana/cherry deserializePath("/:item1/:item2/:item3", "/apple/banana/cherry") => {item1: "apple", item2: "banana", item3: "cher ...

What is the most efficient method for generating random dark colors using javascript code?

Looking for a function that specifically returns dark colors. Although I can generate random colors with the code below, how do I make sure it only retrieves dark ones? document.getElementById('mydiv').style.backgroundColor = '#' ...

Integrate a feature in your form that allows users to preview and edit their submission before finalizing

I've set up my HTML form with the following structure: <div class="container"> <div class="form-group" ng-controller="studentController"> <form role="form" class="well form-horizontal" id="registerForm" name="forms.register ...

Problem with jQuery AJAX Request Resolving JSON Data

One thing I have on my first page is this function: <script> function update() { $("#notice_div").html('Loading..'); $.ajax({ type: 'GET', dataType: 'json', data: latestid, url: '2includejso ...

Ways to differentiate between an angular element and a jQuery element

In order to implement a feature where clicking outside of a dropdown hides it within a directive, I have the following code: $(document).click(function(e) { var selector = $(e.target).closest('.time-selector'); if (!selector. ...

Ways to ensure certain code is executed every time a promise is resolved in Angular.js

Within my Angular.js application, I am executing an asynchronous operation. To ensure a smooth user experience, I cover the application with a modal div before initiating the operation. Once the operation is complete, regardless of its outcome, I need to r ...

Launching npm using the command "npm run protractor" results in console errors being thrown upon completing the test

Recently, we made the decision to streamline the installation process of Protractor on local machines by specifying it in package.json rather than installing it individually with the -g flag. The addition we made looks something like this: "scripts": { ...

Neither Output nor EventEmitter are transmitting data

I am struggling to pass data from my child component to my parent component using the Output() and EventEmitter methods. Despite the fact that the emitter function in the child component is being called, it seems like no data is actually being sent through ...

Interactive webpages with dynamic HTML content, similar to the design of popular platforms such

Explore the source code of Dropbox's homepage or any Soundcloud page. They utilize various scripts and minimal pure HTML content (article, main, p, div). This method of generating pages is referred to as dynamic content/HTML. The main function seems ...

Having trouble displaying Google Map using GMapPanel in EXTJS 4?

Ext.Loader.setPath('Ext.ux', '../ux'); Ext.require([ 'Ext.tree.*', 'Ext.data.*', 'Ext.window.MessageBox', 'Ext.window.*', 'Ext.ux.GMapPanel' ]); var map = new Ext.ux ...