Embed a JS script WooCommerce on Thanyou page with Order data - javascript

I need to create a script to send a query on the thank you page in woocommerce.
I am trying to do something similar for a shipping script But I nee to call an api with address and skus fired from the order thank you page. Can any of you help?
window.DeliverrApi.getShippingOptions({
destination: {
street1: "110 Sutter Street",
street2: "9th Floor",
zip: "94014",
city: "San Francisco",
state: "CA",
country: "US"
},
skus: [
"sku127"
],
sellerId: "deliverr-seller"
})
there data:
https://tags.deliverr.dev/reference/#getshippingoptions

Use the following to embed a JS for Deliverr in WooCommerce Order received page with the order details:
add_action( 'woocommerce_thankyou', 'deliverr_api_shipping_options_js' );
function deliverr_api_shipping_options_js( $order_id ) {
// Get the WC_Order Object instance from order id
$order = wc_get_order( $order_id );
$seller_id = 'deliverr-seller'; // ? !!! - to be defined
$skus = array(); // Initializing
// Loop through order items
foreach ( $order->get_items() as $item ) {
$product = $item->get_product(); // Get the WC_Product Object instance
$skus[] = $product->get_sku(); // Add each product sku to the array
}
?><script type="text/javascript">
jQuery( function($){
window.DeliverrApi.getShippingOptions({
destination: {
street1: "<?php echo $order->get_shipping_address_1(); ?>",
street2: "<?php echo $order->get_shipping_address_2(); ?>",
zip: "<?php echo $order->get_shipping_postcode(); ?>",
city: "<?php echo $order->get_shipping_city(); ?>",
state: "<?php echo $order->get_shipping_state(); ?>",
country: "<?php echo $order->get_shipping_country(); ?>"
}<?php if( ! empty($skus) ) { ?>,
skus: [
"<?php echo implode('", "', $skus); ?>"
]<?php }
if( ! empty($seller_id) ) { ?>,
sellerId: "deliverr-seller"
<?php } ?>
});
});
</script>
<?php
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related

WooCommerce set cart quantity with AJAX?

I've now been scratching my head about this for several days and need some pointers.
I'm making a custom theme totally from scratch for a WooCommerce site and now I'm trying to get the cart functionality to work. I'm stuck at trying to have buttons (+/-) for updating the quantity of a product item in the cart.
The problem to me seems to be that the WC() I use inside functions.php is not the same instance as the current frontend-session, or something among those lines. At least my thought for now.
If I've debugged correctly the WC()->cart->set_quantity($cart_item_key, 0) gives no error (if using number 0), all other numbers gives '500 (Internal Server Error)'. But even with 0 quantity in cart is never changed nonetheless.
I've enqueued the scripts correctly so the AJAX function call executes fine when the button is clicked.
Here's my HTML and PHP (simplified)
<div class="cart-items">
<?php foreach(WC()->cart->get_cart() as $cart_item_key => $cart_item) : ?>
<div class="cart-item">
<div class="quantity" id="cart-qty-<?php echo $cart_item_key ?>">
<button class="minus" id="cart-subtract"
onclick="updateCartQuantity('<?php echo $cart_item_key ?>', '<?php echo $cart_item['quantity'] ?>', -1)">-</button>
<p><?php echo $cart_item['quantity'] ?></p>
<button class="plus" id="cart-add">+</button>
</div>
</div>
<? endforeach; ?>
</div>
Here's my JS (inside a file called shopping-ajax.js)
function updateCartQuantity(cart_item_key, current_qty, value) {
function qty_cart() {
jQuery.ajax({
type: "POST",
url: my_ajax_object.ajax_url,
data: {
action: "update_cart",
hash: cart_item_key,
quantity: current_qty,
value: value,
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
},
});
}
qty_cart();
}
Here's my PHP function (inside functions.php)
function updateCartQuantity(){
$cart_item_key = $_REQUEST['cart_item_key'];
$quantity = $_REQUEST['quantity'];
$value = $_REQUEST['value'];
WC()->cart->set_quantity($cart_item_key, $quantity + $value);
echo $quantity + $value;
wp_die();
}
add_action( 'wp_ajax_nopriv_update_cart', 'updateCartQuantity' );
add_action( 'wp_ajax_update_cart', 'updateCartQuantity' );
A massive thanks for any help or pointer in advance!
You should manage product qty according to the qty input box(change qty).
My JS:
location: theme directory -> js -> custom.js
jQuery( function( $ ) {
$( document ).on( 'change', 'input.qty', function() {
var $thisbutton = $(this);
var item_hash = $( this ).attr( 'name' ).replace(/cart\[([\w]+)\]\[qty\]/g, "$1");
var item_quantity = $( this ).val();
var currentVal = parseFloat(item_quantity);
$.ajax({
type: 'POST',
url: cart_qty_ajax.ajax_url,
data: {
action: 'my_cart_qty',
hash: item_hash,
quantity: currentVal
},
success: function(response) {
jQuery(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]);
//jQuery(document.body).trigger('update_checkout');
}
});
});
});
fuctions.php -
Setup Enqueue Ajax Scripts:
function enqueue_cart_qty_ajax() {
wp_register_script( 'my_cart_qty-ajax-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '', true );
wp_localize_script( 'my_cart_qty-ajax-js', 'cart_qty_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'my_cart_qty-ajax-js' );
}
add_action('wp_enqueue_scripts', 'enqueue_cart_qty_ajax');
Ajax call -
function ajax_my_cart_qty() {
// Set item key as the hash found in input.qty's name
$cart_item_key = $_POST['hash'];
// Get the array of values owned by the product we're updating
$threeball_product_values = WC()->cart->get_cart_item( $cart_item_key );
// Get the quantity of the item in the cart
$threeball_product_quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9\.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) ), $cart_item_key );
// Update cart validation
$passed_validation = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $threeball_product_values, $threeball_product_quantity );
// Update the quantity of the item in the cart
if ( $passed_validation ) {
WC()->cart->set_quantity( $cart_item_key, $threeball_product_quantity, true );
}
// Refresh the page
echo do_shortcode( '[woocommerce_cart]' );
die();
}
add_action('wp_ajax_my_cart_qty', 'ajax_my_cart_qty');
add_action('wp_ajax_nopriv_my_cart_qty', 'ajax_my_cart_qty');

How do I format this string with json encode?

To fill the value "items" in the script I need to get the individual order item names and prices and list them in the following format:
EventID::Price::Name::productID | EventID::Price::Name::productID
I don't know exactly how to output them in the format outlined above.
My code (to be added to functions.php)
add_action( 'woocommerce_thankyou', 'wg_tracking' );
function wg_tracking( $order_id ) {
$order = wc_get_order( $order_id );
$order_total = $order->get_total();
$code = $coupon->get_code();
$currency = $order->get_currency();
foreach ( $order->get_items() as $item_id => $item ) {
$total = $item->get_total();
$product_name = $item->get_name();
$item_id = $item->get_id();
} $items_list = //something here to order the data?
}
?>
<script>
(function(w,e,b,g,a,i,n,s){w['ITCVROBJ']=a;w[a]=w[a]||function(){
(w[a].q=w[a].q||[]).push(arguments)},w[a].l=1*new Date();i=e.createElement(b),
n=e.getElementsByTagName(b)[0];i.async=1;i.src=g;n.parentNode.insertBefore(i,n)
})(window,document,'script','https://analytics.webgains.io/cvr.min.js','ITCVRQ');
ITCVRQ('set', 'trk.programId', 777777);
ITCVRQ('set', 'cvr', {
value: '<?php echo $order_total ?>',
currency: '<?php echo $currency ?>',
language: 'de_DE',
eventId: 777777,
orderReference : '<?php echo $order_id ?>',
comment: '',
multiple: '',
checksum: '',
items: '<?php echo SOMETHING ?>',
voucherId: '<?php echo $code ?>',
});
ITCVRQ('conversion');
</script>
Based on the recommendation to use json encode, I've now got this.
add_action( 'woocommerce_thankyou', 'wg_tracking' );
function wg_tracking( $order_id ) {
//grab order
$order = wc_get_order( $order_id );
//grab woocommerce objects
$order_total = $order->get_total();
$code = $coupon->get_code();
$currency = $order->get_currency();
// are there any coupons used?
$coupons = "";
$couponCount = 0;
foreach ($order->get_used_coupons() as $coupon) {
$couponCount++;
if($couponCount > 1) { // add comma if more than one coupon
$coupons .= ',';
}
$coupons .= $coupon;
}
// grab line items from the order
$line_items = $order->get_items();
//loop over line items
$wgItems = array();
foreach ( $line_items as $item ) {
$wgItem = array();
$wgItem ['price'] = $order->get_line_total( $item, true, true );
$wgItem ['name'] = $item->get_name();
$wgItems[] = $wgItem;
}
}
?>
<script>
(function(w,e,b,g,a,i,n,s){w['ITCVROBJ']=a;w[a]=w[a]||function(){
(w[a].q=w[a].q||[]).push(arguments)},w[a].l=1*new Date();i=e.createElement(b),
n=e.getElementsByTagName(b)[0];i.async=1;i.src=g;n.parentNode.insertBefore(i,n)
})(window,document,'script','https://analytics.webgains.io/cvr.min.js','ITCVRQ');
ITCVRQ('set', 'trk.programId', 282105);
ITCVRQ('set', 'cvr', {
value: '<?php echo $order_total ?>',
currency: '<?php echo $currency ?>',
language: 'de_DE',
eventId: 1064725,
orderReference : '<?php echo $order_id ?>',
comment: '',
multiple: '',
checksum: '',
items: '<?php echo json_encode($wgItems) ?>',
voucherId: '<?php echo $coupons ?>',
});
ITCVRQ('conversion');
</script>
You can serialize the values to a string and encode with JSON. json_encode should do the trick.
<script>
const data = <?= json_encode($YOUR_ARRAY) ?>
</script>

Live WooCommerce Product Search Form using AJAX (Shortcode)

While the search form works, I need help fixing the problem that occurs when the form is empty after having been typed into.
What I mean is this:
If you start typing a search query, you start to get results. This part works fine.
But if you, while / after typing, remove the text from the search form - you get a list of ALL products.
It should only show results if and when typing and show nothing if and when empty.
Fix:
After applying a modified version of the solution offered and provided by Terminator-Barbapapa as per below, it works as intended.
The code below might not be 100% correct, but it works.
The code so far:
add_shortcode('live_search', 'live_search_function');
function live_search_function() { ?>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="productfetch"></div>
<?php
}
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() { ?>
<script type="text/javascript">
function fetch() {
if( document.getElementById('keyword').value.trim().length == 0 ) {
jQuery('#productfetch').html('');
} else {
jQuery.ajax( {
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#productfetch').html( data );
}
});
}
}
</script>
<?php
}
add_action('wp_ajax_data_fetch' , 'product_fetch');
add_action('wp_ajax_nopriv_data_fetch','product_fetch');
function product_fetch() {
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
You can add a check in your fetch() function to see if your input field is empty. If so, clear the datafetch div, else run your AJAX.
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() { ?>
<script type="text/javascript">
function fetch() {
if( document.getElementById('keyword').value.trim().length == 0 ) {
jQuery('#productfetch').html('');
} else {
jQuery.ajax( {
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#productfetch').html( data );
}
});
}
}
</script>
<?php
}

query wont get variable from page

php isn't passing $id to query
I am trying to execute an inline edit script using data pulled from a mysqli query that pulls specific data based on url ?id= using if isset $_GET $id, the page is getting and echoing the id correctly, however, the query isn't getting the $id variable.
I have tested the query by replacing the $id var with a number relative to the data and it works without issue.
I have tried adding the $id into the $_SESSION and retrieving it from there but still no luck.
The main page is an index.php (which has url of index.php?id=2019018) which fetches data and displays it as a datagrid with inline edit capability through js (fetch_data.php).
you may notice tests etc that have been commented out
both scripts are below, any help appreciated
index.php
<html>
<head>
<title>Inline Table Insert Update Delete in PHP using jsGrid</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<style>
.hide
{
display:none;
}
</style>
</head>
<body>
<div class="container">
<br />
<div class="table-responsive">
<h3 align="center">Inline Table Insert Update Delete in PHP using jsGrid</h3><br />
<div id="grid_table"></div>
</div>
</div>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
//session_start();
//$_SESSION['id_sess'] = $id;
?>
<?php
// echo $_SESSION['id_sess'];
echo $id;
?>
</body>
</html>
<script>
$('#grid_table').jsGrid({
width: "100%",
height: "600px",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete data?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "fetch_data.php",
data: filter
});
},
insertItem: function (item) {
return $.ajax({
type: "POST",
url: "fetch_data.php",
data: item
});
},
updateItem: function (item) {
return $.ajax({
type: "PUT",
url: "fetch_data.php",
data: item
});
},
deleteItem: function (item) {
return $.ajax({
type: "DELETE",
url: "fetch_data.php",
data: item
});
},
},
fields: [
{
name: "job_id",
type: "text",
//css: 'hide'
},
{
name: "part_id",
type: "text",
//css: 'hide'
},
{
name: "part_name",
type: "text",
width: 150,
validate: "required"
},
{
name: "part_cost",
type: "text",
width: 150,
validate: "required"
},
{
name: "part_rrp",
type: "text",
width: 50,
validate: "required"
},
{
name: "quantity",
type: "text",
width: 50,
validate: "required"
},
{
type: "control"
}
]
});
</script>
fetch_data.php
<?php
//$id = $_GET['id'];
//$id = $_SESSION['id_sess'];
$connect = new PDO("mysql:host=localhost;dbname=****", "****", "****");
$method = $_SERVER['REQUEST_METHOD'];
/* if(!isset($_GET['id'])) // if it doesnt get id?
{
echo "IT WORKS";
//$id = $_GET['id'];
}else{
$id = $_GET['id'];
} */
if ($method == 'GET') {
$data = array(
':part_name' => "%" . $_GET['part_name'] . "%",
':part_cost' => "%" . $_GET['part_cost'] . "%",
':part_rrp' => "%" . $_GET['part_rrp'] . "%",
':quantity' => "%" . $_GET['quantity'] . "%"
);
//$query = "SELECT job_id, part_id, part_name, part_cost, part_rrp, quantity FROM jobs INNER JOIN job_parts USING (job_id) INNER JOIN parts USING (part_id) Where job_id = 2019018";
$query = "SELECT job_id, part_id, part_name, part_cost, part_rrp, quantity FROM jobs INNER JOIN job_parts USING (job_id) INNER JOIN parts USING (part_id) Where job_id = '$job_id'";
$statement = $connect->prepare($query);
$statement->execute($data);
$result = $statement->fetchAll();
foreach ($result as $row) {
$output[] = array(
'part_id' => $row['part_id'],
'part_name' => $row['part_name'],
'part_cost' => $row['part_cost'],
'part_rrp' => $row['part_rrp'],
'quantity' => $row['quantity']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
if ($method == "POST") {
$data = array(
':part_name' => $_POST['part_name'],
':part_cost' => $_POST["part_cost"],
':part_rrp' => $_POST["part_rrp"]
);
$query = "INSERT INTO parts (part_name, part_cost, part_rrp) VALUES (:part_name, :part_cost, :part_rrp)";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if ($method == 'PUT') {
parse_str(file_get_contents("php://input"), $_PUT);
$data = array(
':part_id' => $_PUT['part_id'],
':part_name' => $_PUT['part_name'],
':part_cost' => $_PUT['part_cost'],
':part_rrp' => $_PUT['part_rrp']
);
$query = "
UPDATE parts
SET part_name = :part_name,
part_cost = :part_cost,
part_rrp = :part_rrp
WHERE part_id = :part_id
";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if ($method == "DELETE") {
parse_str(file_get_contents("php://input"), $_DELETE);
$query = "DELETE FROM parts WHERE part_id = '" . $_DELETE["part_id"] . "'";
$statement = $connect->prepare($query);
$statement->execute();
}
?>
You need to pass the id to your AJAX request too since it is considered a totally separate request.
e.g.
insertItem: function (item) {
return $.ajax({
type: "POST",
url: "fetch_data.php?id="<?php echo $id; ?>,
data: item
});
},

Wordpress AJAX search not working

I am trying to create a search functionality with AJAX so it will load posts. It currently does not show the results.
I took this code from another post and played around with it as the completed code was sent privately.
Any help would be greatly appreciated.
functions.php file code
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}}
Script (in functions.php)
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
html
<input type="text" name="keyword" id="keyword" onkeyup="fetch()">
<div id="datafetch">Search results will appear here</div>
You might want to update the method name to 'POST' as javascript is case sensitive
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
You also might want to do an async call which needs callback as above approach will do synchronous call. Check this answer for callback approach
jQuery: Return data after ajax call success
there are some typos in your code like an extra } and a mising } later in php code. Please try:
functions.php
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch_search() {
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
html
<input type="text" name="keyword" id="keyword" onkeyup="fetch_search()">
<div id="datafetch">Search results will appear here</div>

Categories

Resources