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>
Related
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.
I've been trying to figure out how to make a dataLayer for the Order Confirmation page (Thankyou.php). I wanted to add the following function (via functions.php or Code Snippet) but it gives a fatal error when I try. Can anyone see what I'm doing wrong or if there is a better way to do this?
I'm fairly new but trying to learn and I've been researching but can't find the answer, sorry if this may be a novice question. It gives a fatal error for the < in script so I thought maybe I wasn't supposed to have in PHP but when I remove that then I get a fatal error for unexpected { on same line:
add_action( 'woocommerce_thankyou', 'checkout_datalayer' );
function checkout_datalayer( $order_id ) {
<script>
dataLayer.push({
'ecommerce': {
'currencyCode': '<?php echo $order->get_order_currency(); ?>',
'purchase': {
'actionField':{
'id': '<?php echo $order->get_order_number(); ?>',
'affiliation': 'Website',
'revenue': <?php echo number_format($order->get_total(), 2, ".", ""); ?>,
'shipping': <?php echo number_format($order->calculate_shipping(), 2, ".", ""); ?>,
<?php if($order->get_used_coupons()): ?>
'coupon': '<?php echo implode("-", $order->get_used_coupons()); ?>'
<?php endif; ?>
},
'products': [
<?php
foreach($order->get_items() as $key => $item):
$product = $order->get_product_from_item( $item );
?>
{
'name': '<?php echo $item['name']; ?>',
'id': '<?php echo $product->get_sku(); ?>',
'price': '<?php echo number_format($order->get_line_subtotal($item), 2, ".", ""); ?>',
'brand': 'Brand',
'quantity': <?php echo $item['qty']; ?>
},
<?php endforeach; ?>
]
}
}
});
</script>
}
To anyone interested, I figured out the issue I believe. It was assuming the entire thing was PHP and the only way to stop that was to add ?> before the <script> and <?php after the </script>.
I am developing a website using php & MySQL, i have two functions
1. Grab data from database,
2. display HTML view codes with a link to view individual product details using $_GET variable.
Everything works perfectly. But i want the product details to load without the page being refreshed. I understand Ajax is capable in handling the task but i am not knowledgeable in Ajax. Any assistance would be appreciated.
Below are my codes example:
//Main product view
function product_view($product) {
$output = "";
$output = $output . '<li class="col-sx-12 col-sm-3">';
$output = $output . '<div class="product-container">';
$output = $output . ' product name';
$output = $output . '----';
$output = $output . '----';
$output = $output . '----';
$output = $output . '</div>';
$output = $output . '</li>';
return $output;
}
//Main product display
function get_products() {
require(ROOT_PATH ."inc/db_connect.php");
$sql = "SELECT * FROM products WHERE status='Active'";
$query = mysqli_query($db_connect, $sql);
return $query;
}
//View page
$products = get_products();
if (!empty($products)) {
foreach ($products as $product) {
echo product_view($product);
}
}
To use AJAX as suggested in some comments of your question, you can use this sample code in your client side:
$(document).ready(function(){
$.ajax({
url: 'products.php',
method: 'GET'
}).then(function(data){
for(int i=0; i < data.length; i++){
$('body').append('<li class="col-sx-12 col-sm-3"><div class="product-container>...'+data[i].attribute+'</div></li>');
//append all information that you need
}
})
});
at your backend you need to return the JSON so:
$products = get_products();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($products);
This question may be asked numerous times but I am facing difficulty in doing so.
var_dump($lex_post_data); works fine on controller
My Controller code
try{
// need for the manage functionality to be initialized.
$manage_mode = FALSE;
$appointment = array();
$provider = array();
$customer = array();
$lex_post_data = $this->input->post('lexname');
var_dump($lex_post_data);
// Load the book appointment view.
$view = array (
'available_services' => $available_services,
'available_providers' => $available_providers,
'company_name' => $company_name,
'manage_mode' => $manage_mode,
'appointment_data' => $appointment,
'provider_data' => $provider,
'customer_data' => $customer,
'post_data' => $lex_post_data
);
} catch(Exception $exc) {
$view['exceptions'][] = $exc;
}
$this->load->view('appointments/book', $view);
View Code:
<script type="text/javascript">
var GlobalVariables = {
availableServices : <?php echo json_encode($available_services); ?>,
availableProviders : <?php echo json_encode($available_providers); ?>,
baseUrl : <?php echo '"' . $this->config->item('base_url') . '"'; ?>,
manageMode : <?php echo ($manage_mode) ? 'true' : 'false'; ?>,
appointmentData : <?php echo json_encode($appointment_data); ?>,
providerData : <?php echo json_encode($provider_data); ?>,
customerData : <?php echo json_encode($customer_data); ?>,
lexpostData : <?php echo json_encode($lex_post_data); ?>,
csrfToken : <?php echo json_encode($this->security->get_csrf_hash()); ?>
};
console.log(GlobalVariables);
var EALang = <?php echo json_encode($this->lang->language); ?>;
var availableLanguages = <?php echo json_encode($this->config->item('available_languages')); ?>;
$(document).ready(function() {
FrontendBook.initialize(true, GlobalVariables.manageMode);
// GeneralFunctions.centerElementOnPage($('#book-appointment-wizard'));
GeneralFunctions.enableLanguageSelection($('#select-language'));
});
</script>
Ques1: Is this the correct way of accessing the values sent from controller.
Ques2: On console.log(GlobalVariables); I am getting
lexpostData : null
What I am doing wrong.
Please guide
EDIT
SOLVED & CLOSED: I was trying to get differnt name varriable on view. Had to use
lexpostData : <?php echo json_encode($post_data); ?>,
instead of
lexpostData : <?php echo json_encode($lex_post_data); ?>,
In controller you are passing $lex_post_data in post_data
'post_data' => $lex_post_data
So in view instead of
<?php echo json_encode($lex_post_data); ?>
Use
<?php echo json_encode($post_data); ?>
the below function is my controller code which is called by an ajax request:
function search_featured_candidates() {
$skills = $this->input->post('skills');
$this->load->model('Featured_candidate', 'featured', TRUE);
$result = $this->featured->get_featured_candidates_by_skills($skills);
if ($result) {
$str = "";
foreach ($result as $row) {
$str .= "Name: " . $row->candidate_name . "<br/>";
$str .= "Exp: " . $row->experience . "<br/>";
$str .= "Skills: " . $row->skills . "<hr/>";
}
$html = $str;
echo json_encode(array('html' => $html, 'success' => TRUE));
} else {
$html = 'No Candidates Found!';
echo json_encode(array('html' => $html, 'success' => FALSE));
}
}
my view code:
<script>
$(function() {
$("#featured_candidates").on("change paste keyup", function() {
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>mypage/search_featured_candidates/",
data: {skills: $(this).val()},
dataType: "json",
success: function(data) {
if (data.success === true) {
$("#featured").html(data.html);
} else {
$("#featured").html(data.html);
}
}
});
});
});
</script>
<div class="panel-body">
<div>
<input type="text" style="width: 100%"
name="featured_candidates" id="featured_candidates"
placeholder="keyword / skills" title="Featured Candidates"
/>
<br/><hr/>
</div>
<div id="featured">
<?php
foreach ($result as $row) {
echo "Name: " . $row->candidate_name . "<br/>";
echo "Exp: " . $row->experience . "<br/>";
echo "Skills: " . $row->skills . "<hr/>";
}
?>
</div>
</div>
now i am trying to display the result array using ajax like i have displayed in my view code using foreach. so to display it using ajax i have concatenated the array in my controller method in $str but it is not working while when i updated my controller method to this:
function search_featured_candidates() {
$skills = $this->input->post('skills');
$html = $skills ;
echo json_encode(array('html' => $html, 'success' => TRUE));
}
it is working fine..any help or suggesttion would be a great help...thanks in advance..
You have a mistake here
foreach ($result as $row) {
echo "Name: " . $row->candidate_name . <br/>";
echo "Exp: " . $row->experience . "<br/>";
echo "Skills: " . $row->skills . "<hr/>";
}
You forgot the "
. $row->candidate_name . "<br/>";
// ^ You forgot the "
The formulation of your question makes it difficult to know where your problem really is. But from a quick look you normally have to set proper headers in order to output json formatted data with PHP.
Try adding this before you do your echo, maybe this solves your problem:
header('Content-Type: application/json');