Save WooCommerce Order details in custom table - php

I have created a custom database in table order-master in which I will save WooCommerce order total amount, shipping charges and token.
For this, I have edited paypemts.php file, code is below:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/canadiapharma.com/wp-config.php' );
global $woocommerce;
global $wpdb;
echo '<h3>Custom Calculation :</h3>';
$amount_2 = $woocommerce->cart->get_cart_total();
$ship_raw = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_shipping_total() ) );
$ship = $ship_raw - 3600;
echo '<strong>Shipping :</strong>';
echo $ship;
$nano=WC()->cart->cart_contents_total;
echo '<br>';
$total_amt = $nano+$ship;
echo '<strong>Total :</strong>';
echo $total_amt;
echo '<br>';
$salt = 'dAta_EnC!=';
$token_raw = base64_encode($total_amt. $salt);
$token = preg_replace(sprintf('/=/', $salt), '', $token_raw);
echo '<strong>Token :</strong>';
echo $token;
$wpdb->query("INSERT INTO order_master (payment_amt, ship, token) VALUES ('$total_amt', '$ship', '$token')" );
?>
This code works fine and stores the data to the database. But it stores the data as soon as the checkout.php page loads. So, I made some changes and created an onclick event on Place Order button in checkout.php page.
OnCLick Event:
<?php echo apply_filters( 'woocommerce_order_button_html', '<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '" onclick="dbinsert()">' . esc_html( $order_button_text ) . '</button>' );
?>
dbinsert():
<script>
function dbinsert() {
var myKeyVals = { amount : <?php echo $total_amt; ?>., ship : <?php echo $ship; ?>., token : <?php echo $token; ?> }
var saveData = $.ajax({
type: 'POST',
url: "savedata.php",
data: myKeyVals,
dataType: "text",
success: function(dbinsert) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
}
</script>
onclick event executes perfectly but doesn't know why data is not going into the database. Below is my savedata.php file.
<?php
global $wpdb;
$total_amt = $_POST['amount'];
$ship = $_POST['ship'];
$token = $_POST['token'];
$stmt = $wpdb->query("INSERT INTO order_master (payment_amt, ship, token) VALUES ('$total_amt', '$ship', '$token')" );
$stmt->bindparam('payment_amt', $total_amt);
$stmt->bindparam('ship', $ship);
$stmt->bindparam('token', $token);
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
?>
Please help me to fix this issue.

Try by changing your ajax url url: "savedata.php", to url: "<?php echo admin_url('admin-ajax.php?action=save_order_data');?>" and add below code in your theme's function.php
add_action('wp_ajax_nopriv_save_order_data', 'save_order_data');
add_action('wp_ajax_save_order_data', 'save_order_data');
function save_order_data() {
global $wpdb;
$total_amt = $_POST['amount'];
$ship = $_POST['ship'];
$token = $_POST['token'];
$stmt = $wpdb->query("INSERT INTO order_master (payment_amt, ship, token) VALUES ('$total_amt', '$ship', '$token')" );
$result = $wpdb->query($wpdb->prepare($stmt));
if($result)
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
}
Updated:
There is an error in var myKeyVals = { amount : <?php echo $total_amt; ?>., ship : <?php echo $ship; ?>., token : <?php echo $token; ?> }. Change your var myKeyVals as below:
var myKeyVals = { amount : "<?php echo $total_amt; ?>",
ship : "<?php echo $ship; ?>",
token : "<?php echo $token; ?>" }
You need to write php code in "" in javascript.
Hope this helps.

Related

values not saving in database

Once we click on Button, i am trying to update values in Database & along with that i need to download pdf....
once values [tracking_id] are updated in database, than only i can able to download pdf....
When i click on button its not updating tracking_id column in database.... instead it showing 0....
shippinglabel.php Full code in pastebin
<?php
$db_handle2= new DBController();
$star="select pincode , xpressbee from shippment_details where xpressbee='xpressbee' and pincode='$pinc'";
$resultstar = $db_handle2->runSelectQuery($star);
if($resultstar)
{
if($orderrecords[$k]["tracking_id"]==''){
?>
<input type="button" name="shipment" id="xpress" value="xpress"
onclick="createshipment('<?php echo $orderrecords[$k]["order_id"]; ?>')" />
<?php }}
?>
<?php
if($orderrecords[$k]["tracking_id"]!='' && $orderrecords[$k]["shipping_name"]=='xpress')
{?>
<a target="_blank"
href="/ecom1/xpress/xpressdownload.php?orderId=<?php echo $orderrecords[$k]["order_id"]; ?>"
id="pdfdownload" >
<input type="button" name="shipment" value="DOWNLOAD" /></a>
<?php }?>
<Script>
function createshipment(orderid)
{
var assignee='<?php echo $_SESSION['login_user']?>';
alert(orderid);
$.ajax({
url: "xpressshipment.php",
type: "POST",
data:'orderid='+orderid+'&assignee='+assignee,
success: function(data){
if(data==1)
{
$("#pdfdownload").show();
$("#ekartc").hide();
}
if(data==2){alert("order id not proper.");}
if(data==0){alert("First Enter Tracking Id.");}
window.location ="/ecom1/xpress/xpressdownload.php?orderId="+orderid;
//location.reload();
}
});
}
xpressshipment.php Full code in pastebin
<?php
$data =
array (
'OrderNo' => $order_id,
'AirWayBillNO' => $resultc[0]['awb'],
);
$data = json_encode($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
$res=json_decode($curl_response);
if($res->AddManifestDetails[0]->ReturnMessage=='successful')
{
$sqli="update do_order set tracking_id='".$resultc[0]['awb']."',shipping_name='xpress' , current_status='99' where order_id='".$order_id."'";
$resulti=$db_handle->executeUpdate($sqli);
$sqlj = "update ecomexpress_awb set orderid = '".$order_id."',status='assigned' WHERE awb ='".$resultc[0]['awb']."'";
$resultj = $db_handle->runSelectQuery($sqlj);
}
xpressdownload.php Full code in pastebin
<?php
if(isset($_GET['orderId']) && $_GET['orderId']!='')
{
$orderid=$_GET['orderId'];
}
else
{
echo 2;
}
$sqlorder = "SELECT comments,tracking_id,order_id,order_date,address,product_type,alternateno,sku,customer_email,price,customer_name,phone_number,payment_type,product_name from do_order where order_id='".$orderid."' limit 1";
$resultdoorder = $db_handle->runSelectQuerys($sqlorder);
if($resultdoorder['tracking_id']=='')
{
echo "0";
}
else
{
// pdf download code
}

Braintree payment with Paypal doesn't connect with my Paypal account

I have been working with the implementation of Braintree payment gateway and now i am stuck with its Paypal method. The issue is describe below.
I have integrated the necessary code for for this and when selection the Paypal method and trying to login to Paypal, it always shows the error like below screenshot.
[![error screen while login in to paypal][1]][1]
I think this is happening because of the client token is wrong. but i have creating the token using the php method: $clientToken = Braintree_ClientToken::generate().
(It will currently login when i give the demo client token provided by Braintree demo code).
Here below i mentioned my code . Please check and hope anyone can trigger the issue.
<?php
require_once '_environment.php';
function braintree_text_field($label, $name, $result) {
echo('<div>' . $label . '</div>');
$fieldValue = isset($result) ? $result->valueForHtmlField($name) : '';
echo('<div><input type="text" name="' . $name .'" value="' . $fieldValue . '" /></div>');
$errors = isset($result) ? $result->errors->onHtmlField($name) : array();
foreach($errors as $error) {
echo('<div style="color: red;">' . $error->message . '</div>');
}
echo("\n");
}
// CLIENT TOKEN
$clientToken = Braintree_ClientToken::generate();
if(isset($_POST['payment_method_nonce'])){
$nonce = $_POST['payment_method_nonce'];
$result = Braintree_Transaction::sale(array(
'amount' => '91.00',
'paymentMethodNonce' => $nonce
));
if ($result->success) {
echo($result->customer->id);
echo($result->customer->creditCards[0]->token);
echo 'success';
} else {
foreach($result->errors->deepAll() AS $error) {
echo($error->code . ": " . $error->message . "\n");
}
}
}
?>
<form id="checkout" method="post" action="">
<div id="payment-form"></div>
<input type="submit" value="Pay $10">
</form>
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>
var clientToken = '<?php echo trim($clientToken);?>';
braintree.setup(clientToken, "dropin", {
container: "payment-form"
});
</script>
To create a PayPal transaction, you will need a customer id, the following sample works for me.
index.php
<?php
require("config.php"); //config.php contains Braintree_Configuration object.
$aCustomerId = '39538986'; // can be generated from braintreegateway.com vault->New Customer
$clientToken = Braintree_ClientToken::generate(array(
"customerId" => $aCustomerId
));
;
?>
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>
var clientToken = "<?php echo $clientToken ?>";
braintree.setup(clientToken, "dropin", {
container: "payment-form"
});
</script>
<form>
<div id="paypal-container"></div>
</form>
<script type="text/javascript">
braintree.setup(clientToken, "paypal", {
container: "paypal-container",
onPaymentMethodReceived: function (obj) {
window.location.href = 'http://localhost/braintree/checkout_paypal.php?nounce='+obj.nonce;
}
});
</script>
checkout_paypal.php
<?php
require("config.php");
$nonce = $_GET["nounce"];
$result = Braintree_Transaction::sale(array(
'amount' => '100.00',
'paymentMethodNonce' => $nonce,
'options' => array(
'submitForSettlement' => True
)
));
?>

Print with PHP into Javascript

Code for the analysis of the payment page but does not write the code in javascript codes..
For example (HTML Print):
<script>
woopra.track('Odeme Sayfasi', {
urunSayisi: '',
amount: '',
currency: '$'
});
</script>
21234.55
2: 2 pcs products
1234.55: amount
PHP & Javascript codes:
<?php
$mageFilename = '/home4/emre2010/public_html/app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$output = "";
foreach ($session->getQuote()->getAllItems() as $item) { ?>
<script>
woopra.track('Payment Page', {
urunSayisi: '<?php $output .= $item->getQty(); ?>',
amount: '<?php $output .= $item->getBaseCalculationPrice(); ?>',
currency: '$'
});
</script>
<?php } print $output; ?>
Why not write into the javascript code? - Where I make mistake?
P.S: E-commerce script: Magento1
You're mixing 2 approaches. When you close the PHP tags and start your JavaScript code, that's getting output directly into the page. Then you're storing information in a variable instead of outputting it directly into the content.
You need to do something like this:
<script>
woopra.track('Payment Page', {
urunSayisi: '<?php echo $item->GetQty(); ?>',
amount: '<?php echo $item->getBaseCalculationPrice(); ?>',
currency: '$'
});
</script>
If you want to build your JavaScript code and spit it out all in one go, then you'd need to put your JS code into a PHP variable and then print the output, like so:
<?php
$output = '';
$output .= "<script>";
$output .= " woopra.track('PaymentPage', {";
$output .= " urunSayisi: '" . $item->GetQty() . "',";
etc.
But the top approach of printing directly into your code is simpler and cleaner for what you seem to be doing.
You're not printing the values where you think you are, just concatenating them into $output. I'd do it like this:
<?php
$mageFilename = '/home4/emre2010/public_html/app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$output = "";
foreach ($session->getQuote()->getAllItems() as $item) {
$qty = $item->getQty();
$price = $item->getBaseCalculationPrice();
$output .= $qty . $price;
?>
<script>
woopra.track('Payment Page', {
urunSayisi: '<?php print $qty ?>',
amount: '<?php print $price ?>',
currency: '$'
});
</script>
<?php
}
print $output;
?>
You should echo or print
<script>
woopra.track('Payment Page', {
urunSayisi: '<?=$item->getQty()?>',
amount: '<?=$item->getBaseCalculationPrice()?>',
currency: '$'
});
</script>

Why does posting form with ajax plugin give result in console but not post the form to the server?

I am using a plugin to hijack a form and post it via an ajax function within the plugin. I can post the form and get a result in the console but I am unable to get the form to post and work properly.
My current build is using:
Laravel - PHP framework
Instagram PHP class - Interacting with the instagram api with php
Ajax plugin - To post forms without page refresh.
Currently I have got this for the ajax code(plugin):
Link here
And in my functions.js file I have got this code to post the form:
$(document).ready(function() {
$('.forms').each(function() {
$(this).formSubmit({
// Shows the formData that will be submitted; return false
// to prevent the form from being submitted
before: function(formData) {
if( console ) {
console.log('`before` callback:');
console.log(formData);
}
},
// Shows the AJAX response when the form is accepted
success: function(data) {
if( console ) {
console.log('`success` callback:');
console.log(data);
}
},
// Shows the AJAX response when the form is rejected
error: function(data) {
if( console ) {
console.log('`error` callback:');
console.log(data);
}
},
// Shows the AJAX error if one occurs
ajaxError: function(textStatus, errorThrown) {
if( console ) {
console.log('`ajaxError` callback:');
console.log(textStatus);
console.log(errorThrown);
}
},
// These add and remove a custom class called 'whoops' to the
// parent element of all invalid fields
showInvalid: function() {
$(this).parent().addClass('whoops');
},
hideInvalid: function() {
$(this).parent().removeClass('whoops');
}
});
});
});
Below is the markup for the form that wraps around the image so you can send a like/unlike through the instagram api from the form submit.
try {
$instagram = new Instagram\Instagram;
$instagram->setAccessToken($_SESSION['instagram_access_token']);
$token = $_SESSION['instagram_access_token'];
//$clientID = $_SESSION['client_id'];
$current_user = $instagram->getCurrentUser();
$tag = $instagram->getTag('folkclothing');
$media = $tag->getMedia(isset($_GET['max_tag_id']) ? array( 'max_tag_id' => $_GET['max_tag_id'] ) : null);
$liked_media = $current_user->getLikedMedia();
/* echo 'https://api.instagram.com/v1/media/'. $item->getId() .'/likes?access_token='.$token.''; */
if ( isset( $_POST['action'] ) ) {
echo '<br/>FORM IS SUBMITTED, INSPECT WHAT WAS SENT';
print_r($_POST);
$id = $_POST['id'];
switch( strtolower( $_POST['action'] ) ) {
case 'like':
$current_user->addLike( $id );
break;
case 'unlike':
$current_user->deleteLike( $id );
break;
}
}
} catch ( Exception $e ) {
// yes there is an error
$error = $e->getMessage();
}
echo '<section id="images">';
foreach ( $media as $item ) {
echo '<article class="instagram-image">';
echo '<form class="forms" action="'; echo URL::current(); echo '" method="post">';
$id = $item->getId();
echo '<a title="' . $item->getCaption() .'" class="fancybox" href="' . $item->link . '"><img alt="' . $item->getCaption() .'" src="' . $item->images->standard_resolution->url . '" /></a>';
echo '<div class="formSubmit-feedback"></div>';
echo '<img src="/public/img/377.gif" alt="loader"/>';
if ( $current_user->likes($item) ){
echo '<button class="ajax instabtn unlike icon-heart" type="submit" name="action" value="Unlike"></button>';
} else {
echo '<button class="ajax instabtn like icon-heart" type="submit" name="action" value="Like"></button>';
}
echo '<input type="hidden" name="id" value="'; echo $id; echo '">';
echo '<p>'; echo $item->likes->count; echo '</p>';
echo '</form>';
echo '</article>';
}
echo '</section>';
The errors I get when posting the form are below, it finds the right id of the object to post tobut it will not post to the server:
`before` callback: functions.js:51
Object {id: "509073517011482478_5670460"}
I know its close but I am unsure where to look with it.

How can I post data through a form with ajax and get it working? [duplicate]

This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed 9 years ago.
I have a piece of ajax script that is trying to post a form for me. Currently without ajax the form will post properly and it will send the data. What I want is an ajax post so it does not refresh the page and it posts the data too. There are multiple forms on one page.
My js script looks like this:
function post_form(action)
{
var token = $('.forms').attr('id');
var itemId = $('.forms').find('input.id').val();
var instaUrl = 'https://api.instagram.com/v1/media/'+itemId+'/likes?access_token='+token+'';
console.log(token);
console.log(itemId);
console.log(instaUrl);
var dataString = token;
$.ajax({
type: "POST",
url: instaUrl,
data: dataString,
crossDomain: true,
dataType: 'jsonp',
beforeSend: function()
{
$("#loading").fadeIn("slow");
if ( action == "like" )
{
$("#open"+comment_id).hide();
$("#loading_like_or_unlike"+comment_id).html('<img src="loader.gif" align="absmiddle" alt="Loading...">');
}
else if ( action == "unlike" )
{
$("#close"+comment_id).hide();
$("#loading_like_or_unlike"+comment_id).html('<img src="loader.gif" align="absmiddle" alt="Loading...">');
}
else {}
},
success: function(response)
{
if ( action == "like" )
{
$("#close"+comment_id).show();
}
else if ( action == "unlike" )
{
$("#open"+comment_id).show();
}
else {}
$("#loading").fadeOut("slow");
}
});
event.preventDefault();
}
$(document).ready(function() {
$('button.like').each(function() {
$(this).on('click', function(){
post_form();
});
});
});
Now in my markup I have a form that has an id in a hidden input value. The form once posted looks for the id and uses a case switcher with a like ans unlike switch. It uses the instagram php library to connect and get the data for the images as you will be able to see:
try {
$instagram = new Instagram\Instagram;
$instagram->setAccessToken($_SESSION['instagram_access_token']);
$token = $_SESSION['instagram_access_token'];
//$clientID = $_SESSION['client_id'];
$current_user = $instagram->getCurrentUser();
$tag = $instagram->getTag('folkclothing');
$media = $tag->getMedia(isset($_GET['max_tag_id']) ? array( 'max_tag_id' => $_GET['max_tag_id'] ) : null);
$liked_media = $current_user->getLikedMedia();
/* echo 'https://api.instagram.com/v1/media/'. $item->getId() .'/likes?access_token='.$token.''; */
if ( isset( $_POST['action'] ) ) {
echo '<br/>FORM IS SUBMITTED, INSPECT WHAT WAS SENT';
print_r($_POST);
$id = $_POST['id'];
switch( strtolower( $_POST['action'] ) ) {
case 'like':
$current_user->addLike( $id );
break;
case 'unlike':
$current_user->deleteLike( $id );
break;
}
}
} catch ( Exception $e ) {
// yes there is an error
$error = $e->getMessage();
}
// view rendering stuff
// display the error
if ( $error != '' )
{
echo "<h2>Error: ".$error."</h2>";
}
echo '<section id="images">';
foreach ( $media as $item ) {
echo '<article class="instagram-image">';
// define the form and set the action to POST to send the data to this script
echo '<form id="'. $token .'" class="forms" action="'; echo URL::current(); echo '" method="post">';
$id = $item->getId();
echo '<a title="' . $item->getCaption() .'" class="fancybox" href="' . $item->link . '"><img alt="' . $item->getCaption() .'" src="' . $item->images->standard_resolution->url . '" /></a>';
echo '<div class="formSubmit-feedback"></div>';
//echo '<img src="/public/img/377.gif" alt="loader"/>';
if ( $current_user->likes($item) ){
echo '<button class="ajax instabtn unlike icon-heart" type="submit" name="action" value="Unlike"></button>';
} else {
echo '<button class="ajax instabtn like icon-heart" type="submit" name="action" value="Like"></button>';
}
echo '<input class="id" type="hidden" name="id" value="'; echo $id; echo '">';
echo '<p>'; echo $item->likes->count; echo '</p>';
//echo '<p>'.$item->getId().'</p>';
//echo '<p>By: <em>' . $item->user->username . '</em> </p>';
//echo '<p>Date: ' . date('d M Y h:i:s', $item->created_time) . '</p>';
//echo '<p>$item->comments->count . ' comment(s). ' . $item->likes->count . ' likes. ';
echo '</form>';
echo '</article>';
}
echo '</section>';
The form works I know that for sure but I really need to know how I can get this to post to the right place and do the switch so it likes/unlikes the image.
Does anyone know a way around this at all?
Thanks
So the database changes happen properly but the page doesn't reflect the change properly?
I'm not sure if the ajax success has action in its scope...try echoing the action in the php script and using the ajax response var to control the images.

Categories