jquery/ajax request to server and display selected record - javascript

I am wondering how jquery/ajax can send a query to the server and then let the server (php) calculte the response, and append it to the webpage with jquery/ajax again?
Example :
I have 3 products in database with the details for each product (name, description and image).
I have a page with links to these 3 products and I want to display only the clicked product details with jquery/ajax :
html :
<nav>
<ul>
<li>prod1</li>
<li>prod2</li>
<li>prod3</li>
</ul>
</nav>
<div></div>
JS
$(document).ready(function() {
$('a').click(function(){
$('div').load("products.php");
});
});
this is what my products.php file looks like :
<?php
try
{$bdd = new PDO('mysql:host=localhost;dbname=ddb', 'root', '');}
catch (Exception $e)
{die('Error : ' . $e->getMessage());}
$reponse = $bdd->query('SELECT * FROM products ORDER BY id DESC') or die(print_r($bdd->errorInfo()));
?>
<div class="prod_details">
while ($data = $reponse->fetch()){ ?>
<h1><?php echo $products['name']; ?></h1>
<p><?php echo $products['description']; ?></p>
<img src="<?php echo $products['image_path']; ?>">
<?php }?>
</div>
This displays all the products, how can I get only the clicked product to be displayed?

there is a few things wrong here. First of all your js:
$('.div').load("products.php");
will try to load products.php into an element with the class of div not into the div element.
secondly it will try to load products.php from the same directory location as your js script. you probably want to do /products.php and then place products.php in the root.
Finally your HTML is incorrect as you need a UL or OL tag around your LI tags.
To get the php to return the individual product you will need to pass the product Id to your PHP and then amend the SQL query to accept a WHERE id clause. something like this:
HTML:
<nav>
<ul>
<li>prod1</li>
<li>prod2</li>
<li>prod3</li>
</ul>
</nav>
<div></div>
JS:
$(document).ready(function() {
$('a').click(function(){
$('div').load("products.php?id=" + $(this).attr('data-id'));
});
});
Then your PHP query should be:
$id = $_GET['id'];
query("SELECT * FROM products WHERE `id` = '$id' ORDER BY id DESC")
That should do it for you, with a bit of fiddling.

Add an id to tag which will be product id, then pass the product id to jquery's load as below:
$('.div').load("products.php?prodid=" + $(this).attr('id'));
In php, do a $_GET['prodid'] to get the clicked product id, and modify your query to use WHERE clause.
Now, dont expect complete solutions, you can take it off from here.

Related

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

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>
record_count.php
<?php
include("db.php");
$search_word=$_GET['q'];
$sql = mysqli_query($db,"Select name, city FROM users where id = $id");
$record_count=mysqli_num_rows($sql);
//Display count.........
echo $city;
echo $name
?>

Ajax - Response from another page

My HTML as follows, located in index.php
<div id="showDetails">
</div>
<div id="showList">
</div>
And my Ajax as follows, still in index.php
function funcReadRecord() {
var readrecord1 = "readrecord1";
var sometext = $('#SNOW_INC').val();
$.ajax({
url : "findsql.php",
type : 'post' ,
data : { readrecord1 : readrecord1,
sometext : sometext } ,
success : function(data, status){
$('#showList').html(data);
}
});
}
Now, I can return my list and view the required list (shown as a list group) in index.php.
I have a button in index.php that when clicked, runs the function.
<div>
<button type="button" onclick="funcReadRecord()" class="btn btn-primary">Search SQL (LIKE)</button>
</div>
The code in findsql.php as follows
if(isset($_POST['readrecord1']) && isset($_POST['sometext'])){
$displaysql = "SELECT * from datadump where short_description LIKE '%".$_POST['sometext']."%'";
$result = mysqli_query($conn, $displaysql);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
$items[] = array(
"number" => $row['number'],
"priority" => $row['priority'],
"description" => $row['short_description']);
}
}
echo '<p class="lead">SEARCH SQL (LIKE)<p>';
echo '<div class="list-group">';
foreach($items as $result) {
?>
<a href="#" class="list-group-item list-group-item-action">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1"><?php echo $result['number']; ?></h5>
<small></small>
</div>
<p class="mb-1"><?php echo $result['description']; ?></p>
<small><?php echo $result['priority']; ?></small>
</a>
<?php
}
echo '</div>';
}
All I'm doing is getting the data from MySQL and assigning them to array and listing them. I know I could do it directly but I need the array in some other function.
The question is how do I make details from the array to show in showDetails div tag when I click the list? Right now, the HREF is #. I could assign a function, but not sure where to write them.
If I should write a function to return them, should I write in index.php or findsql.php?
Thanks in advance.
I understand that you need individual record information in #showDetails div right ! then
step1: assign new function while clicking the particular item as onclick="funcReadRecord(number)", this should at findsql.php file.
step2: write an ajax function in index.php which will send that particular unique id or in your case number
function funcReadRecord(number) {
$.ajax({
url : "findsql.php",
type : 'post' ,
data : { id: number } ,
success : function(data, status){
$('#showDetails').html(data);
}
});
Step3: Write another function in findsql.php with else if block as checking id isset or not, change the query that takes the number or any key that gets only that particular record.
else if(isset($_POST['id'])){
$displaysql = "SELECT * from datadump where number = ".$_POST['id'].";
// remaining design code below
}
We can use the if-else statement to write multiple ajax calls as above.
Edited, Note: kindly ignore the syntax issue in the above code, concentrate on the process used to a single PHP file for multiple ajax calls using branching statements.

Updating and passing a value in PHP

I want to make a bundle creator in Wordpress using Woocommerce, where you select 1 of 4 T-shirts + 1 of 4 pairs of socks and they get added to the cart. Currently I am stuck on figuring out how to approach this. What I currently need to achieve is this:
There is a top image which corresponds to the currently selected product and three smaller images below that. Once you click the small image, it needs to change the top image. There is also a title on the bottom, which corresponds to the currently selected product, that changes together with the top image. You can see the intended result here.
I need to somehow get the ID of the product the user clicks on and pass it to other php functions. This is where I got stuck. Can anybody help me out?
The code should look something like this:
<div id="selected-product-image">
<?php get_the_post_thumbnail(/* ID of the currently selected product*/); ?>
</div>
<ul class="products">
<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 4, 'product_cat' => 't-shirts', 'orderby' => 'name' );
$loop = new WP_Query( $args );
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<li class="product">
<div class="select-product"><!--This should have a function to capture the product ID on click. -->
<?php echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); ?>
</div>
</li>
<?php endwhile; ?>
<div id="selected-product-name">
<?php get_the_title(/* ID of the currently selected product*/) ?>;
</div>
<?php wp_reset_query(); ?>
</ul>
I understand that I can do something like this using AJAX, but I am not sure how to use the returned ID back in get_the_post_thumbnail() or get_the_title(). This is what I got:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#select-product").click(function() {
var id = 29; /* Any value for testing */
jQuery.ajax({
method: "post",
url: "/test.php",
data: {
productID: id
}
})
.done(function(data) {
alert(data);
/* How do I use this data to update the picture/title? */
});
});
});
</script>
<!-- THE test.php FILE -->
<?php
$productID = $_POST['productID'];
echo $productID;
?>
UPDATE:
I have tried editing the test.php to echo a function, but I am getting a 500 error every time I try using a Wordpress function inside the test.php file. I tried including the wp-blog-header.php file so the functions can run, but it still doesn't help. What am I doing wrong?
<!-- THE test.php FILE -->
<?php
include_once('wp-blog-header.php');
$productID = $_POST['productID'];
echo get_the_post_thumbnail($productID);
?>

Passing value from jquery to php variable in same page

I know similar questions to this have been asked before but I don't see an answer that suits my question. I have a div that triggers a jquery script which stores an id. I can get the id into a variable in the jquery but I want to then assign that id to a PHP variable that exists on the same page.
So far this is what I've got. Here is my div that exists in index.php:
echo '<div id="'.$unit_id.'" class="dropdown unit '.$unit_size.' unit-'.$unit_number.' '.$unit_status.' data-unit-id-'.$unit_id.'">';
And here is my jquery that I call in from functions.php:
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
$.ajax({
type: 'post',
data: {id: unit_id}, //Pass the id
});
});
</script>
I want to pass the unit_id into a variable on index.php called $getID but I can't seem to find a way of getting in there. I've tried using post but there really isn't a form being submitted. It's just a dive being clicked on.
You must change your id in your <div> and set it to fetch the variable sent by jQuery. Other than that, your jQuery script looks fine.
Here's how I would do it:
# Fetch the variable if it's set.
<?php $unit_id = (isset($_POST["id"])) ? $_POST["id"] : null; ?>
# Echo it as the id of the div.
<div id = "<?= $unit_id; ?>" class = "dropdown unit"></div>
EDIT:
The PHP code above is equal to:
# Fetch the variable if it's set.
<?php
if (isset($_POST["id"])):
$unit_id = $_POST["id"];
else:
$unit_id = null;
endif;
?>
Assign id to div id attribute like this, Use:
<div id="<?php echo $unit_id; ?>" class="dropdown unit"></div>
Try this hope it will work
<div id="<?php echo $unit_id;?>" class="dropdown unit"></div>
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
$.ajax({
type: 'post',
'id='+unit_id, //Pass the id
});
});
</script>
What you mean by this '$unit_id' in div ID. Just put the code in PHP Tag, while working with PHP in HTML pages use the code inside PHP tags.
Availale PHP tags : <?php echo $unit_id ?> (or) <?=$unit_id ?> (short tag).
Change your div with :
<div id="<?=$unit_id ?>" class="dropdown unit"></div>
or
<div id="<?php echo $unit_id ?>" class="dropdown unit"></div>
Then your script will be work
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
// to check whether value passing or not
console.log(unit_id);
$.ajax({
type: 'post',
data: {id: unit_id}, //Pass the id
});
});
</script>

Trying to show full size image from thumbnails retrieved using php and database

I'm trying to use thumbnails retrieved from database. PHP is working fine and displaying my thumbnails. I don't know how to get the id from database into the imageID for JavaScript function and getElementById, to display as full size when clicked. I can do straight JavaScript inline onsubmit in my code. The inline JavaScript is working; the thumbnail is being displayed, and when clicked a full size shows, but I want to use my database retrieved images to show the full size image when clicked. Do you think you can help me with my code?
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<script type="text/javascript">
//function that shows full sized image of the thumbnail
function showImage(imageID) {
//first hide all images
document.getElementById('image1').style.display = 'none';
//then display the one that had its thumbnail clicked.
document.getElementById(imageID).style.display = '';
}
</script>
</head>
<body>
<h1></h1>
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "travel1";
$conn = new mysqli($host, $user, $pass, $database);
if ($conn->connect_error)
die ("Unable to connect to database: " . $conn->connect_error );
$sql = "select * from what_to_do
where DESTINATION='NEW YORK CITY'";
$result = $conn->query($sql);
if ($result->num_rows >= 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<td>".$row["THUMBNAIL"]."</td>";
}
echo "</table>";
}
else {
echo "You have no destinations";
}
$conn->close();
?>
<p>
<img id="image1" alt="" src="images/NewYork/Pick7/9-11show.jpg"
style="display: none" />
</p>
<p>
<img alt="" src="="images/NewYork/Pick7/9-11thumb.JPG"style="width:100px;
height:100px" onclick="showImage('image1')" />
</p>
In this code the second img tag is closed prematurely, like src="something" etc etc. If that tag were properly formed, I think this should work?
Otherwise, you would just do something like " src="/blah" />
Hopefully that answers your question?
And then for the I onclick function just do essentially the same thing.
I'm going to presume a lot, but here goes!
The above answer is correct, you are prematurely closing an image tag at the bottom of your code, it should be like this:
<img alt="" src="images/NewYork/Pick7/9-11thumb.JPG" style="width:100px;
height:100px;" onclick="showImage('image1')" />
But otherwise there are a few other issues to address...
First, by typing in the specific name of the destination for each query on every page you'll be defeating the purpose in using a database! Just like you've mentioned, you need to use the ID and pull in the data accordingly.
To do this you need to define what the ID is by letting the user select the destination on a previous page/section(in your example a destination list might be appropriate with all the destinations in some kind of order, be that ascending or descending ect... PHP has a few different ways.)
So first, the query to sort by ID is:
SELECT * FROM travel1 order by id desc
and then to set the ID in the URL when the destination link is clicked, here's an example link using php to carry the ID to the next page:
more info
Once you get to the destination info page(that's what I'm calling your above code), filter your data so that you can access the specific destination by ID by firstly adding this to your page(after you've connected to the database that is):
<?php
if(isset($_GET['id'])){
$id = preg_replace('#[^0-9]#i', '',$_GET['id']);
$result = $con->query("SELECT * FROM travel1 WHERE id='$id' ");
while($rows = $result->fetch_assoc()) {
echo "<td>".$row["THUMBNAIL"]."</td>";
}
} else {
echo "We're having some issues...";
}
?>
The above code will pick up the database ID from your URL which was carried over from the previous page(your new destination list) and can be echoed out like your other links such as:
'echo "<td>".$row["THUMBNAIL"]."</td>";'
I hope this helped! =D

Categories

Resources