Updating and passing a value in PHP - javascript

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);
?>

Related

Using Ajax to create session and echo results

I'm trying my best to get this to work. But AJAX is pretty new to me. So hang in there...
Ok, I've asked a couple of questions here about getting this issue that I'm having to work. I (We)'ve come a long way. But now the next issue is here.
I'm trying to echo a session in a div using AJAX.
The AJAX code is working, I can echo plain text to the div I want it to go. The only problem I have is it does not display the title of the item.
I have some items (lets say 3 for this example) and I would like to have the custom save the Items in a Session. So when the customer clicks on save. The ajax div displays the title. And if the custom clicks the 3rd item it show the 1st and 3rd item, etc...
My HTML:
<button type="submit" class="btn btn-primary text-right" data-toggle="modal" data-target=".post-<?php the_ID(); ?>" data-attribute="<?php the_title(); ?>" data-whatever="<?php the_title(); ?>">Sla deze boot op <span class="glyphicon glyphicon-heart" aria-hidden="true"></span></button>
My AJAX code:
$(".ajaxform").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "example.com/reload.php",
success: function(data) {
$(".txtHint").html(data);
},
error: function() {
alert('Not OKay');
}
});
return false;
});
My PHP reload.php:
<h4>Saved Items</h4>
<p>Blaat...</p>
<?php echo "Product Name = ". $_SESSION['item'];?>
I saw this code on here: I'm not using this code. Only wondering if I can use it for my code, and then how?
Change session.php to this:
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
And in your HTML code:
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"name": brandName}, function(results) {
$('#SOME-ELEMENT').html(results);
});
}
How I'm getting my title();:
<?php
// Set session variables
$_SESSION["item"][] = get_the_title();
?>
Is this some thing I can use? And could someone help me with the code?
Thanks in advance!
I'm not too sure on what exactly you're trying to accomplish, but here's a quick and dirty example of making an HTTP request (POST) with a name of a product, storing it in a PHP session, and outputting all product names in the session:
HTML
<p>Product A <button class="add-product" data-product="Product A">Add Product</button></p>
<p>Product B <button class="add-product" data-product="Product B">Add Product</button></p>
<p>Product C <button class="add-product" data-product="Product C">Add Product</button></p>
<div id="response">
</div>
JavaScript
$('.add-product').click(function() {
var productName = $(this).data('product');
$.post('addProduct.php', {productName: productName}, function(data) {
$('#response').html(data);
})
});
PHP (addProduct.php)
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if ($productName) {
$_SESSION['products'][] = $productName;
}
?>
<h4>Your added products:</h4>
<ul>
<?php foreach ($_SESSION['products'] as $product): ?>
<li><?php echo htmlspecialchars($product); ?></li>
<?php endforeach;?>
</ul>

form method post and jquery

I'm doing a cakephp form in my view and clicking on the button, I would like to evaluate values before making a certain action, the problem is not me, in another view I have exactly the same code and if it works, but here , do not. However, I do not have any error console.
echo $this->Form->create('Detalle', array('class'=>'form_center', 'type'=>'file','id'=>'detalle_form'));
echo $this->Form->input('FechaEvento', array('type'=>'hidden','value'=>$fecha_evento));
if($SuperAdmin and !$evento['Evento']['gratuito']){
echo $this->Form->input('Inscripcion.cortesia', array('type'=>'checkbox', 'value'=>1, 'label' => utf8_encode('Cortesía'), 'div' => 'input checkbox inputRutPasaporte'));
echo $this->Form->input('Inscripcion.boleta_no_generar', array('type' => 'hidden', 'value' => 0));
}
$options_btn = array('label' => __('Pagar'), 'class' => 'btn_blue', 'div' => false);
echo $this->Form->end($options_btn);
javascript :
<script type="text/javascript">
$(document).ready(function(){
<? if($evento['Evento']['generar_boleta']){ ?>
<? if($evento['Evento']['habilitar_compra_multiple']){ ?>
$('#detalle_form').data('callback', function(form){
alert("TEST");
});
<? } ?>
<? } ?>
});
</script>
The code looks fine but the point is we need information on your control flow. I assume there are missing variables due to it being different.
I advise you to
combine the code into a CakePHP element that is called in the view so you write the code only once (keeping your code DRY)
set DebugLevel to 2
install CakePHP DebugKit DebugKit on Github
check for missing variables and errors
if the problem persists, give us more information accordingly

AJAX GET simple PHP Multiple variables

I need a simple way to retrieve multiple PHP variables into html divs. I searched a lot of posts but I can't found an answer.
I am looking for something like this:
go-to-index.php
<?php
$name = 'Jonh';
$phone = '123456789';
$details = 'Detail about';
?>
index.php
<div class="name">Your Name is : <?php echo $name; ?></div>
<div class="phone">Your Phone Number is : <?php echo $phone; ?></div>
<div class="details">Your Details are : <?php echo $details; ?></div>
I want instead of echo to get them via AJAX Call.
What is the correct AJAX REQUEST syntax to do that?
UPDATE
My bad I do not noticed before but forgot to say I also need to load the calls one by one. I have too many requests and take a lot of time.
May the query .each() function should work like I want?
In your PHP:
<?php
echo json_encode(Array(
'name' => "John",
'phone' => "1234567890",
'details' => "Details about..."
));
Your HTML:
<div class="name">Your Name is : <span class="name_value"></span></div>
<div class="phone">Your Phone Number is : <span class="phone_value"></span></div>
<div class="details">Your Details are : <span class="details_value"></span></div>
Your jQuery:
$(document).ready(function(){
$.getJSON('user-info.php',function(data){
$(".name_value").html(data.name);
$(".phone_value").html(data.phone);
$(".details_value").html(data.details);
});
});
Note: you'll set the user-info.php string to the URL (relative or absolute) of your PHP script that grabs the user info.
You need a PHP script that will output JSON containing the values you want, and you need a Javascript handler to ask for that data and do something when it gets it. Here's an example:
# File: go-to-index.php
<?php
$name = 'Jonh';
$phone = '123456789';
$details = 'Detail about';
echo json_encode(
[
'name' => $name,
'phone' => $phone,
'details' => $details
]
);
Then your HTML page:
<!-- File: index.php -->
<div class="name">Your Name is : <span class="container"></span></div>
<div class="phone">Your Phone Number is : <span class="container"></span></div>
<div class="details">Your Details are : <span class="container"></span></div>
<button class="loadMe" type="button">Click here to make things work</button>
And finally your jQuery:
$(document).ready(function() {
$('.loadMe').click(function() {
$.ajax({
// Path to your backend handler script
url: 'go-to-index.php';
// Tell jQuery that you expect JSON response
dataType: 'json',
// Define what should happen once the data is received
success: function (result) {
$('.name .container').html(result.name);
$('.phone .container').html(result.phone);
$('.details .container').html(result.details);
},
// Handle errors in retrieving the data
error: function (result) {
alert('Your AJAX request didn\'t work. Debug time!');
}
});
});
});
You can do this on any event - the button was just an example. You can also use plain Javascript or any other library, just used jQuery since you tagged it in your question.

Jquery flickering when I add classes to my divs

I'm having trouble with Jquery and flickering. My problem is this, when I convert my id's to classes the below syntax isn't working. The problem is, it flickers. It flickers approx. 7-8 times. What am I doing wrong? Any help would be appreciated. Thanks everyone.
I would also like to add when I change my classes to ID's everything works great but only one item on my webpage has the ability of hide>click>slideToggle (which isn't what I want because I'm listing more than one item per page for sale). This syntax is below as well, it's very similar to the syntax that does not work but I've decided to include it anyway.
(Not working syntax. Has classes)
<?php
echo "<div class=\"fmv2\">Your Name</div>";
?>
<div class="p122">
<?php
echo form_open("submit/submit_info");
echo form_label('Your Name:','name');
$data = array(
"name" => 'name',
"id" => 'box_width',
"value" => set_value('name')
);
echo form_input($data);
echo '<br>';
echo form_submit('Submit','Submit');
echo form_close();
?>
</div>
My Jquery (Not working, has classes)
// JavaScript Document
$(document).ready(function(){
$(".p122").hide(function(){
$(".fmv2").click(function() {
$(".p122").slideToggle(300);
});
});
});
Working syntax (Has Ids)
<?php
echo "<div id=\"fmv2\">Your Name</div>";
?>
<div id="p122">
<?php
echo form_open("submit/submit_info");
echo form_label('Your Name:','name');
$data = array(
"name" => 'name',
"id" => 'box_width',
"value" => set_value('name')
);
echo form_input($data);
echo '<br>';
echo form_submit('Submit','Submit');
echo form_close();
?>
</div>
My Jquery. (Working, has Ids)
// JavaScript Document
$(document).ready(function(){
$("#p122").hide(function(){
$("#fmv2").click(function() {
$("#p122").slideToggle(300);
});
});
});
I figured out my problem. I've been playing around with the syntax and the below code works.
$(function() { // Shorthand for $(document).ready(function() {
$('div.p122').hide();
$('div.fmv2').click(function() {
$(this).next('div.p122').slideToggle(300);
});
});

jquery/ajax request to server and display selected record

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.

Categories

Resources