How to pass json_encoded variables from .php to external .js? - javascript

that's my first post :)
I have a problem with passing json_encoded variables from PHP VIEW file to an external JS. I am using FuelPHP. The following is part of the VIEW:
1. These are the PHP variables:
<?php
$sensor_id_num = $sensor->id_num;
$sensor_name = $sensor->name;
$sensor_unit = $sensor->unit;
$sensor_lati = $sensor->lati;
$sensor_longi = $sensor->longi;
?>
2. Here the variables are json_encoded and their value is given to JS vars:
<script src="<?php echo Asset::get_file('mapmarkers.js','js') ?>" type="text/javascript">
var sensor_id_num = <?php echo json_encode($sensor_id_num); ?>;
var sensor_name = <?php echo json_encode($sensor_name); ?>;
var sensor_unit = <?php echo json_encode($sensor_unit); ?>;
var sensor_lati = <?php echo json_encode($sensor_lati); ?>;
var sensor_longi = <?php echo json_encode($sensor_longi); ?>;
</script>
3. The above mentioned mapmarkers.js is the external JS that I want to pass the vars to. In that JS I am using google.maps javascript API to draw a map and one marker for each map. Every marker is representing a sensor's location, so that's why I'm passing latitude and longitude. That should be part of the php VIEW. That View shows some sensor's text info along with the map.
4. So the text info and the map are visualized, but not the markers. The problem is in the JS file. When I try to use the vars from tag into the JS, the browser console shows their value is 'undefined'. I'm accessing the vars with 'window.name_of_var'. Even when I access them without 'window.' their value is not shown, "Uncaught ReferenceError: sensor_lati is not defined" is shown instead. That's part of the JS:
var myLatLng = new google.maps.LatLng(window.sensor_lati,window.sensor_longi);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: window.sensor_name,
html: window.sensor_name
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(html);
infowindow.open(map, marker);
});
Does anybody has an idea where could the problem be? I don't have much experience with FuelPHP and JavaScript. Any help would be appreciated ;)

You cannot have a <script> element with a src attribute and javascript code within it. Well, you can, but it's pretty much undefined what browsers do with that so your results will vary from browser to browser.
The solution would be to first define the variables, then include the remote script:
<script type="text/javascript">
var sensor_id_num = <?php echo json_encode($sensor_id_num); ?>;
var sensor_name = <?php echo json_encode($sensor_name); ?>;
var sensor_unit = <?php echo json_encode($sensor_unit); ?>;
var sensor_lati = <?php echo json_encode($sensor_lati); ?>;
var sensor_longi = <?php echo json_encode($sensor_longi); ?>;
</script>
<script src="<?php echo Asset::get_file('mapmarkers.js','js') ?>" type="text/javascript"></script>

Set the variables before calling the external js file
<script type="text/javascript">
var sensor_id_num = <?php echo json_encode($sensor_id_num); ?>;
var sensor_name = <?php echo json_encode($sensor_name); ?>;
var sensor_unit = <?php echo json_encode($sensor_unit); ?>;
var sensor_lati = <?php echo json_encode($sensor_lati); ?>;
var sensor_longi = <?php echo json_encode($sensor_longi); ?>;
</script>
<script src="<?php echo Asset::get_file('mapmarkers.js','js') ?>" type="text/javascript">

You should divide your <script /> into 2 parts.
Probably you don't need json_encode php function here. Also add wrapping doublequotes.
mapmarkers.js must be added after defining your variables
<script type="text/javascript">
window.sensor_id_num = "<?php echo $sensor_id_num; ?>";
window.sensor_name = "<?php echo $sensor_name; ?>";
window.sensor_unit = "<?php echo $sensor_unit; ?>";
window.sensor_lati = "<?php echo $sensor_lati; ?>";
window.sensor_longi = "<?php echo $sensor_longi; ?>";
</script>
<script src="<?php echo Asset::get_file('mapmarkers.js','js') ?>" type="text/javascript" />

Related

Unable to print PHP variable using JS

I understand that this question has been asked a lot of of times, but the solutions posted there don't seem to work for me. I have a code as follows:
<script>
var JSvar = "<?php echo $phpVar ?>";
document.write(JSvar);
</script>
<?php
$phpVar="jajha";
?>
I actually want to pass a PHP variable to a JS function, but I wanted to try if printing the variable works first. Please help me out.
instead of
<script>
var JSvar = "<?php echo $phpVar ?>";
document.write(JSvar);
</script>
<?php
$phpVar="jajha";
?>
try
<?php
$phpVar="jajha";
?>
<script>
var JSvar = "<?php echo $phpVar ?>";
document.write(JSvar);
</script>

How to pass PHP (index.php file ) Variable value to external JAVASCRIPT .js File?

Actually this code is wrote in index.php file but now i want to pass this javascript array value to external js file.
<?PHP
$qry2 = mysql_query("SELECT table_no FROM table_info");
while($res2 = mysql_fetch_array($qry2))
{
static $i = 0;
$i++;
$reg_table[$i] = $res2['table_no'];
}
?>
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
I want the bookedSeats variable to be in the external table.js file.
You have jQuery tag in there, so I am going to give you this... use Ajax:
test.php
<?php
// Handle Ajax Request
if (isset($_GET['loadData']))
{
// Query your db here, im building dummy data
$results = array();
for ($i = 0; $i < 10; $i++) {
$results[] = 'Data '. $i;
}
// Return Data
exit(json_encode($results));
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// Load Data Via Ajax
$.getJSON("test.php?loadData", function(bookedSeats)
{
console.log(bookedSeats);
});
</script>
When the page loads, we get the result like this:
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
This can be greatly simplified and made immune to XSS:
<script>
var bookedSeats = <?php echo json_encode(array_values($reg_table)); ?>;
</script>
You can now refer to bookedSeats in your external .js file, but only if that file is being run after this inline script has been placed. In other words, putting:
<script src="external.js"></script>
after the <script>...<?php ... ?>...</script> is okay, but putting it before is only okay if you are deferring its execution - it's just safer to put it after ;)
I have an alternative solution for you eventually even if Latheesan Kanes's one is right.
Mine is just given as a trivial exemple if you have access to a constructor in your Javascript object in the table.js file.
<script>
var bookedSeats = new Array();
person=new Object();
<?php foreach($reg_table as $key => $val)
{
// here a javascript object
?>
person.firstname="John"; // of course replace firstname and John by your informations
<?php }?>
// then call table.js constructor
var objectInTableDotJS = new YourConstructor(person); // now in table.js you need to make modification :)

Javascript updating variable

I have used some javascript with some php. The jquery changes a php variable like it should... i echoed the new php variable and it shows, however my javascript variables don't change
<?php
$image ='<div id="myid"></div>';
?>
<script type="text/javascript" src="storescripts/jquery-1.10.2.min.js"></script>
<script>
var my_pic = new Image();
my_pic.src = '<?php echo $image; ?>';
</script>
<script language="JavaScript" type="text/javascript">
function swapContent(cv){
$("#myDiv").html("animated gif").show();
var url ="myphpscript2.php";
var id = <?php echo $id; ?>;
$.post(url,{contentVar: cv, id: id,},function(data){
$("#myDiv").html(data).show();
});
}
</script>
These are the scripts used. I have no idea why just before the php variable will change but the other will just stay as ''

Run PHP echoed Javascript

I am just getting into the world of PHP, Javascript and HTML and would like some help from the community regarding the following code. Basically I want to pass variables plucked from a ODBC_connection by PHP into textboxes. Lines 1-3 were for me to test to get the box to update which it does but anything echoed by PHP does not run. I am completely new to this so I realize I must be missing something trivial.
I welcome any suggestions or comments about what I can do to fix this or what I can do better in general.
Thank you.
<script type='text/javascript'>
document.getElementById('modeltxt').value = "test2";
</script>
<?php
echo "<script type='text/javascript'>";
echo "document.getElementById('modeltxt').value =\"TEST3\";";
echo "document.getElementById('customertxt').value = $customer;";
echo "document.getElementById('endusertxt').value = $enduser;";
echo "document.getElementById(dongletxt').value = $dongle;";
echo "document.getElementById('shipdatetxt').value = $shipdate;";
echo "document.getElementById('chasistypetxt').value = $chasistype;";
echo "document.getElementById('chasisnumbertxt').value = $chasisnumber;";
echo "document.getElementById('opsystxt').value = $opsys;";
echo "document.getElementById('dvd1txt').value = $dvd1;";
echo "document.getElementById('dvd2txt').value = $dvd2;";
echo "document.getElementById('storagetxt').value = $storage;";
echo "document.getElementById('nodrivetxt').value = $nodrive;";
echo "document.getElementById('drivesizetxt').value = $drivesize;";
echo "document.getElementById('interface1txt').value = $interface1;";
echo "document.getElementById('interface2txt').value = $interface2;";
echo "document.getElementById('interface3txt').value = $interface3;";
echo "document.getElementById('interface4txt').value = $interface4;";
echo "document.getElementById('interface5txt').value = $interface5;";
echo "document.getElementById('interface6txt').value = $interface6;";
echo "document.getElementById('commentstxt').value = $comments;";
echo "document.getElementById('warrantyexptxt').value = $warrantyexp;";
echo "document.getElementById('extendedwarrantytxt').value = $extwarexp;";
echo "document.getElementById('onsitetxt').value = $onsite;";
echo "document.getElementById('sqlversiontxt').value = $sqlversion;";
echo "<\script>";
You can create dynamics JS using the below
Define Content-Type on the top of your .js.php file:
<?
header('Content-Type: application/javascript');
// Write your php code
?>
and call the js file like this ..
<script type="application/javascript" src="JS_PATH/name-of-file.js.php"></script>
and if you want to use inline php values, you can write like this
<script type="application/javascript">
document.getElementById('modeltxt').value = "<?php echo $dummy_value ?>";
</script>
No need to do this. You can simply use javascript inside php as below :-
As you mention in your question
Basically I want to pass variables plucked from a ODBC_connection by PHP into textboxes.
<?php
// Php block of code
?>
<script type="text/javscript">
document.getElementById('modeltxt').value = "TEST3";
document.getElementById('customertxt').value = "<?php echo $customer;?>";
......
....
...
</script>
<?php
// Another block of code
?>

What is this Javascript Syntax Error

I have this code which sends a variable to JS from a PHP file.
<script type="text/javascript">
var pids = new Array(<?php echo implode(', ', $pids); ?>);
var permalink = "My name is <?php the_permalink(); ?>";
</script>
For reasons beyond my comprehension, when take away "My name is", it's a syntax error.
<script type="text/javascript">
var pids = new Array(<?php echo implode(', ', $pids); ?>);
var permalink = "<?php the_permalink(); ?>";
</script>
There is no output, the script dies on.
[Syntax Error]
= new Array(67, 68, 69, 70, 71,
The first code was working, now has spontaneously stopped, despite no changes. Now, neither works.
I discovered the problem is the preceding code:
When the less-than sign is changed to less-than-or-equal to, there is a javascript syntax error. Somehow this must break the array or the implode function
$pids = array();
$i=0;
$result = count($wpdb->last_result);
while($i < $result) {
$pids[] = $wpdb->last_result[$i]->pid;
$i++;
}
?>
<script type="text/javascript">
var pids = new Array(<?php echo implode(', ', $pids); ?>);
var permalink = "My name is <?php the_permalink(); ?>";
</script>
try it:
var permalink = "My name is '<?php the_permalink(); ?>'";
Try this :
var permalink = "My name is " + <?php the_permalink(); ?>;
you probably have ' or " inside one of the php output functions, try to escape them.
this could happened also if one of your pids is a wrong type and implode fails to finish.

Categories