John Davidson

javascript - Update content with Ajax. How to separate the output in HTML <div>

0 comments
Message:


I am updating my site content with AJAX by using this method i have found here: https://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html


This works very well but according to this tutorial i have to echo the values i want to show as an updated value in the background running "record_count.php". Later all values are shown up in my frontend file "index.php" within the specific <div id="xxx">. my problem is now that in my background "record_count.php" i have several values i echo but in need them in separate HTML <div id="1, 2, ...> In my example it is $name and $city. How can i connect the values to a specific HTML <div id="1, 2, ...> ? (Please ignore the old query method i have copy/paste here. In my code i am using prepared statements with PDO)


index.php



<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php?q=<?php echo $id; ?>').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds

<body>
<div id="load_tweets"> </div>
</body>

</script>


My Answer:
record_count.php

php
// Connect to database and fetch values
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
$stmt = $pdo->prepare("SELECT name, city FROM your_table WHERE id = :id");
$stmt->bindParam(':id', $_GET['q']);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);

// Echo the values in separate divs
echo '
' . $result['name'] . '
';
echo '
' . $result['city'] . '
';
?>


In this code snippet, we are fetching the values from the database based on the id passed through the GET parameter. We then echo the values in separate divs with specific ids. This way, when the content is loaded in the frontend, the values will be displayed in the respective divs with ids "1" and "2".

Rate this post

3 of 5 based on 7032 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us