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 );
}
}
Related
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
I have a dropdown and whenever the value changes I am calling a javascript function to change some values. I am using Codeigniter, and in javascript, I have used ajax and made ajax call to controller function. the response is "success", but it is empty, and even if I write echo "hi" in the controller the response is empty.
ajax_operations.php
function getInventory()
{ echo "hi";
$table ="inventory"
$inventoryRecordOptionsData = "";
$inventoryRecords = array();
$option ="item_name";
if($this->input->post('storeId') != "" ){
//$inventoryRecords = $this->base_model->fetch_records_from($table, array(store_id => $this->input->post('storeId')));
$query = $this->db->query("SELECT id, item_name FROM dt_inventory WHERE store_id = 34");
$inventoryRecords = $query->result_array();
//$inventoryRecords = $this->db->get_where($table,array('store_id' => '35')->result();
if(count($inventoryRecords) > 0) {
$inventoryRecordOptionsData = '<option value="">Select '.$option.'</option>';
foreach($inventoryRecords as $ic) {
$inventoryRecordOptionsData = $inventoryRecordOptionsData . '<option value="'.$ic->id.'">'.$ic->item_name.'</option>';
}
}
else{
$inventoryRecordOptionsData='<option value="">Select '.$option.'</option>';
}
}
echo $option;
//echo $inventoryRecordOptionsData;
}
javascript function
function getInventoryRecords(store_id)
{ //alert(store_id);
var childId = "items";
var optionTxt = "items";
if(store_id > 0) {
$.ajax({
type: "post",
url: "<?php echo site_url();?>/ajax_operations/getInventory",
data: "storeId="+store_id+"",
success: function(data, textStatus, xhr) {
if(data) {
$('#'+childId).empty();
$('#'+childId).append(data);
} else {
console.log("hi"+data+"hello");
$('#'+childId).empty();
alert("empty response");
$('#'+childId).append('<option value="">No '+optionTxt+' available.</option>');
}
$('#'+childId).trigger("liszt:updated");
}
});
} else {
$('#'+childId).empty();
$('#'+childId).append('<option value="">Select '+optionTxt1+' First.</option>');
$('#'+childId).trigger("liszt:updated");
}
}
I am getting "SUCCESS" as status. but the data is empty.
I tried to insert data into database by using ajax and php. However, I have no idea why it is not working. I have tested the html file, all the itemName, category, price are valid and the php file return me "success" just the data inserted to database is empty.
$(document).ready(function(){
var url = "http://domain/addProduct.php?callback=?";
$("#addProduct").click(function() {
var itemName = $("#itemName").val();
var category = $("#select_category").val();
var price = $("#price").val();
var dataString = "$itemName=" + itemName + "&category=" + category + "&price=" + price + "&addProduct=";
if ($.trim(itemName).length > 0 & $.trim(category).length > 0 & $.trim(price).length > 0) {
$.ajax({
type: "POST",
url: url,
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#addProduct").val('Connecting...');
},
success: function(data) {
console.log(data);
if (data == "success") {
alert("Successfully add item");
} else if(data="failed") {
alert("Something Went wrong");
}
}
});
}
return false;
});
});
<?php
header("Access-Control-Allow-Origin: *");
require("config.inc.php");
$name = mysql_real_escape_string(htmlspecialchars(trim($_POST['itemName'])));
$category = mysql_real_escape_string(htmlspecialchars(trim($_POST['category'])));
$price = mysql_real_escape_string(htmlspecialchars(trim($_POST['price'])));
$date = date("d-m-y h:i:s");
$statement = $pdo->prepare("INSERT INTO product(name, category, price, date) VALUES(:name, :category, :price, :date)");
$statement->execute(array(
"name" => $name,
"category" => $category,
"price" => $price,
"date"=>$date
));
if($statement)
{
echo "success";
}
else
{
echo "failed";
}
?>
replace this code:
dataString="$itemName="+itemName+"&category="+category+"&price="+price+"&addProduct=";
to:
dataString="itemName="+itemName+"&category="+category+"&price="+price+"&addProduct=";
and replace this code too:
if($.trim(itemName).length>0 & $.trim(category).length>0 & $.trim(price).length>0)
to:
if($.trim(itemName).length>0 && $.trim(category).length>0 && $.trim(price).length>0)
Because & is a Bitwise Operator But && is Logical Operator, So in this condition we always use logical operator.
You can't use date as your table column. date is a predefined/reserved keyword. Change the name of your date column into your database and modify your sql query and try again.
I have problem with autocomplete in Codeigninter and Jquery
I have a controller
<?php
public function search() {
$user = $_GET['term'];
$query = $this
->db
->select('nama_kota')
->like('nama_kota', $user)
->get('kota');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$row_set[] = htmlentities(stripslashes($row['nama_kota']));
}
echo json_encode($row_set);
}
}
?>
I have a view
<script>
$(function () {
var availableTags = "<?php echo base_url('admin/kota/search'); ?>";
$("#user-input").autocomplete({
source: availableTags
});
});
</script>
<input id="user-input" type="text" name="nama_kota" placeholder="Search User" autocomplete="on">
everything its okay
but I'm trying multiple values
<script>
$(function () {
var availableTags = "<?php echo base_url('admin/kota/search'); ?>";
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#user-input").autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
<input id="user-input" type="text" name="nama_kota" placeholder="Search User" autocomplete="on">
no work and availableTags only read addres url no function in controller
whats wrong guys please help me, Thanks
which type off output you need If you need like this
eg.
name,
address,
blood_group.
with output of Autocomplete call
Sorry For late reply I am very very busy in my work
this is JS call to Controller
<script>
jQuery("#h_student_name").autocomplete({
minLength: 0,
source: "DropdownController/hostel_students/" + $("#h_student_name").val(),
autoFocus: true,
scroll: true,
dataType: 'jsonp',
select: function (event, ui) {
jQuery("#h_student_name").val(ui.item.contactPerson);
jQuery("#h_student_id").val(ui.item.code);
}
}).focus(function () {
jQuery(this).autocomplete("search", "");
});
</script>
and this is controller for call
<?php
//Hostel Student Auto compelete
public function hostel_students(){
$term = trim(strip_tags($this->input->get('term')));
if( $term == ''){
$like = $term;
$result_set = $this->DropdownModel->hostel_students(array('hostel_status_id' => 1));
$labels = array();
foreach ($result_set as $row_set) {
$labels[] = array(
'label' => $row_set->student_name.' S/D '.$row_set->father_name.' ,Form# '.$row_set->form_no.' ',
'code' => $row_set->hostel_id,
'value' => $row_set->student_name,
);
}
$matches = array();
foreach($labels as $label){
$label['value'] = $label['value'];
$label['code'] = $label['code'];
$label['label'] = $label['label'];
$matches[] = $label;
}
$matches = array_slice($matches, 0, 10);
echo json_encode($matches);
} else if($term != ''){
$like = $term;
$result_set = $this->DropdownModel->hostel_students(array('hostel_status_id' => 1), $like);
$labels = array();
foreach ($result_set as $row_set) {
$labels[] = array(
'label' => $row_set->student_name.' S/D '.$row_set->father_name.' ,Form# '.$row_set->form_no.' ',
'code' => $row_set->hostel_id,
'value' => $row_set->student_name,
);
}
$matches = array();
foreach($labels as $label){
$label['value'] = $label['value'];
$label['code'] = $label['code'];
$label['label'] = $label['label'];
$matches[] = $label;
}
$matches = array_slice($matches, 0, 10);
echo json_encode($matches);
}
}
?>
and this is model for call
<?php
// Hostel student autocomplete
public function hostel_students($where, $like = NULL){
if($like):
$this->db->like('student_name', $like);
$this->db->or_like('form_no', $like);
$this->db->or_like('college_no', $like);
endif;
$this->db->join('student_record', 'student_record.student_id=hostel_student_record.student_id');
return $this->db->where($where)->get('hostel_student_record')->result();
}
}
?>
have any issue comment me I will online today
I am trying to get the results from the database whether username is available or not . But it is not giving any results i am not getting ajax response this is the html code
<form id="user_form">
<input placeholder="username here" type="text" name="ajax-data" id="ajax-data">
<input type="submit" name="btnSubmit" id="btnSubmit" Value="Submit">
</form>
<span class="php_responce_here"></span>
This is the ajax code which i have used
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: {ajax-data: textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result);
}
});
});
});
</script>
final code of php where i have used the validation and the query to find whether the username is available in the database or not the problem is that it is not giving any of the result
<?php
error_reporting(0);
require "config.php";// configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if($user_name)
{
$usernamecheck= mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check= mysql_fetch_row($usernamecheck);
if($check[0]==0)
{
if($user_name!=""){
if(strlen($user_name)>25){
echo "You have reached the maximum limit";
}
else{
echo "User name is valid";
}
}
else
{
echo "username is empty";
}
}
else{
echo "Username Already Taken";
}
}
?>
should be submit event not click:
$("form#user_form").submit(function(e) {
e.preventDefault();
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: { "ajax-data": textboxvalue },
success: function(result) {
$(".php_responce_here").html(result);
}
});
});
and as #Cyril BOGNOU pointed out;
data: { "ajax-data": textboxvalue }
You should too add data type to be returned with the parameter if you want to return JSON for example
dataType: 'JSON',
and Yes I think you should better write
data: { "ajax-data": textboxvalue }
So the update should be
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
dataType: 'JSON',
data: {"ajax-data": textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result.message);
}
});
});
});
and return json string from PHP script
<?php
error_reporting(0);
require "config.php"; // configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if ($user_name) {
$usernamecheck = mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check = mysql_fetch_row($usernamecheck);
if ($check[0] == 0) {
if ($user_name != "") {
if (strlen($user_name) > 25) {
$message = "You have reached the maximum limit";
} else {
$message = "User name is valid";
}
} else {
$message = "username is empty";
}
} else {
$message = "Username Already Taken";
}
echo json_encode(["message" => $message]);
}
?>
NOTE : mysql is deprecated. you should use mysqli or PDO
There are some mistakes in your code. check the below code. it should work.
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var textboxvalue = $("#ajax-data").val();
$.ajax({
data: {ajaxdata: textboxvalue},
type: "POST",
url: 'second.php',
success: function (result)
{
$(".php_responce_here").html(result);
}
});
return false;
});
});
</script>
You can not create variable ajax-data with -.
PHP
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$user_name'");
$check = mysql_num_rows($usernamecheck);
you should use mysql_num_rows instead of mysql_fetch_row. it will auto calculate the rows.
Check working example
Empty page? Nothing prints out?
<?php
error_reporting(-1);
ini_set('display_errors', 1);
require "config.php";// configuration file holds the database info
if(isset($username = $_POST['ajax-data'])){
if($l = strlen($username) <= 25 && $l > 2){
$sql = "SELECT * FROM users WHERE username='$username'"; // wide open for SQL injections. use mysqli or PDO instead.
if($rsl = mysql_query($sql) != false){ // ALWAYS verify if your query's ran successfully.
if(mysql_num_rows($rsl) != 0){
echo 'Username already exists';
} else {
echo 'Username is available';
}
} else {
echo 'Query failed: ' . mysql_error();
}
} else {
echo $l > 25 ? 'Reached limit' : 'Needs to be longer';
}
} else {
echo "post['ajax-data'] not set<\br>";
print_r($_POST);
}
?>
Then there is your Javascript code that I have questions on. Yet you have a submit button but you want to check if its valid upon change?
$(document).ready(function(){
$("#user_form").submit(function(event){
event.preventDefault();
$.ajax({
url: "second.php",
type: "post",
data: $(this).serialize(),
success: function(result){
$(".php_responce_here").html(result);
}
});
});
});