From JSON to JavaScript transformations

Currently, I am attempting to utilize JSON with data retrieved from the server by implementing this PHP script:


include("db_connect.php");

mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

$result = mysql_query("SET NAMES utf8");
$query = "SELECT * FROM models WHERE models.product_id='".$product_selected."'";
$result = mysql_query($query);
$json_object =  "{ \"model\": [";

   while($result_row = mysql_fetch_row($result)) {
     $json_object .= " {\"model_name\" : \"".$result_row[1]."(".$result_row[2].")";
     $json_object .= "\"},";

    }
       $json_object = substr($json_object,0,strlen($json_object)-1);
       $json_object .= " ]};";

       echo  json_encode($json_object);

The resulting output of the PHP code above is a JSON-formatted response like this:

{ "model":
           [
              {"model_name" : "xxxxx "},
              {"model_name" : "xxxxx "},
              {"model_name" : "link2(U)"},
              {"model_name" : "xxxxx)"}
           ]
  };

However, upon receiving this response through Ajax, the following error occurs:


var my_JSON_object = {};
var xmlHttp = createXmlHttpRequestObject();
  try {
         xmlHttp.open("GET", "ajaxproduct_new.php?product_id=" product_id,true);
         xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
              my_JSON_object = JSON.parse( xmlHttp.responseText );

             alert(my_JSON_object.model[0].model_name);
              }
  }
             xmlHttp.send(null);

   } catch (e){
           alert("Can't connect to server:\" e.toString());
}

An attempt to trigger an alert for

my_JSON_object.model[0].model_name
results in the error message that my_JSON_object.model is undefined.

If you have any insights on why this issue persists despite repeated attempts, please share your knowledge. Thank you!

Answer №1

When creating a JSON-like string and passing it to the json_encode function, it is incorrect. The json_encode function actually accepts an object or an array. Therefore, you should create an array instead of a string:

$data = array();

while(($result_row = mysql_fetch_row($result))) {
    $data = array('model_name' => $result_row[1] . '(' . $result_row[2] .')');
}

echo json_encode(array('model' => $data));

Your JavaScript code seems to be fine.

Answer №2

Before attempting to manipulate data.model[0].model_name, it is crucial to understand what data actually represents. Using eval for testing purposes may not be the best approach.

To begin debugging, start by alerting the xmlHttp.responseText variable!

  • If the response doesn't match your expectations, the issue likely lies with the server.

  • If the response matches your expectations, there may be a client-side problem or oversight in JSON formatting.

In conclusion, following Felix's advice would probably lead you in the right direction.

Answer №3

Check out these code snippets: let information = eval("(" + xmlHttp.responseText + ")"); displayInformation(alert(data.model[0].model_name)

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

Tips for efficiently waiting for the outcome in a unified function for multiple callbacks within node.js

Perhaps the question title is not the most appropriate, but let me explain what I am trying to achieve in my code // First Callback Function connection_db.query(get_measure_query,function(err,user_data1){ if(err){ // throw err; ...

Tips for transferring a value from a Next.js route to a physical component

So, I encountered some issues while creating a Next.js project related to the database. To solve this problem, I connected to Vercel's hosted database. After successfully inserting and selecting data into the database using routes, I wanted to enhance ...

Issue experienced with Vue2 where utilizing a computed property to filter a nested v-for structure

I have a unique HTML challenge that requires me to iterate through an unconventional data setup. The information is retrieved in two separate parts from Firebase: one for categories and another for businesses. The structure of the data is as follows: Busi ...

Next.js has a problem where it displays incorrect data when users navigate rapidly between pages

An unusual challenge has emerged while rendering data on a Next.js page in my application. Here's the scenario: I've created a Next.js page that showcases customer details based on a query parameter called cid. The page retrieves customer data an ...

Using MVC's AntiForgeryToken with ajax requests and IsAjaxRequest() function

Forgive my confusion on this matter, but I've been pondering it recently. Perhaps I am overlooking some key details about the inner workings of this system, and naturally, I haven't had the opportunity to test this particular scenario. Picture a ...

attempting to retrieve the selected values from within an iframe

I'm attempting to access the values of an iframe element select within a dialog on my page. In my JS file, I wrote code to access a select with the ID "firstSelectms2side__sx", but it didn't work as expected. Setting aside the iframe, I also tr ...

Using Node.js, securely encode data using a private key into a base64 format that can only be decoded on the server side

Here is my specific situation: An http request arrives at the server for a login action A user token needs to be created. This token consists of a Json object composed of different fields. It is then converted to a string and encoded in Base64. const ...

Renaming a list of Object[] in a JList: A step-by-step guide

Novice in programming here. I am currently developing an application that will provide users with information about various companies. The data is obtained through an API in different formats - some have fields that make deserialization easier, while othe ...

How can you effectively use a table filter extension to sort through dropdown values?

Is there a way to update the dropdown values based on new data after applying the first filter? For example, only displaying $0 in the second dropdown menu? Essentially, I want to filter the values in a table and then have the dropdown options reflect the ...

Utilizing data in mongoose: A beginner's guide

I have two database models: User and Conversations. The User model has the following schema: const userSchema = mongoose.Schema({ username: String, logo: String, ..... }) and the Conversation schema is as follows: const conversationSchema = mongo ...

What is the best way to utilize v-select for searching entries while also allowing users to type in text within the input field for the search?

How can I implement a fold-out display for entries in a v-select field while also enabling text search functionality to find specific items? Are there any Vuetify props that address this, or do you have any suggestions on how to approach this? <v-sele ...

Having trouble with jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

Understanding the syntax for matching files and paths in Node/JavaScript using glob, including the use of wild

I stumbled upon http://gruntjs.com/configuring-tasks#globbing-patterns and found it to be the most useful reference so far. I have come across the following statement multiple times: For more on glob pattern syntax, see the node-glob and minimatch docu ...

Tips for manipulating fixed elements while navigating through the window's content

I am currently working with Materialize CSS (link) and I'm trying to figure out how to move select content while scrolling the page or when the window is scrolling. However, the example code I've implemented doesn't seem to be working. Is th ...

JavaScript for Verifying Phone Numbers

After extensive research and tutorials, I am still unable to figure out what is going wrong with my work. I have a button that looks like this: Despite Stack Overflow causing some trouble for me, please ignore the missing class as it is there. This is no ...

Updating the model of a Vuejs single file component (.vue) within the <script> tag

Discovering the world of vuejs, I set out to create a basic single file component for testing purposes. This component's main task is to showcase a boolean and a button that toggles the boolean value. It also listens for a "customEvent" which trigger ...

Obtain the object literal string with additional decorative strings surrounding it

In my current Typescript code, I have an object literal structured like this: const MyNamesStrings = { a: { b: "hello", c: "bye" } d: { e: "qwerty" } } However, I am looking for a way to wrap these strings with add ...

Having a problem with the xmlhttprequest, not confident if it is being called correctly

I encountered a problem with the code I have where a user selects a sales center and it should trigger a currency change. Both selections are dropdowns, but when I choose a sales center, I receive an error saying ReferenceError: makeRequest is not define ...

What is the best way to include the ID when making edits in Angular?

Is there a way to pass the ID when a user edits a document? Below is the HTML and component.ts code: HTML <h1 mat-dialog-title>Hi {{data.name}}</h1> <form [formGroup]="addTaskForm" (ngSubmit)="save()" > <mat-form-field> <ma ...

Navigating the complexities of ASP.Net Ajax and Postback

Despite reading numerous posts on AJAX in ASP .Net, I am still hesitant about utilizing updatepanel. Even with the use of updatepanel, the entire life cycle of an element is still processed. For instance, a basic operation of adding two numbers and displa ...