How to use jquery and ajax to retrieve an array of data and show it on the screen

I am facing an issue with my ajax request.

Actually, I am unsure of how to fetch multiple records.

I attempted the following:
    $rqt = "SELECT a,b,c from table";
    $res = mysql_query($rqt);
    while ($data = mysql_fetch_assoc($res)):
    $objet = $data;
    endwhile;
//requesting
    return $objet;

However, it only outputs one row in PHP even though there are several records in the database.

The second issue is related to displaying these records.

In jQuery, I tried this:

$.ajax({
                    type: "POST",
                    url: "requetes_ajax/fetch_debours_detail.json.php",
                    data: "groupe="+groupe_debours,
                    success: function(data){
                    $('.remove').remove()
                    console.log(data);
                    $.each(data, function (key, value) {
                        $('#fetchdebours tr:last').after('<tr class="remove"><td>'+data.libelle_debours+'</td><td>'+data.date+'</td><td>'+data.debours_montant_ht_tva+'</td><td>'+data.debours_montant_ht_no_tva+'</td><td>'+data.debours_montant_ttc+'</td></tr>')
                        //alert(key + ': ' + value);
                    });
                    }
                });

The problem here is that instead of displaying all records in one row, it populates items both horizontally and vertically, resulting in as many rows as columns.

Any assistance on this matter would be greatly appreciated.

Answer №1

When utilizing the while loop, you may notice that you are continuously replacing the $objet variable with each new row, resulting in only retaining the latest row.

To construct an array instead, consider implementing the following code:

$objet = array();
while ($data = mysql_fetch_assoc($res)):
    $objet[] = $data;
endwhile;

If you intend to transmit the data as JSON, ensure you set dataType: "json" within your $.ajax call. Next, convert the PHP array into JSON format. You can use the code below:

$json = json_encode($objet);
print($json);

Since you are now passing an entire array instead of just one object, make a slight adjustment to your display code:

$.each(data, function (k, obj) {
    $('#fetchdebours tr:last').after('<tr class="remove"><td>' + obj.libelle_debours + '</td> ... </tr>')
});

Remember to exercise caution when using the code as it has not been tested yet.

Answer №2

Looking at the structure of your ajax request, it appears that you are expecting a JSON response. You can achieve this by following the code snippet below:

$query = "SELECT column1, column2, column3 FROM your_table";
$result = mysqli_query($connection, $query);
$data = mysqli_fetch_assoc($result);
echo json_encode($data);

For more information on how to use json_encode

Please note that PHP version 5.2.0 or higher is required for this function

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

Assess the HTML containing v-html injection

Is there a way to inject raw HTML using Vue, especially when the HTML contains Vue markup that needs to be evaluated? Consider the following example where HTML is rendered from a variable: <p v-html="markup"></p> { computed: { m ...

Selection pseudo selectors for tooltips are a great way to provide additional

Can someone explain how tooltips change on Medium.com when you double click a word or sentence to reveal options like share and edit? https://i.stack.imgur.com/0EVmH.png ...

Using PHP to extract information from a CSV file

I am dealing with a CSV file titled mail.csv that contains the following information: d,2012-08-24 00:00:57+0200,2012-08-24 00:00:45+0200,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5dbdac7d0c5d9ccf5dbd0c2c69bd6d4d8d0c7d ...

how to properly position an image using javascript

I have two tilesheet images and I have successfully rendered them, but I am struggling to figure out how to place the character in front of the map. https://i.stack.imgur.com/n1a3Q.png I have placed these images in two different JavaScript files. This i ...

The database table contains HTML and JavaScript content that is displayed on a textarea

Inside my database table, there is a value that contains PHP/JS/HTML like the following code: <h2>Welcome</h2> <p> &nbsp;&nbsp;test</p> This content can be displayed on a textarea without replacing any HTML or JS elements. ...

Tips for accessing a variable value within a JavaScript function

I am currently facing an issue where I am unable to retrieve a variable from a JavaScript function and use it outside of the function. While I can successfully output the variable value inside the function, I am struggling to access it elsewhere in my sc ...

Specify "Accept" headers using jQuery when fetching data within an iframe

I am working on a webpage where I am adding an iframe dynamically like this: $('<iframe id="testIframe" />').src('http://www.google.nl/').appendTo('body'); The accept headers being sent while loading the content in thi ...

Discover the country linked to a city using Rails and ajax in real time for an autocomplete feature

Looking for a way to implement an autocomplete feature using AJAX in a textfield. User types their city The system searches for the closest match in the database as they type Once a partially matching city is found, it displays options in the format "cit ...

Using Vuejs to dynamically render a select dropdown based on the initial selection made in the first dropdown menu

I am facing an issue with two drop-down menus. The second menu's choices need to be filtered and displayed based on the selection made in the first drop-down. The RoomID value from the first drop-down is used to filter an array of objects for the seco ...

Is it possible for the upload form submission to wait until the file processing is finished?

Is it possible for the form submission to wait until the file processing is complete? I am currently using web2py and its sqlform to upload a video file. As the file is being uploaded, it is also being converted to flv format. The progress of both uploadi ...

Guide to Embedding a SQL Table into an HTML Table

I need to set up a table within my current webpage to showcase a list of movies along with their genres. Welcome to my Movies page. The index.php file contains all the necessary database credentials and establishes the connection. <?php session_start( ...

Failure parsing occurred when attempting to make an HTTP POST request from Angular to a PHP server

When I try to consume the PHP endpoint from Postman, everything works fine. But when I attempt to do the same from an Angular post request, I encounter an error - Http failure during parsing for. Even though I have double-checked my code and it all seems c ...

What is the recommended return type in Typescript for a component that returns a Material-UI TableContainer?

My component is generating a Material-UI Table wrapped inside a TableContainer const DataReleaseChart = (): React.FC<?> => { return ( <TableContainer sx={{ display: 'grid', rowGap: 7, }} > ...

What is the correct method for setting a scope variable from a service in Angular?

Is there a way to retrieve the return value from a service method and set it into the scope for further processing in the template? I've discovered that I cannot directly access the scope within services. While I could use Rootscope, I believe there ...

What is the best way to send JavaScript data to PHP?

Is it possible to post a variable to a PHP script without refreshing the page? If so, how can this be achieved? Here is an example using jQuery: $.ajax({ url: "myphpfile.php", type: "post", data: json/array/whatever, success: function(){ ...

Display a loading animation before the page loads upon clicking

$("#button").click(function(){ $(document).ready(function() { $('#wrapper').load('page.php'); }); }); <div id="wrapper"></div> <div id="button">click me</div> I would like to display a loading ic ...

React - Unable to perform 'removeChild' on 'Node' object: The specified node cannot be removed as it is not a child of this node

I am encountering an issue in my React project with the following structure: <div className="App"> <BrowserRouter> <BasicLayout title={"test"}> <Routes> <Route path="/home&qu ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

Transferring data to a recurring include file

Is there a more efficient way to pass variables in an include that is used multiple times on the same page? Below is a sample code that technically works, but I believe there might be a better approach. Any suggestions would be greatly appreciated. index. ...

Python Selenium- Extract and print text from a dynamic list within a scrolling dropdown element

I am currently working on a project using Selenium and Python to extract a list of company names from a dropdown menu on a javascript-driven webpage. I have successfully managed to reveal the list of company names by clicking the navigation button, and eve ...