Having trouble retrieving AJAX response data using jQuery

I have been searching and attempting for hours without success.

On my current page, I am displaying basic data from a database using PHP in an HTML table. However, I now want to incorporate AJAX functionality to refresh the data without reloading the page.

Although I tried implementing this solution, it seems that the AJAX call is working correctly, and the values are refreshing as expected. Yet, I am facing challenges in retrieving these values.

Here is a snippet of my main page (index.php):

<html>
<head>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
</head>
<body>
<h3>Output: </h3>

<table border="1" id="output"></table>

<script id="source" language="javascript" type="text/javascript">
$(function() {
    update_content();
});

    function update_content() 
    {
    $.ajax({                                      
      url: 'query.php',                  
      data: "",                        
      dataType: 'json',                
      success: function(data)          
      {
        if(data){       
       (data + '').length;
    }
    var temp = new Array();
        $('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");
      } 
    });
    setTimeout(function(){
            update_content();
        }, 1000);
    }
</script>
</body>
</html>

In the query.php file (used for AJAX calls):

<?php 
include('inc/connection.php');

# Main query
$sql = "
select LastUpdated, symbol, sum
from TheTable
";

$result = mysql_query($sql);

while($row = mysql_fetch_row($result)){
$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);
}
echo json_encode($table_data);
?>

When I directly run query.php in the browser, I can see all the data in this format:

[{"LastUpdated":"20170614","symbol":"AUD","sum":"20"},{"LastUpdated":"20170614","symbol":"AUD","sum":"10"}]

However, on the main page, I only see undefined inside the table. Ideally, I would like to display all the fetched records from the database (which might vary in number) using a JavaScript loop in the code above.

HINT/MODIFICATION
By changing:

$('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");

to
$('#output').html("<tr><td>"+data[0]+"</td></tr>");

in index.php

AND

$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);

to
$table_data[]=$row;
in query.php,

only the first row is displayed as a string like 20170614,AUD,40.
END HINT/MODIFICATION

This might be a simple question or problem, but I am new to jQuery and experimenting with AJAX for the first time.

P.S. I understand that mysql_* functions are deprecated and acknowledge the security risks involved.

Your assistance would be greatly appreciated.

Answer №1

Whenever you want to update the data table, it is recommended to simply rebuild the entire table. Within your callback function, make sure to iterate through the array and insert new rows into the table.

$.ajax({
  url: 'data.php', //the endpoint to retrieve data          
  dataType: 'json', //format of the data      
  success: function(data) {
      if (!Array.isArray(data) || !data.length) {
          return;
      }

      $("#output").empty(); //clear existing table content
      for(var i = 0, len = data.length; i < len; i++) {

        $("#output").append(
          "<tr><td>" + data[i].LastUpdated + "</td>" + 
          "<td>" + data[i].symbol + "</td></tr>" +
          "<td>" + data[i].sum + "</td></tr>"
        );
      }
    }
});

Answer №2

To implement the necessary modifications, follow these steps:

Replace

data["symbol"]

with

data.symbol

If you encounter any issues, please inform me immediately.

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

Conceal element with Wicket while AjaxButton is loading lazily

I am having an issue with an AjaxLazyLoadPanel on my page, which contains a long-loading list and a submitting AjaxButton. Once the AjaxLazyLoadPanel is fully loaded, upon submission, another long-loading process begins, requiring me to refresh the entire ...

What is the best way to trigger a jQuery function after adding a <div> element through Ajax loading?

When I use Ajax to append a <div>, the dynamic inclusion of jQuery functions and CSS for that particular <div> does not seem to work. The insertion is successful, but the associated jQuery functions and CSS do not load properly. How can this be ...

My jQuery code is encountering issues with the .each loop functionality

I have encountered an issue with the code snippet below, which is intended to hide the "IN STOCK" phrase on specific vendors' product pages. Upon testing, I noticed that the loop doesn't seem to be executing as expected when using console.log. Ca ...

Developing an Angular filter using pipes and mapping techniques

I am relatively new to working with Angular and I have encountered a challenge in creating a filter for a specific value. Within my component, I have the following: myData$: Observable<MyInterface> The interface structure is outlined below: export ...

Perform two functions in order using jQuery within a loop

Just dipping my toes in the waters of Javascript. Please go easy on me :) I'm working with two functions that both involve making jQuery requests within for loops. Here's an example: function x(y,z) { for (var i = 0; i < y; i ++) { $.a ...

Improprove Google PageSpeed score - must resolve

My mobile website is loading incredibly slow, despite my attempts to improve the speed using Google PageSpeed insights. Unfortunately, I'm having trouble interpreting the screenshot and identifying what changes need to be made. Is there anyone who c ...

Declining the request to incorporate an external website into my web platform

While checking the console errors in Google Chrome, I encountered the following error message: The page 'https://website.com' was blocked from framing because a higher-level ancestor violates the Content Security Policy directive: "frame-an ...

Modify the website address and show the dynamic content using AJAX

$(function(){ $("a[rel='tab']").click(function(e){ //capture the URL of the link clicked pageurl = $(this).attr('href'); $("#Content").fadeOut(800); setTimeout(function(){ $.ajax({url:pageurl+'?rel=tab&apo ...

Learn how to properly implement cookies in a fetch request within Nextjs

Here is a code snippet to consider: Index.getInitialProps = async function({req}) { const res = await fetch("http://localhost/api/tiles"); const json = await res.json(); } If the /api/tiles endpoint requires access to the uid cookie from the user, t ...

The cURL command successfully executes the request, however, it fails to work in both Postman and web browsers

A problem arises when the Node Js (express) server responds to requests using cUrl, resulting in an infinite load. However, when requested via Postman or a browser, there are no errors but still faces issues. Despite searching for solutions, none of the s ...

Transfer a term to a different division - JavaScript Object Model

I am trying to achieve a specific task where I need to move one term under another in SharePoint. However, despite my efforts using JSOM and SharePoint 2013, I have not been able to find a direct method for moving terms. The code snippet I have used below ...

Show data from a Mysql table column in a dropdown menu

I am trying to show the values from a MySQL table field in a select box. I attempted the code below but it only displays the specified field values in the echo function and not in the select box. I'm unsure where I made a mistake. $con = mysql_conne ...

Writing and altering content within the <code> element in Chrome is unreliable

Utilizing a WYSIWYG Editor with contenteditable functionality allows users to input "code snippets" using a <code> element. Here is an example: <div contenteditable="true"> <p> This is a paragraph with an <code>inline s ...

How to achieve the wrapping functionality in ReactJS that is similar to

Is there a ReactJS equivalent to jQuery's wrap method? I want to wrap menuContents with the following element: <ul className="nav nav-pills nav-stacked"></ul> The contents of menuContents are generated like this: let menuContents = thi ...

Tips for iterating through nested objects with a for loop

Struggling with validations in an Angular 5 application? If you have a form with name, email, gender, and address grouped under city, state, country using FormGroupname, you might find this code snippet helpful: export class RegistrationComponent implemen ...

What is the method for saving background color and font size preferences in local storage using HTML?

I want to give visitors to my site the option to customize the background color and text size. Can their preferences be saved in local storage? If so, could you share some HTML code to make this possible? ...

JavaScript Update Function for Pointers in Parse.com - Modify a Row with a Pointer

I am currently working with Parse and JavaScript. While I know the ObjectId from the Status_id-class, I am facing a challenge in updating the column in the Question_status-class due to it being of Pointer-type. Can anyone guide me on how to update a Poin ...

Can diverse array elements be divided into separate arrays based on their object type in JavaScript?

Looking to create new arrays based on objects with similar attributes from an existing array? Here's how: Starting with this [ {name: "test", place: "country"}, {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"}, {name: "te ...

Trouble with Spaces in FPDF PHP Library on UNIX Operating System?"

I have encountered a strange issue while using the FPDF library to create a PDF document from MySQL tables. Everything works perfectly fine on my Windows computer, but when I try running the script on my Ubuntu machine, all the spaces disappear inexplicabl ...

How can the Material UI select component be customized to automatically scroll to the top when all items are selected?

After implementing the material ui select feature, I observed that when all items are selected, closed, and then reopened, the scroll position is automatically moved to the end. Is there a way to prevent this and keep it at the top? Current display: http ...