Is it possible to add a product to cart with a new price using JavaScript? I have been working on a little script that calculates the price of the product. I would really like to write a function like this:
function addToCart(productID, productPrice) {
//add the product to cart with JavaScript
}
Any help or pointers would be deeply appreciated.
So far I have written 4 main files:
functions.js - calculates and shows the current price based on options the customer chooses (this works fine)
ajaxSubmit.js - jQuery ajax to send the variables to my PHP files (sends successfully)
post.php - file where the variables are sent
simple.php - the single product PHP file which displays the product
I have been able to send the variable from the JavaScript function to my product but I don't know how to add the product to cart.
My post.php looks like this:
EDIT: The following code works now and adds the product with the id 747
<?php
require('../../../../../../wp-load.php');
global $woocommerce;
$woocommerce->cart->add_to_cart(747);
sleep(3);
if (empty($_POST['ammount'])) {
$return['error'] = true;
$return['msg'] = 'You didnt select the amount.';
}
else {
$return['error'] = false;
$final_amount = $_POST['ammount'] * 10;
$return['msg'] = 'Youve chosen: ' . $final_amount . '.';
}
echo json_encode($return);
?>
I have found out that you can add a product into the cart using the following code in PHP:
global $woocommerce;
$woocommerce->cart->add_to_cart($product_id);
Then I tried adding these 2 lines into my post.php and it didn't work and also the form stopped working. If I add this into my simple.php (which basically displays the product) it works fine.
My question is: How can I add a product into the cart using this setup?
To add a product using AJAX I had to include the wp-load.php into my post.php file. That way I could access to the woocommerce variable and later add the product. Look above for the code fix.
Related
If any of you are familiar with WooCommerce you may know that we have a [add_to_cart id="product_id"] shortcode to automatically add an item of given product_id to the cart.
This works fine while I give the specific ID in the html code, but I want it to be automated, for example getting the ID from a cookie.
The problem with this is that using JavaScript it is not possible to get function because it has to come from the server side but I've been mumbling for hours and getting nowhere with PHP...
What Can I do?
EDIT 1:
what I have is the following:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('test').innerHTML= '[add_to_cart id="4158"]';
})
and this does not work. Nontheless dinamically with cookies.
You don't give enough information about how you need to retrieve the product ID, but once you have it you could use do_shortcode() to automatically insert it into the shortcode:
if( isset( $_COOKIE['product_id'] ) ) {
$product_id = $_COOKIE['product_id']; // Get this from your cookie somehow
$shortcode = sprintf( '[add_to_cart id="%d"]', $product_id );
echo do_shortcode( $shortcode );
}
Solved the issue with an AJAX request to the server sending all the product information I had, it then answered with the
do_shortcode()
function and I was able to write that answer into some html element to view the button I needed.
Thank in advanced,
I was looking at creating a linked dropdown menu and found tutorial/code online
I have used this code twice to create lmsdropdown.php and clubdropdown.php. I am able to store the values from the lmsdropdown form is a session and echo them to clubdropdown (just for verification that values are present).
lmsdropdown is a php include within members.php and clubdropdown is an include in members2.php.
When I select a value on clubdropdown the page refreshes to populate the 2nd dropdown box and this results in my session data being cleared.
I am new to PHP/Javascript so the answer may be very obvious but this has had me stumped for a few days now. Any help would be very much appreciated.
Below is a merge of two snippets members2.php, that has taken the output of lmsdropdown and stored output in sessions.
clubdropdown shows the java code and also the echo session statements
I am able to correctly echo the session data however the javascript seems to remove this when building dropdown 2.
members.php session data
<?php
session_start();
$_SESSION['lms'] = $_POST['lms'];
$_SESSION['week'] = $_POST['week'];
if (!isset($_SESSION['usr_lvl']) or ($_SESSION['usr_lvl'] != 0)) {
header("Location: login.php");
exit();
}
?>
clubdropdown output of session data
<SCRIPT language=JavaScript>
function reload(form) {
var val = form.lge.options[form.lge.options.selectedIndex].value;
self.location = 'members-page2.php?lge=' + val;
}
</script>
</head>
<body>
<?php
$usr = $_SESSION['usr_id'];
#$lge=$_GET['lge']; // Use this line or below line if register_global is off
if(strlen($lge) > 0 and !is_numeric($lge)){ // to check if $lge is numeric data or not.
echo "Data Error";
exit;
}
$usr = $_SESSION['usr_id'];
$lms=$_SESSION['lms'];
$week=$_SESSION['week'];
echo "<br>Value of \$week = $week<br>Value of \$lms = $lms <br>Value of \$usr = $usr";
The image below shows the session variables outputted to clubdropdown that is included in members2.php
clubdropdown with variables shown
This image shows the errors after a selection is made from th 1st dropdown.
Error after list refresh
From some of the answers to similar questions on here I assume the error is because the post data is being overwritten/removed on refresh but I thought that's what the session was for?
Any input is greatly received thank you.
You are getting the values from $_POST, which the second time you run the page is absent. You need to add an If(isset($_POST['lms'])){ $_SESSION['lms'] = $_POST['lms']; } so that it is skipped if the $_POST value isn't present.
Currently, your $_SESSION variables are still there, but are being replaced with empty $_POST values.
I suspect you might be better off using an AJAX call to populate your dropdown list.
To illustrate my problem description, there is a list to which one or more tasks can be attached.
when user tries to delete the list, a php code would check mysql 'tasks' table to see if there is any task(s) attached to the list being deleted.
if there is/are task(s), user would be prompted a popup, saying that deleting the list would also delete all the attached tasks, asking for confirmation for the same.
on OK, would proceed and delete all tasks, then delete the list .... on Cancel, would do nothing.
I have devised thing as below,
<?php
try
{
$list_id = $_GET['id'];
//Instantiate Database object
$database = new Database;
//check if task exist for the list to be deleted
$database->query('SELECT * FROM tasks WHERE list_id = :id');
$database->bind(':id',$list_id);
$database->single();
$rc = $database->rowCount();
if($rc > 0)
{
?>
<script type="text/javascript">
if(confirm('The list has one or more task attached to it. Deleting the list will also delete the attached tasks. Do you want to proceed ?'))
{
//prepare and execute delete tasks
$database->query('DELETE FROM tasks WHERE list_id = :id');
$database->bind(':id',$list_id);
$database->execute();
//prepare and execute delete lists
$database->query('DELETE FROM lists WHERE id = :id');
$database->bind(':id',$list_id);
$database->execute();
if($database->rowCount() > 0)
{
header("Location:index.php?msg=listdeleted");
}
}
</script>
<?php
}
}
catch(Exception $e)
{
echo '<p>'.$e->getMessage().'</p>';
}
?>
The problem is that - The code does nothing. No error. Simply nothing.
I did some googling and found out that most people are suggesting ajax call to do that. I do not know ajax. So, to do this tiny bit of thing, I would have to devote some considerable amount of time now. So, I need the following 2 things -
Could you people please confirm me if ajax is the only possible solution here? I would only go to ajax if no other way left to execute php as shown above
From the code I pasted above, can anyone suggest any better approach to what I am trying to accomplish?
Either
a) learn to use ajax, as it is the most obvious solution. Once you have learned it you will find it invaluable
or, if you really haven't the time
b) use your JS 'confirm' to redirect the user to a new PHP page, passing the ID of the record that you want to delete in the URL of the page redirect. On that new PHP page, process your delete and then use a PHP redirect to bring the user back to your original page.
Go for option (a)...
Yes, as the guys said, ajax will be one nice way to do this.
The confirm alert it's working?
Inside of your js function, you can't put the php code without the "< ? php..?>" between then as you did.
In one of my webpage I print one button multiple times and all have different logId. I want that when user click then there will JQuery into the picture and there should be no server side post-back. Since a unique log id is associated with every button so I pass the information to JS file from *.Module as below when the button is clicked:-
*.module File -- PHP File
$thm_button .= '<input type="button" class="clsPrevious" id="btnPrev_'.$user->uid.'_'.$logid;>';
*.js File
$('.clsPrevious', context).click(function (event) {
var previousLog=this.id.split('_');
//Retrieve log Id and Process the log id using AJAX call
}
This is working fine here but I feel there is security concern as everyone can view the log id of the button in HTML source.
Are there any ways in Drupal/PHP/HTML to pass the sensitive information to JS without showing in HTML Viewer.
You can pass values from PHP to Javascript with "Drupal.settings".
Read more about it here.
You can create a input button which looks something like this.
$thm_button .= '<input type="button" class="clsPrevious" data-myModule=" . $key . ">;
where $key is a random/serial variable but is unique per Log ID.
Create a mapping array of key value pair and pass to javasript using drupal_add_js()
<?php
drupal_add_js(array('myModule' => array('_YOUR_CUSTOM_KEY_1_' => '_LOG_ID_1_')), 'setting');
?>
And now modify your click function to,
$('.clsPrevious', context).click(function (event) {
var key = $(this).attr("data-myModule");
// Now a this point you have the lookup table in Drupal.settings.myModule
// use the "key" variable to find the LOG ID
}
I want to dynamically create webpages using a php script(for example : category.php) which takes on variable 'category' and do a mysql query to get data from the server and create a webpage.
category.php
< ? php
include_once("php_includes/db_conx.php");
$sql = "SELECT * FROM PRODUCTS WHERE CATEGORY = 'CLOTHING' ";
$result = $db_conx->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
/*GENERATE SOME WEBPAGE*/
}
}
? >
So when a user clicks a link "/category/clothing " it should pick the variable value (category = 'clothing' ) from this link and dynamically generate a webpage with the address "www.example.com/category/clothing" instead of something like "www.example.com/category/?category=clothing"
What i want to avoid is a url having '?' and '='
So I want to achieve 2 things:
A single php file generating pages dynamically by taking values from links like "/category/clothing"
Url of the new webpage should be simple and proper "www.example.com/category/clothing" (of course it should be same as the link clicked ) and not like "www.example.com/category/?category=clothing"
Can someone write a example php or js script which can achieve this or point me in the right direction(in case its very simple)
PHP can't do this by itself. You are going to need an .htaccess apache module called mod rewrite. Here is a tutorial how to make pretty urls.
http://code.tutsplus.com/tutorials/using-htaccess-files-for-pretty-urls--net-6049