Obtaining JSON data through Ajax following a MySQL query

In the process of setting up my bookshop, I decided to create a cashdesk script. This form includes an ajax dynamic search feature and is specifically designed for use on a local PC, rather than being published on the web.

By scanning the EAN code, the form automatically populates with details such as the title, author, editor, and price of the book, making it easy to add the item to the basket.

Now, I am working on incorporating Json into this script. However, I am facing challenges in retrieving values from the MySQL query and correctly filling them into the respective fields of my cashdesk form.

I have conducted tests on both the MySQL query and the Json formats.

The MySQL Query

<?php
header('Content-Type: text/html; charset=ISO-8859-1');

include('connexion.php');
$connect_db = connect();

$i = 0;
$tmp = array();


$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");

while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$tmp[$i] = $row;
}
echo json_encode($tmp);

close();
?>

An example of Json:

[{"product_id":"7097","product_name":"Paix pour tous - Livre audio","product_author":"Wayne W. Dyer","product_editor":"Ada","product_price":"20.28"}] 

The Ajax Script

var xhr = null;
  function getXhr()
  {
  if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
  else if(window.ActiveXObject)
  {
  try
  {
  xhr = new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch (e)
  {
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
alert("Not Working");
xhr = false;
}
}

function ajaxEAN()
{
getXhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{

var data = '{"product_id": "product_id", "product_name":"product_name", "product_author":"product_author", "product_editor":"product_editor", "product_price":"product_price"}';

oData = JSON.parse( data);
for( var i in oData){
document.getElementById( i).value = oData[i];
}

}
}
xhr.open("POST",'ajaxrecupaddr.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
EAN = document.getElementById("EAN").value;
xhr.send("EAN="+EAN);
}

Any assistance provided would be greatly appreciated!

Answer №1

From what I gather, extracting JSON data from a response isn't straightforward. In this case, you can achieve this by:

xhr.onreadystatechange = function()
{
   if(xhr.readyState == 4 && xhr.status == 200) {        
     oData = JSON.parse(xhr.responseText);
     for(var i = 0; i < oData.length; i++) {
         for( var key in oData[i]){
            document.getElementById(key).value = oData[i][key];
         }    
     }
}

Here, xhr.responseText will provide a string containing the JSON data received from the server.

A couple of additional pointers to consider: Instead of

header('Content-Type: text/html; charset=ISO-8859-1');

it's advised to use:

header('Content-Type: application/json;');

Moreover, the line below leaves room for SQL injections:

$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");

Instead of simply using

WHERE product_EAN = '$_POST[EAN]'
, it's recommended to do something like
WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "'
:

$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "'");

Learn more about mysql_real_escape_string. It helps properly escape potentially dangerous characters and prevents errors when handling ' symbols in EAN codes. Also, be aware of the deprecation warning for the MySQL extension, suggesting a switch to a different database extension.

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

When running npm run build, an error with the error code ELIFECYCLE is

For some time now, I have been following the "ES6 for everyone" series by Wes Bos, but I hit a roadblock while trying to tackle a webpack episode. Every time I attempt to execute the "npm run build" command in my CMD prompt, I encounter this error: npm ...

Ways to showcase information in a React dropdown menu

Having trouble creating a movie filter based on categories using React select? When trying to display the data, it just doesn't seem to work no matter what I do. Any advice or tips would be greatly appreciated as I'm new to React. The "categorie ...

Using Angular, the $http.post method is utilized to send data in JSON format

I am working with a JavaScript variable that is an array of objects. To display this variable in the view, I am using the code below: <tr ng-repeat="user in lala.users"> <td>{{ user.firstName }}</td> <td>{{ user ...

Instructions for sketching a square at predetermined coordinates

Looking for a simple function to draw a box at specific coordinates x and y. I've searched for guides, but they all seem to provide excessive or insufficient information. Thanks in advance! ...

Node.js fails to send a list of all clients

js. I have conducted a series of tests successfully so far. Hello world Server-client communication with events Multiple rooms However, I am facing an issue in sending messages to the clients using socket.io The main reason for this is to maintain a li ...

Are you experiencing difficulty loading ng-view in AngularJs?

I am new to AngularJs. I am currently using a wamp server and have successfully loaded the HTML page, but unfortunately the view is not being displayed. I have added ng-app to the body as well, but still unable to load the view. <!DOCTYPE html> ...

Click action: two functions, but only the first one seems to be functioning. Feeling frustrated

Here is the HTML code I am using: <td width="15%" align="center"><input name="submit" type="submit" class="button" value="Basic" tabindex="13" onclick="return submit_Click('bxbas','bxsht');" /></td> And b ...

Utilizing a jQuery plugin or function with customizable options when adding elements dynamically

jQuery offers a useful feature where you can use $(document).on(...) to apply an event to newly added elements in the HTML, such as after an Ajax request. Can you provide an example of how to use this with a custom function/plugin like hoverpulse? Anothe ...

Is there a way to incorporate the Indian rupee symbol into a Google chart?

I've been trying to incorporate the Indian Rupee symbol into a Google chart using the code below: var formatter = new google.visualization.NumberFormat({ prefix: '&#8377;' }); However, I'm encountering an issue where ...

Controlling File Upload Edits: A Guide to Effective Management

I am facing an issue on my product page related to adding and updating products in the database. The problem lies with images not displaying correctly. During the product insertion process, everything works fine. In my aspx page, I have the following code ...

A new WordPress plugin that includes a custom designed stylesheet featuring a hidden display property within a specific

After reloading the page, my plugin displays a constructed stylesheet. However, when I access it for the first time or reload with ctrl + f5, the constructed stylesheet does not appear. I have meticulously searched through all of the plugin code looking f ...

Is there a way to create a stacked bar chart through iterative steps?

I am currently working with time series data stored in an array structured like this: var data = [ [{date: 2016-01-01 00:00:00, value: 52}, {date: 2016-01-02 00:00:00, value: 23}, {date: 2016-01-03 00:00:00, value: 42}, {date: 2016-01-04 00:00:00, value ...

What is the mechanism behind the functioning of a click event within a leaflet bindpopup?

I am trying to incorporate a button inside the leaflet popup that will zoom in to the location of the point when clicked. The button and its corresponding event are defined within the pointToLayer() function. However, upon clicking the button, there is no ...

Be warned: Babel has detected a duplicate plugin or preset error

Currently, I am enrolled in a React course on Frontend Masters. As part of the course, we were tasked with modifying the Babel config to allow state instantiations like: state = {index: 0} in class components. However, when I executed the command: npm i ...

Only capitalized keyboard input will be registered by the document on keydown event

I'm currently working on developing a shared canvas wall that looks the same to everyone viewing the webpage and can be edited in real-time by all users. However, I'm facing some challenges when it comes to accurately capturing keyboard input to ...

Overriding JSON variables globally

In my project, I needed to utilize json2.js since the JSON object in the browser (IE8) was not capable of parsing strings into JSON. After reviewing json2.js, I have a question regarding the variable declaration within it. The json2.js file declares a gl ...

Generate and display a random element on a webpage using Javascript or jQuery on page refresh

Currently, I am developing a website for my unique custom themes on a blogging platform. One of the features I am looking to add is a review section, where only one random review will display per page refresh. My question is, can anyone assist me in crea ...

Creating JSON with PHP: Ensuring consistent keys in JSON output derived from PHP arrays

Is there a method to convert a PHP array (or any other similar PHP object) into JSON while maintaining identical keys for a JSON array? For example: {"categories" : [ {"key": "data1"}, {"key": "data2"}, {"key": "data3" } ] } It is worth noting that the ...

Node.js socket.io: How to Handle Multiple Returned Values from a Single Event

I've been working on a simple chat app using Node, Express (^4.15.3), and socket.io (^2.0.3). However, every time I add a new message, I notice that I get an additional response each time. For instance, when I send the message "Hello" for the first t ...

Invoke a React component within a conditional statement

There is a function for exporting data in either csv or xls format based on an argument specifying the type. The functionality works flawlessly for xls but encounters issues with csv. Here's the code snippet: const exportFile = (exportType) => { ...