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>
Related
I have this below code in a file named test.php, whose task is to create a JSON object and transfer it to a function in JS.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if($row) {
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
$encodedJSON = json_encode($myJSON); //final variable in PHP to pass to below function.
//JS begins here
echo <<<JS001
<script type="text/javascript">
var msg = {$encodedJSON};
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');'
}
}
};
ThunkableWebviewerExtension.postMessage(msg);
alert(msg);
</script>
JS001;
} else {
echo 'Incorrect ID';
}
?>
</body>
</html>
I have this piece of script, but I can only write it inside PHP - because the value the function requires, is stored in a PHP variable. All it should do is fetch the PHP's encodedJSON variable's value and store it in a local JS variable msg. Then, I created a function whose task is to POST a message, and called it next. All this worked perfectly when run in a separate HTML file, in which JS was written individually.
What should I do, to make the JS piece of code run inside PHP code? Thanks!
Given that $myjson contains the json string in php, then
var msg = {$myJSON};
to understand better above code is equivalent to:
var msg = JSON.parse('{$myJSON}')
is the way to convert it to js object from php variable.
Please see comments in the code for further help.
Please run below code and see how console.log is printing the json object:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
//started with hard coded data to show a working copy paste example
$row = array('date'=>'09-Oct-2020','txnid'=>1234,'atomid'=>456,'amount'=>21345);
if($row) {
$obj = new stdclass(); //op should add this to avoid warning
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
//to see the json encode value in php
//var_dump($myJSON);
//this is not needed in op code
//$encodedJSON = json_encode($myJSON); //final variable in PHP to pass to below function.
//JS begins here
echo <<<JS001
<script type="text/javascript">
//php json string is converted to js object here
var msg = {$myJSON};
//see msg object printed in console
console.log(msg);
</script>
JS001;
} else {
echo 'Incorrect ID';
}
?>
</body>
</html>
I want to make something like this in order to deliver a JSON:
<?php
header("Content-Type:application/json");
require "data.php";
if(!empty($_GET['name']))
{
$name=$_GET['name'];
$price =$_GET['value'];
if(empty($price))
{
response(200,"Product Not Found",NULL);
}
else
{
response(200,"Product Found",$price);
}
}
else
{
response(400,"Invalid Request",NULL);
}
function response($status,$status_message,$data)
{
header("HTTP/1.1 ".$status_message);
$response['status']=$status;
$response['status_message']=$status_message;
$response['data']=$data;
$json_response = json_encode($response);
echo $json_response;
}
The "value" on the data.php file is found by a JavaScript like this:
<script src='/web3.min.js'></script>
<script type='text/javascript'>
var web3 = new Web3(new Web3.providers.HttpProvider('https://example.com'));
var value = web3.xxx.getValue('xxxx');
</script>
But I don't know how to pass it from the JavaScript variable to the $price variable in this php file... could you help me?
As Andrew suggests in his comment, you can use Ajax to get the data from your PHP-Script:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <!-- add jQuery for easy AJAX functions -->
<script src='/web3.min.js'></script>
<script type='text/javascript'>
var web3 = new Web3(new Web3.providers.HttpProvider('https://example.com'));
var value = web3.xxx.getValue('xxxx');
$.get("/path/to/file.php?name=&value="+value, funtion(data) { // get data from PHP-Script
data = JSON.parse(data);
if (data.status_message === "Product Found") // if a product was found, set "price" to the price
var price = data.data
});
</script>
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();
Framework: CodeIgniter 2.0
I am trying access session data setup in model from view.
This is the code I am testing in view:
<script type='text/javascript'>
function notEmpty(elem, helperMsg){
var num_records = '$this->session->userdata("number_Of_Records_session")';
alert(num_records);
if(elem.value.length > 0){
alert(helperMsg);
elem.focus();
return false;
}else{
window.location="/path/";
}
return true;
}
</script>
When I use PHP code I could retrieve the value from session and display it.
<?php
$numberOfRecords_session =
$this->session->userdata('number_Of_Records_session');
echo "Num records:".$numberOfRecords_session;
?>
But in javascript this line
var num_records = '$this->session->userdata("number_Of_Records_session")';
print this message in alert box:
$this->session->userdata("number_Of_Records_session")
Any advice to retrieve value in javascript and show it alert box is appreciate.
You cannot access your session (stored on server) from JavaScript (executed on client)
So you have to declare a JavaScript variable and define it with PHP
Like this you're defining a string:
...
<script>
var sessionValue = "<?php echo $this->session->userdata('number_Of_Records_session');?>";
</script>
...
If you're sure that there is always a number you could remove the " above, which are defining the variable as string.
If you're not sure about the datatype of the sessionValue you should use parseInt(string,radix):
...
<script>
var sessionValue = parseInt("<?php echo $this->session->userdata('number_Of_Records_session');?>");
if(sessionValue == "NaN") sessionValue = 0;
</script>
...
I am trying use an array created in PHP in my external javaScript. I have PHP code that puts images from the directory depending on the userid given via url, into an array and I want to be able to use this array in javaScript so that I can create a photo slideshow and have the images change depending on the userid. I think this is achievable as I have researched online, but somehow it just doesn't work for me. I am not sure what I am doing wrong.
In the head of my html, I have this code to add in my external javaScript and to declare the variable/array in Javascript. Not sure if it's right, I got it off here from one of the solutions:
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">var userphoto = "<?= $galleryarray ?>";</script>
<script type="text/javascript">var userid = "<?= $user_id ?>";</script>
<script src="javascript.js"></script>
Here is my PHP code inside my basic HTML:
And here is my external JavaScript code:
$ (document).ready(function(){
var photodisplay =
[
$("#photo1"),
$("#photo2"),
$("#photo3"),
$("#photo4"),
$("#photo5"),
];
var userid = "<?php echo json_encode($user_id); ?>"; // getting php variable
var userphoto = "<?php echo json_encode(galleryarray); ?>";
// List of images for user one
/*var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";*/
//preloading photos
function preloadingPhotos() {
for (var x=0; x<5; x++)
{
photodisplay[x].attr("src", "Photos/" + userid + "/" + userphoto[x]);
photodisplay[x].hide();
console.log("preloaded photos");
}
displayPhoto();
}
function displayPhoto(){
photodisplay[0].fadeIn(3000);
photodisplay[0].delay(3000).fadeOut(3000, function() { //first callback func
photodisplay[1].fadeIn(3000);
photodisplay[1].delay(3000).fadeOut(3000, function() { //second callback func
photodisplay[2].fadeIn(3000);
photodisplay[2].delay(3000).fadeOut(3000, function() { //third callback func
photodisplay[3].fadeIn(3000);
photodisplay[3].delay(3000).fadeOut(3000, function() { // fourth callback func
photodisplay[4].fadeIn(3000);
photodisplay[4].delay(3000).fadeOut(3000, function() {
setTimeout(displayPhoto(), 3000);
});
});
});
});
});
}// end of function displayPhoto
window.onload = preloadingPhotos;
}); //end ready
PHP:
Have your PHP define the variable(s) inside of a <script> tag like this...
<script>
var userid = "<?php echo json_encode($user_id); ?>";
var userphoto = "<?php echo json_encode(galleryarray); ?>";
</script>
Your following external javascript files will then be able to use the userid and userphoto variables, even though they weren't defined directly in the external file
In the below code userphoto & userid are now javascript variables.
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">var userphoto = "<?= $galleryarray ?>";</script>
<script type="text/javascript">var userid = "<?= $user_id ?>";</script>
<script src="javascript.js"></script>
Php code will not be executed in external javascript file. so when below lines are executed
userid will be a string with "< ? php echo json_encode($user_id); ? > " as its value and similarly for userphoto.
var userid = "<?php echo json_encode($user_id); ?>"; // getting php variable
var userphoto = "<?php echo json_encode(galleryarray); ?>";
Modify your basic HTML to
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">var userphoto = <?php echo json_encode(galleryarray); ?>; </script>
<script type="text/javascript">var userid = <?php echo json_encode($user_id); ?>;</script>
<script src="javascript.js"></script>
and you can use these variables in external javascript file provided it is loaded after these variables are assigned. So you need not assign these variables in external javascript again.
Simply rename your file named javascript.js to javascript.php and change your script tag to <script src="javascript.php"></script>
Update
You also can use .htaccess to keep your javascript.js as it is in the script tag by doing something like the following in your .htaccess file:
RewriteRule ^javascript\.js$ javascript.php
For more details about using .htaccess in such case, checkout the
following question's answer:
Parsing PNG as PHP via htaccess works only on local server but not on webserver