What's wrong with my code? I can't even place an order or save it on database. I'm using ajax/jquery, it reaches the success but the problem is, it doesn't save in database.
PS: I also included place_order(); under script type.
Button:
<button id="place_order" class="btn btn-black">PLACE ORDER</button>
Jquery:
//Placing Order / Complete the Transaction
function place_order() {
$('#place_order').click(function(e){
var place_order = $('#place_order').val();
$.ajax({
type: 'POST',
url: '../pages/class.php',
data: {place_order:place_order},
success:function(data) {
location.href="../pages/index.php";
}
});
});
}
Class.php
if(isset($_POST['place_order'])) {
if(isset($_SESSION['item_cart'])) {
foreach($_SESSION['item_cart'] as $id=>$val) {
$user_id = $_SESSION['id']; //id of users
$product_stocks = $val['product_stocks']; //product stocks
$product_id = $val['product_id']; //id of product/item
$product_name = $val['product_name']; //name of product
$product_quantity = $val['product_qty']; //quantity of product
$product_price = $val['product_price']; //price of product
$product_size = $val['product_size']; //size of product
//Total Price
$total = $product_quantity * $product_price;
//Check if the stocks is less than quantity
if ($product_stocks < $product_quantity) {
echo "Insufficient Stock";
} else {
//Insert it on database
$insert_query = "INSERT INTO tbltransactions(product_name, product_price, product_qty, total_price, product_id, account_id) VALUES('$product_name', $product_price, $product_quantity, $total, $product_id, $user_id)";
$query = mysqli_query($db_conn, $insert_query);
//If the query is success, update the stocks in database
if($query) {
$update_query = "UPDATE tblproduct_extension SET product_stocks = $product_stocks - $product_quantity WHERE product_id = '$product_id' AND product_size='$product_size'";
$query = mysqli_query($db_conn, $update_query);
//unset the SESSION
unset($_SESSION['item_cart']);
}
}
}
}
}
There is no value assigned to the variable place_order
data: {place_order:place_order},
Assign value to variable using
var place_order = $("#place_order").val(); //change field name
Related
In cart.php I have an input where user can input your own price
<input type="number" id="customPrice">
<div data-id="<?php echo $product_id ?>" id="updateCart">Update</div>
And I have a js function for make ajax request with product id and new price data
<script type="text/javascript">
jQuery(function ($) {
let customPrice = document.getElementById('customPrice');
let price = customPrice.value;
let updateCart = document.getElementById('updateCart');
let id = updateCart.dataset.id
updateCart.addEventListener('click', function () {
$.ajax({
url: "../wp-admin/admin-ajax.php",
data: {action: "add_custom_price", id: id, price: 10},
type: "POST",
success(data) {
if (data) {
console.log(data)
}
$("[name='update_cart']").trigger("click");
}
});
});
});
</script>
In my functions.php i have
function add_custom_price($cart)
{
if (is_admin() && !defined('DOING_AJAX'))
return;
if (did_action('woocommerce_before_calculate_totals') >= 2)
return;
if (isset($_POST['price']) && $_POST['id']) {
$price = intval($_POST['price']);
// $id = intval($_POST['id']);
foreach ($cart->get_cart() as $cart_item) {
$cart_item['data']->set_price($price);
}
}
}
add_action('wp_ajax_add_custom_price', 'add_custom_price');
add_action('wp_ajax_nopriv_add_custom_price', 'add_custom_price');
add_action('woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
But it don't work. I have 500 error
Where is my mistake? Or how i can do it or another way? Any suggestion please
You need to get the product, then affect the price, then save
function add_custom_price($cart) {
if (is_admin() && !defined('DOING_AJAX'))
return;
if (did_action('woocommerce_before_calculate_totals') >= 2)
return;
if (isset($_POST['price']) && $_POST['id']) {
$price = intval($_POST['price']);
$id = intval($_POST['id']);
// Get product
$product = wc_get_product($id);
$product->set_regular_price($price);
$product->save();
// delete the relevant product transient
wc_delete_product_transients( $id );
}
}
this is my javascript
<script>
function multiply(id) {
var quantity = $("#quantity"+id).val();
var price = $("#price"+id).text();
var dataArray= 'quantity1='+ quantity + '&price1='+ price;
$.ajax({
url: "ajaxmultiply.php",
data: dataArray,
type: 'POST',
success: function (data) {
$("#total"+id).(data);
}
});
}
</script>
I am able to get the total of the products but i am having issue in getting net total of the product, i am doing this using ajax, when i add the total it will give me previous value as concatenated with next value,i tried using through array but it also didn't work, now i store the total value in new table and then fetch it from there and add it but i didn't give me required answer, i tried to use array in it but it also didn't work for me
This is my ajaxmultiply.php file code
<?php
include 'connection.php';
$quantity=$_POST['quantity1'];
$price = $_POST['price1'];
$total= $quantity * $price;
//echo $total;
$query =mysqli_query ($conn,"INSERT INTO grand_total (total) VALUES
('$total')");
$getdata=mysqli_query($conn,"SELECT * FROM grand_total");
while ($fetchdata=mysqli_fetch_assoc($getdata)){
$newtotal = $fetchdata['total'];
$id = $fetchdata['id'];
$grandTotal=$newtotal + $newtotal;
echo $grandTotal;
}
Your while loop should be like below:
$grandTotal = 0;
while ($fetchdata=mysqli_fetch_assoc($getdata)){
$newtotal = $fetchdata['total'];
$id = $fetchdata['id'];
$grandTotal += $newtotal;
}
echo $grandTotal;
I am trying to update my quantity values saved in array so when i update quantity it is also saved after refresh. Problem is that when i am always updating same item, even when i have multiple items in cart and i try to change quantity of each, it changes quantity of only one item. I am bit lost in these loops, i tried to move the update section out of while but it didnt help. Also when I don't have unset($_POST['qt']) it changes all items quantity in cart, which is wrong.
foreach ($_SESSION['cart'] as $index => $item) {
foreach ($item as $id => $quantity) {
$sql = "SELECT name, image, quantity, price FROM product WHERE product.id_p = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($name, $image, $maxquantity, $price);
while($stmt->fetch()) : ?>
<tr>
<td><?=$image?></td>
<td><?=$name?></td>
<td><?=$id?></td>
<td><input type="number" class="form-control quantitycart" data-id="<?=$id?>" min="1" max="<?=$maxquantity?>" data-min="1" data-max="<?=$maxquantity?>" name="quantitycart" value="<?=$quantity = ($quantity > $maxquantity) ? $maxquantity : $quantity; ?>"/></td>
<td>€<span class="price"><?=$price * $quantity?></span>
<input type="hidden" class="real_price" value="<?=$price?>"/></td>
<td><?=$id?><span class="glyphicon glyphicon-remove-sign"/></td>
<tr>
<?php
if(isset($_POST['qt']) && isset($_POST['idupd'])){
$_SESSION['cart'][$index][$_POST['idupd']] = $_POST['qt'];
unset($_POST['qt']);
unset($_POST['idupd']);
}
endwhile;
$stmt->close(); }
}
}
JS
$('.quantitycart').change(function(){
var container = $(this).parents('tr');
var price = container.find('.real_price').val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
var id = $(this).data('id');
container.find('.price').html(total);
$.ajax({
type: 'POST',
cache: false,
data: {qt: qty, idupd: id},
url: 'includes/cartbody.php',
success: function(data){
}
});
});
EDIT:
if(isset($_POST['qt']) && isset($_POST['idupd'])){
$_SESSION['cart'][$index][$_POST['idupd']] = $_POST['qt'];
unset($_POST['qt']);
unset($_POST['idupd']);
}
Hi I am developing an app in phonegap, where I am getting a particular value from server by connecting php file the value I need to pass is a string value 'pmnno'suppose whose value is '2' I need to get the value of '2' in column name 'personalnumber'.. So I am giving my code below
var jsonData;
$.ajax({
type: 'GET',
url: 'http://xxxx.com/app/get_pday1_number.php',
data: { pmnno: '2' },
dataType: 'html',
success: function (response) {
jsonData = response;
alert(jsonData);
}
});
php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pone"]))
{
$pone = $_GET['pone'];
// get a product from products table
$result = mysql_query("SELECT *FROM pdaynew WHERE pone = $pone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pone"] = $result["pone"];
$product["personaldayone"] = $result["personaldayone"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am getting a success mesage that means connection is succesful but ineed the value of '2' in column 'personalnumber' for that where I need to add that code..If anyone knows pls help me...
Instead of using * use personaldayone:
$result = mysql_query("SELECT personaldayone FROM pdaynew WHERE pone = $pone");
I am trying to create a button that when clicked will add a record to that database, and when clicked again, will delete this record from that database (it's a 'favourite' button).
I would like it to work as follows;
User clicks 'fav' button > button state changes to success > record added
User clicks 'fav' button again > state changes to default > record removed from db
So far my code is as follows (updated code thanks to #Peter);
books_model.php
class BooksModel
{
public function checkFav($bookid,$userid)
{
$book_id=$_REQUEST['book_id'];
$user_id=$_SESSION['user_id'];
$sql = "SELECT * FROM favourite WHERE user_id=? AND book_id=?";
$query = $this->db->prepare($sql);
$query->bind_param('ii', $userid,$bookid);
$query->execute();
$query->store_result();
$rows_found = $query->num_rows();
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (user_id, book_id)
VALUES (?, ?)";
$query = $this->db->prepare($sql);
$query->bind_param('ii',$userid,$bookid);
$query->execute();
} else {
$sql = "DELETE FROM favourite WHERE user_id=? AND book_id =?";
$query = $this->db->prepare($sql);
$query->bind_param('ii',$userid,$bookid);
$query->execute();
}
}
}
books_controller.php
class Books extends Controller
{
function checkFav()
{
$checkFav_model = $this->loadModel('Books');
}
}
itemView.php
$(document).ready(function(){
$( "#fav" ).click(function(){
$( this ).toggleClass( "btn-success" );
book_id = $(fav).val(); // set the value of the button (book_id)
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/checkFav', //location of query
data: {book_id:book_id}, //taken from value of button
success: function () {
$( "div.addtofavs" ).slideToggle( "slow" ); //show div below button
}//end success
});//end ajax
});
});
button html
<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button>
Currently when I click the button and look in the console I can see the post, however nothing is being sent to my db.
Any advice or direction is appreciated as I am quite new to MVC and JS.
public function checkFav($bookid,$userid)
{
$sql = "SELECT * FROM favourite WHERE user_id=:userid AND book_id=:bookid";
$query = $this->db->prepare($sql);
$query->bindParam(':userid', $userid);
$query->bindParam(':bookid', $bookid);
$query->execute();
$rows_found = $query->countRows();
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (user_id, book_id) VALUES (:userid, :bookid)";
$query = $this->db->prepare($sql);
$query->bindParam(':userid', $userid);
$query->bindParam(':bookid', $bookid);
$query->execute();
} else {
$sql = "DELETE FROM favourite WHERE user_id=:userid AND book_id =:bookid";
$query = $this->db->prepare($sql);
$query->bindParam(':userid', $userid);
$query->bindParam(':bookid', $bookid);
$query->execute();
}
}
$book_id=$_REQUEST['book_id'];
$user_id=$_SESSION['user_id'];
checkFav($book_id,$user_id);
You can simply do a check:
SELECT * FROM favourite WHERE user_id = :user_id AND book_id = :book_id
if it returns something, execute the
DELETE FROM favourite WHERE user_id = :user_id AND book_id = :book_id
else do the insert.
If you want to show the book is already added as favourite to the user, then you have to execute another call on page load which gives the button an attribute, which tells you AND the user it's already a favourite or not.
In the last case you don't have to do the check anymore. Just execute the DELETE query if it contains the attribute, else do the INSERT
// try to get the attribute of the button
var attr = $(".favoriteButton").attr('data-favorite');
// check the button has the attribute
if (typeof attr !== typeof undefined && attr !== false) {
//delete query
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/deleteFav', //location of query
data: {book_id:book_id}, //taken from value of button
success: function () {
$( "div.addtofavs" ).slideToggle( "slow" ); //show div below button
}//end success
});//end ajax
});
}
Something like that
Use generic vars: var IsDeleted; var IsAdded; then IsDeleted = 0; IsAdded =1; (your book is added). Change the values again when you delete book IsDeleted = 1; IsAdded =0; when you execute $( "#fav" ).click(function() check those values and do what action you want (add, delete).
<button class="fvrt" data-item-id="11" data-current-state="0"> Like <button> // 0 = normal, 1 = liked
$(document).on('click', '.fvrt', function(){
if($(this).attr('data-current-state') == 0){
like_item($(this).attr('data-item-id')); // send ajax request
$(this).attr('data-current-state', '1');
$(this).val('Liked');
}else{
dislike_item($(this).attr('data-item-id')); // send ajax request
$(this).attr('data-current-state', '0');
$(this).val('Like');
} // checking state
}); // on clicked