I am trying to pass revenue data to AdWords from Magento by adding some PHP code to the site, then implementing the tracking with an echo to carry the variable over to the Javascript.
Here is what I have:
<?php
$orderId = Mage::getSingleton('checkout/session')->getLastOrderId();
$order = Mage::getModel('sales/order')->load($orderId);
$total = (float)number_format($order()->getSubtotal(),2);
?>
Then after this, I am using a PHP echo to take the $total into the Google conversion tracking code like this:
<!-- Google Code for Website Conversions Conversion Page --> <script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 1011076746;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "3B7tCPfZj2YQip2P4gM";
if (<?php echo $total?>) {
var google_conversion_value = <?php echo $total?>;
}
var google_conversion_currency = "USD";
var google_remarketing_only = false;
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt=""
src="//www.googleadservices.com/pagead/conversion/1011076746/?value=<?php echo $total?>¤cy_code=USD&label=3B7tCPfZj2YQip2P4gM&guid=ON&script=0"/>
</div>
</noscript>
But no luck.
It returns a Function name must be a string error on line 69. Line 69 is the 4th line down in my code, as far as I know. I had to remove it per the client's request.
Can anyone help please? I am not experienced enough with PHP to really diagnose this one.
Problem : You are using $variable as a function myFunction() in your code which is wrong.
Note : Variables & Functions are two different main elements of every programming language so it's better to at least differentiate between these two and never mistake taking one for another.!
Solution : Remove the Parentheses () after $order in your following code and your problem will be solved.!
CODE :
<?php
$orderId = Mage::getSingleton('checkout/session')->getLastOrderId();
$order = Mage::getModel('sales/order')->load($orderId);
$total = (float)number_format($order->getSubtotal(),2);
?>
#Actual Credit Goes To #Felippe Duarte
EXTRA LESSON :
A Variable can hold a function i.e You can assign a function to a variable and then later you can call that function just right away using the variable.
For Instance :
//It's A Function
function myFunction() {
// Simple Printing The Hello World Text
echo "Hello World";
}
// Assigning The Function To The Variable
$variable = 'myFunction';
//Calling The Variable As A Function
echo $variable();
Related
I have having big issues with the execution order of my code.
HTML sample:
<div id="toast-container" class="toast-top-right"><div id="toast-type" class="toast" aria-live="assertive" style=""><div id="snackbar">message</div></div></div>
.
.<!--Somewhere more down the line-->
.
.
<div class="col_half col_last">
<label for="job-ctc-frm-heard-about">How did you find out about us?</label>
<input type="text" id="job-ctc-frm-heard-about" name="job-ctc-frm-heard-about" value="<?php echo $discovered;?>" class="sm-form-control" />
</div>
Javascript function:
<script>
function Toast(message, messagetype)
{
var cont = document.getElementById("toast-container");
cont.classList.add("show");
var type = document.getElementById("toast-type");
type.className += " " + messagetype;
var x = document.getElementById("snackbar");
x.innerHTML = message;
setTimeout(function(){ cont.classList.remove("show")}, 3000);
}
</script>
PHP sample:
<?php
$discovered ="";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$message = 'Let the games begin';
echo "<script type='text/javascript'>Toast('$message', '$Success');</script>";
$discovered = test_input( $_POST["job-ctc-frm-heard-about"] );
......
?>
Now heres my problem. My php uses a function Toast. My function Toast accesses the HTML div toast-container to set a message. The other div uses the php variable $discovered to remember the entered value on a failed form submit. If i position the JS anywhere before the DOM then var cont will be null so it has to be below.
However if I position the code order as PHP -> HTML -> JS then the function is undefined in PHP so it has to be after JS. But if i position it as HTML -> JS -> PHP then the variable $discovered won't be displayed in the HTML. The orders are conflicting with one another. Is there any work around for this?
The simplest would be to just move the relevant parts to where you need them. You need $discovered to be available throughout your file (when PHP is executed server-side) and you need it to echo the script specifically after your Toast-declaration:
<?php
$discovered ="";
if($_SERVER["REQUEST_METHOD"]=="POST") {
$message = 'Let the games begin';
$discovered = test_input( $_POST["job-ctc-frm-heard-about"] );
// ...
}
?>
<!-- HTML referencing $discovered here -->
<script>
function Toast(message, messagetype)
{
var cont = document.getElementById("toast-container");
cont.classList.add("show");
var type = document.getElementById("toast-type");
type.className += " " + messagetype;
var x = document.getElementById("snackbar");
x.innerHTML = message;
setTimeout(function(){ cont.classList.remove("show")}, 3000);
}
</script>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST") {
echo "<script type='text/javascript'>Toast('$message', '$Success');</script>";
}
?>
If you want to control these things from client-side, you can json_encode your PHP objects, meaning they will be sent in plain-text as if you had hard-coded them into the file. As #FZs mentions, PHP runs on the server and "prepares" the file by executing all <?php ... ?> blocks. When the result reaches the browser, it contains the resulting text and not PHP (browsers don't understand PHP).
Hello I am trying to utilize geomapping within in my website and I'm having trouble dynamically pulling the address for a restaurant and putting it into my javascript. I am using the get method to pull the restaurant_id from the url and then use this to pull the restaurant's complete address. This is the line of code I am having trouble with (var destinationAddress):
$con=mysqli_connect("root","");
$rest_id2=$_GET['id'];
$rest_id=(int)$rest_id2;
$sql="SELECT * from restaurant WHERE restaurant_id='".$rest_id."'";
$result=mysqli_query($con,$sql);
$rows=mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script>
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
</script>
</head>
....
Any one know see what I am doing wrong here?
Make your life easier: build the destination address outside of the template:
$rows=mysqli_fetch_assoc($result);
if( $rows !== NULL )
{
$destinationAddress = "{$rows['address']}, {$rows['city']}, {$rows['state']}, {$rows['zip']}";
}
else
{
// no rows! (anomaly)
$destinationAddress = "no destination address available";
}
// due to the way you'll later inject the variable
// into JavaScript code double quotes must be escaped
$destinationAddress = str_replace( '"', '\"', $destinationAddress );
Then simply
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?=$destionationAddress?>";
} );
Try adding the commas and spaces.
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
becase u forgot to close the function }) , try
<script>
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
})
</script>
I need to put a Javascript variable into php variable, I dont know how to do that. Possible answers are appreciatable.
<script type="text/javascript">
$(document).ready(function(){
$('#number_of_inwards,#number_of_outwards').each(function(){
var product_name,total_stock;
$('#product_name').change(function(){
product_id = $('#product_name').val();
});
var hello = "13";
<?php $d = '<script>hello</script>' ?>
total_stock = <?php echo $st[$d]; ?>;
console.log(total_stock);
$(this).focusout(function(){
var inward = parseInt($('#number_of_inwards').val());
var outward = parseInt($('#number_of_outwards').val());
$('#overall_stock').val(parseInt(inward+outward));
console.log("Inside the Loop"+ inward + outward);
})
})
});
</script>
Here from the code.I added dummy variable
hello="13"
And tried to get it into php variable but It won't work, It returns empty value.
Thanks in advance
With scandinavian letters and when encoding them, I have a problem. With code below, javascript add some extra encoding to variable
<script>
function doit(params) {
var url = "/linkto/code.php" + params;
window.open(url,"Doit","width=750, height=600");
}
</script>
<?php
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
echo 'Do it!'; // link to page
?>
When changing code above to php, changed does not happened and problem go away.
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
// link to page
echo '<a href="/linkto/code.php"'.$param.'>Do it!</a>';
Hi all again,
I cannot make it work, no difference between utf-8 or iso-8859-1.
Result is something else, when using javascript-function or direct link.
You can try it here:
http://www.ajl.fi/tmp/test.php
Here is codes:
test.php:
<script type="text/javascript">
function doIt(params) {
var url = "doit.php" + params;
window.open(url,"doit");
}
</script>
<?php
$var1 = 'pähkinä';
$var1 = urlencode($var1);
echo sprintf("Do it - call",$var1)."<br>";
echo sprintf("Do it - link",$var1);
?>
and here is doit.php:
<?php
var_dump($_GET);
?>
In ist code, you have two issues in this code
1) Short tag will not work inside the <?php ?> here:
echo 'Do it!'; // link to page
2) You forgot to add quotes here:
window.open(url,"Doit",width=750, height=600"); //missing quote here
Modified Code:
<?php
$var1 = 'p%E4hkin%E4';
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
?>
Do it!
<script type="text/javascript">
function doit(params) {
var url = "/linkto/code.php" + params;
console.log(url);
window.open(url,"Doit","width=750, height=600");
}
</script>
I answer to myself - Solved.
IE, Edge and Chrome, all working ok on both cases. Firefox has a problem. When using
Do it!
result is not correct, but when using
Do it!
seems to work on all browsers
I am unable to show php variable in javascript;
this is my code here:
<script type="text/javascript">
$(document).ready(function (){
var n=<?php echo json_encode($count)?>;
for(var i=0;i<n;i++){
var div = document.createElement('div');
div.className = "d5";
div.id=i+1;
document.getElementById('wrapper').appendChild(div);
<?php
$query="select * from shop_product where shop_uniqueid='$unq'";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
$product=$row["in_product"];
?>
var product=<?php echo $product?>;
$('#'+div.id).html(product);
<?php
}
?>
}//for loop ends
});//ready ends
</script>
here i am trying to pass var product in html() of which value is coming from php like: var product=<?php echo $product?>;
but when doing so php value is not coming in Javascript's var product.
when I pass $('#'+div.id).html("abcd"); abcd value is showing in divs.
please help me.
Compare the first place you take data from PHP and put it in JavaScript:
var n=<?php echo json_encode($count)?>;
with your attempt to assign the product value:
var product=<?php echo $product?>;
You haven't converted the data from plain text to JavaScript in the second line. Use json_encode there too.