add to cart using javascript without refreshing the page - javascript

I am creating an shopping page in which I have many Items that are displayed dinamically from database. I want to be able to add
product in cart without refreshing the page,
I want to know how to submit in javascript and be able to get that expecific data-id.
Normally I would just create a a href and pass product_id as a variable in the URL and then use php to manipulate the variable
<?php
$all_products = all_products();
echo '<div class="products">';
foreach($all_products as $key => $data){
echo '<div class="single-product">
<img src="'.$data['src'].'">
<h3>'.$data['name'].'</h3>
<h4>'.$data['price'].'</h4>
<button type="submit" class="addToCart" data-id="'.$data['product_id'].'">Add to cart</button>
</div>
';
}
echo '</div>';
?>
<script>
let addToCart = document.getElementsByClassName('addToCart');
addToCart.addEventListener("submit",(e)=>{
//let id = e.querySelector(data-id);
})
</script>
UPDATE
Thank you #M.Eriksson for your sugestion, I found online this, so if I replace the button with a href and pass javascript function add_to_cart() with product_id inside the variable I can access that variable in javascript using console.log, and I can get the id dinamically, however, I need to manipulate the id and send it using xmlhttpRequest, but it is giving status = 0, I dont see any mistakes in the sintax, and I used the same xmlhttpRequest in other page to request products from server and works
<?php
$all_products = all_products();
echo '<div class="products">';
foreach($all_products as $key => $data){
echo '<div class="single-product">
<img src="'.$data['src'].'">
<h3>'.$data['name'].'</h3>
<h4>'.$data['price'].'</h4>
<a ref="javascript:add_to_cart('.$data['product_id'].')">Add to cart</a>
</div>
';
}
echo '</div>';
?>
<script>
add_to_cart();
function add_to_cart(product_id=1){
console.log(product_id);
let form_data = new FormData();
form_data.append('product_id', product_id);
let url_data ="php/add_to_cart.php";
let ajax_request = new XMLHttpRequest();
ajax_request.open('POST', url_data);
let status1 = ajax_request.status;
console.log(status1);
ajax_request.onload = function(){
//console.log(ajax_request.responseText);
if(status1 == 200){
let output = JSON.parse(this.response);
//display product added sucessfully
let added_successfully = document.getElementById('added_successfully');
added_successfully.innerHTML=output['success'] ;
}
}
ajax_request.send(form_data);
}
</script>

what i would do is to change the button type to button aka: <button type="button">Button</button>
And after that change the EventListener to click and get the target from the event to access the data.
after which you can call a php script from javascript by using the fetch function which will send a HTTP request to your backend server.
eg: (untested)
<button type="button" class="addToCart" data-id="some data">Add to cart</button>
<script>
let buttonsList = document.getElementsByClassName('addToCart');
for (button of buttonsList) {
button.addEventListener("click",(e)=>{
fetch('/path/to/your/product/api?product_id=' + e.target.getAttribute('data-id')).then((data) => {
console.log('product added to cart!')
})
})
}
</script>
Hope this helps :-)

Related

How to set $_SESSION variable when click on a div

In my portfolio I implemented a PHP script that generate some div that contain images of some works.
When users click on a div, there is a redirect on a details.php page that contains work details. How can I set $_SESSION variable values, in order to use them on details.php?
PHP scipt:
$query2="SELECT * FROM Posts WHERE Category='".$record1['Category']."' ORDER BY data_pubb DESC";
$esito2 = mysql_query($query2);
while($record2 = mysql_fetch_array($esito2))
{
echo "
<div class='col-sm-4 job'>
<div class='container hover-image-container'>
<a href=''>
<img src='".$record2['static_img']."' data-src='".$record2['static_img']."' data-animated-src='".$record2['dinamic_img']."' width='100%' height='100%' />
<div class='overlay'>
<div class='text'>".$record2['title']."</div>
</div>
</a>
</div>
</div>
";
}
You would need to use JavaScript to detect the onclick and use AJAX to start the session.
For starters, add session_start(); to the top of your page.
Then add an onclick event to your div:
<div class='col-sm-4 job' onclick='startsession()`>
Then define the startsession() function:
function startsession() {
$.ajax({
var name = ''; // the name of your session e.g $_SESSION['counters'];
var value = ''; // the value of your session e.g 10
url: "sessionstart.php",
data: {session: name, value: value},
success: function(data){
// your success function
}
});
}
Then on sessionstart.php:
<?php
session_start();
$_POST['name'] = $_POST['value'];
<?
session_start();
//Set session
$name = $_POST['name'];
$_SESSION['user'] = $name;
//Fetch session
echo $_SESSION['user'];
You can perform an AJAX Request on click of the div. Pass the data in this request that you want to set in the Session variable. Once you get the response back you can then visit the details.php and access the Session variable that got set.
For onclick either you can set
<div ... onclick="functionName()" ></div>
Or, set an ID or class and attach an event listener to it.
<div id="myDiv">...</div>
$('#myDiv').on('click',function(){
//perform the ajax request here.
});

Change of div in the same page without refresh

In one of my pages, I have an <a> tag. When I click it, I am passing the variable as a GET parameter and retrieving it in the same page and displaying the details.
The code to get the parameters:
if(isset($_GET['CatId']))
{
$CatId= $_GET['CatId'];
}
else $CatId=0;
if(isset($_GET['MainProductId']))
{
$MainProductId= $_GET['MainProductId'];
$FilterAllProductQuery ="WHERE Product.MainProductId = '$MainProductId'";
$FilterProductQuery = "AND Product.MainProductId = '$MainProductId'";
}
else
{
$MainProductId=0;
$FilterAllProductQuery="";
$FilterProductQuery="";
}
The <a> tag:
<a href='Products.php?CatId=<?php echo $CatId;?>&MainProductId=<?php echo $id;?>' ><?php echo $row["MainProdName"] ?></a>
The details to be displayed:
if($CatId == 0)
{$sql = "SELECT *,Product.Id AS ProdId, Product.Name as ProdName FROM Product $FilterAllProductQuery ";}
else
{$sql = "SELECT * ,Product.Id AS ProdId, Product.Name as ProdName FROM Product INNER JOIN MainProduct ON MainProduct.Id = Product.MainProductId
INNER JOIN Category ON Category.Id = MainProduct.CategoryId WHERE Category.Id = '$CatId' $FilterProductQuery ";}
$result1 = $dbcon->query($sql);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$id = $row["ProdId"];
// $image=$row["ImagePath1"];
$qty = $row["Quantity"];
?>
<li class="col-lg-4">
<div class="product-box">
<span class="sale_tag"></span>
<div class="row">
<img src='themes/images/<?php echo $row["ImagePath1"]; ?>' height='200' width='250'> </a></div></div></li>
Now the code is working fine, but what's happening is that when I click the <a> tag, as I am passing the get parameters, the page is refreshing. As all the code are on the same page, I don't want the page to be refreshed. For that, I need to use Ajax request. How can I do that?
I would make an onclick() event on the a tag like so:
<?php echo '<a c_id="'.$CatId.'" MainProductId="'.$id.'" onclick="sendProduct()">'.$row["MainProdName"].'</a>';
Afterwards i would in a .js file write a simple function called sendProduct() and inside i would do an ajax request to a page named ex: insertproduct.php, get the information back and Insertproduct.php would process the data and you could use .html() or .append() to assign the data to the div showing the data with a normal id.
The c_id, MainProductId are custom attributes you could recieve in the .js file as $("#youraTag").attr("c_id");
There's a really good guide here on basic ajax: https://www.youtube.com/watch?v=_XBeGcczFJo&list=PLQj6bHfDUS-b5EXUbHVQ21N_2Vli39w0k&index=3&t=1023s
First you have to remove the href of the link and give it an id.
<a id='link'>
<?php echo $row["MainProdName"] ?>
</a>
Then you put this jQuery into your page. Note, you need to have a div in which you are going to put in all your obtained results. I reffered to this div in the code as #mydiv.
$("#link").click(function(){
$("#mydiv").load("Products.php?CatId=<?php echo $CatId;?>&MainProductId=<?php echo $id;?>");
});

Posting php variable through javascript

So I've setup my php table to be paginated by javascript (so that I dont have to refresh the webpage when looking through the pages of the table) and I'm trying to get a php variable $userid to be passed through the JS as my table needs this variable to echo the correct information from the sql database
Any help is greatly appreciated, my code is as below
<?php include '../session.php';
$userid = $_GET['id'];
?>
<div id='retrieved-data'>
<!--
this is where data will be shown
-->
<img src="../images/ajax-loader.gif" />
</div>
<script type = "text/javascript" src = "includes/js/jquery-1.7.1.min.js"></script>
<script type = "text/javascript">
$(function() {
//call the function onload
getdata( 1 );
});
function getdata( pageno ){
var targetURL = 'includes/pagination/userchatlog/search_results.php?page=' + pageno;
$('#retrieved-data').html('<p><img src="images/ajax-loader.gif" /></p>');
$('#retrieved-data').load( targetURL ).hide().fadeIn('slow');
}
</script>
First off, always use json_encode when outputting PHP variables in javascript. It ensures that the data is safely encoded, whatever it might be.
So it appears you just need to do something like this:
function getdata( pageno ){
var userid = <?php echo json_encode($userid) ?>;
var targetURL = 'includes/pagination/userchatlog/search_results.php?userid=' + userid + '&page=' + pageno;
This will make sure your userid gets sent back to the server every time you getdata. You'll be able to access it as $_GET['userid'] server side in search_results.php.

How to change a link pointing to JavaScript to run automatically?

If I have JavaScript function which is called only when I click on a link.
How can I run that JavaScript automatically?
Please note that I've tried many methods, but they are not working.
The code is:
<div align="left"><a href="javascript:show_desc(document.getElementById('d_<?php echo $item->id;?>'));" class="tablchet" ><?php echo $item->name;?></span></a></div>
In order to properly separate presentation (HTML) and behavior (JS) we will not include any JS into HTML markup. We will also not create dependencies between type of tag and JS function so our code will be
<div align="left">
<a href="" data-id="<?php echo $item->id; ?>" class="tablchet">
<span><?php echo $item->name; ?></span>
</a>
</div>
or even the following
<div align="left">
<span data-id="<?php echo $item->id; ?>" class="tablchet"><?php echo $item->name; ?></span>
</div>
For the presentation, it's ok. Now, use some JS into a separate file included after the presentation HTML with <script src="behavior.js"></script> or directly into HTML document between <script></script>.
The JS could be as following:
// Create a function allow you to manipulate the item clicked and the item targeted (with the id).
var showDesc = function (sender, target) {
// When the sender is clicked...
sender.addEventListener("click", function (e) {
e.preventDefault();
// Do Something with the target...
console.log(target);
});
};
// This part will be executed when all HTML presentation from server will be parse.
document.addEventListener("load", function () {
// Our sender is our `class="tablchet"` markup.
var sender = document.getElementsByClassName("tablchet")[0],
// create the id name with the `data-id` information.
id = "d_" + sender.getAttribute("data-id"),
// and our target is finded with its id.
target = document.getElementById(id);
// Use our showDesc with sender and target wished.
showDesc(sender, target);
});
The way you run the javascript on page is to use the script tag.
Your example would look like this:
<script type="text/javascript">
show_desc(document.getElementById('d_<?php echo $item->id;?>'));
</script>
Well,you are document.getElementById,So,one thing is clear you want to call method after complete page is load as you get the element after DOM is ready.
With JavaScript you can do like this.
window.onload = function() {
var show_desc = function(htmlEle) {
// do further processing.
}
var eleId = 'd_<?php echo $item->id;?>';
var htmlEle = document.getElementById(eleId);
show_desc(htmlEle);
}
If you are using jQuery lib then you can do like this.
$(document).ready(function() {
var show_desc = function(htmlEle) {
// do further processing.
}
var eleId = 'd_<?php echo $item->id;?>';
var htmlEle = $("#eleId");
show_desc(htmlEle);
})

How to set the href?

I have a button, when pressed has to call a function from an external php file and load it in a new page.
When I click the "SHOW" button on my index.php page, it shows me the message hold in "mesaj", but displays it in index.php page (that I don`t want!).
What I want to accomplish is when I click on the "SHOW" button on my index.php it shows me the content of the message into another php page, named - for eg - content.php. I want to set the href.
index.php
<input type = "button" class="btn btn-primary" id = "show" onClick = "show()" value = "SHOW"/>
functions.php
function show()
{
database();
$sql = "SELECT title FROM `Articles`";
$titleSql = mysql_query( $sql ) or die("Could not select articles:");
$html = '<html><body><div class="container"><h2>Basic List Group</h2><ul class="list-group">';
while ($title = mysql_fetch_array($titleSql)) {
$html .= '<li class="list-group-item">'.$title["title"].'</li>';
}
$html .= '</ul></div></body></html>';
echo $html;
//die(json_encode(array("mesaj" => "Entered data successfully ")));
}
function.js
function show(){
var n = $('#show').val()
$.post("functions.php", {show:n}).done(function(mesaj){
//$(document).html(mesaj);
document.write(mesaj);
});
}
There is no reason (apparently) to go from PHP to JS in your case. You'd use JS $.post if you need a change of the DOM after it loaded. You can just do this:
<a href="function.php" class="btn btn-primary" id="show"/>SHOW</a>
This works without going thru JS.
If you want to use BUTTON and go via JS then do this:
<input type="button" class="btn btn-primary" id="show" value="SHOW"/>
jQuery:
$('#show').click(function(e){
e.preventDefault();
window.location.href = 'function.php';
});
Plain JS:
document.getElementById("show").onclick = function(){
window.location.href = 'function.php';
}
As a note, be careful because <button> if used inside a form when clicked submits the form. That's why the e.preventDefault();
Let's say you have multiple functions in your function.php and you need to call one a specific one, I would do this:
function.php
if(isset($_GET['fn1'])){
function functionOne(){
//do something
}
}
if(isset($_GET['fn2'])){
function functionTwo(){
//do something else
}
}
And call it this way:
<a href="function.php?fn1" class="btn btn-primary" id="show"/>SHOW</a>
or
$('#show').click(function(e){
e.preventDefault();
window.location.href = 'function.php?fn1';
//window.location.href = 'function.php?fn2';
});

Categories