I'm somewhat new to Javascript but know enough that I'm aware I shouldn't be writing my Javascript inline with my HTML but instead loading it from an external file. I've been trying to put it in an external file, but because of the way my code works I think it would be better to arrange it in functions that can be called at various points. What is the best practice for this?
At a guess, I'd say I should be wrapping all the JS in a singular file and then calling each code fragment with a function... but I'm not entirely sure how to do that and I'm not knowledgeable enough to know how to pose the question to look around online.
Here's a sample:
<html>
<script type="text/javascript"> <!--Create the arrays-->
var locationLat = new Array();
var locationLong = new Array();
var postURL = new Array();
var postExcerpt = new Array();
var postTitle = new Array();
var featImg = new Array();
var i = 0;
</script>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<script type="text/javascript"> <!--Load data from Wordpress into the arrays so we can use them on a map later-->
locationLat[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLat', true ) ?>";
locationLong[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLong', true ) ?>";
postURL[i] = "<?php echo get_permalink( $id );?>";
postExcerpt[i] = "<?php echo get_the_excerpt();?>";
postTitle[i] = "<?php echo get_the_title($ID);?>";
featImg[i] = "<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>"
i++;
</script>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
<script type="text/javascript">
function initialize() { <!--**I tried putting this function into an external JS file and calling it onLoad with body but it didn't do anythin**g-->
google.maps.visualRefresh = true;
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024,-95.712891),
disableDefaultUI: true,
};
var posts = locationLat.length;
var j = 0;
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var place = new Array();
while (posts != j)
{
var image = '<?php echo get_template_directory_uri(); ?>/location_marker.png';
var myLatLng = new google.maps.LatLng(locationLat[j],locationLong[j]);
place[j] = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
url: postURL[j],
excerpt: postExcerpt[j],
title: postTitle[j],
cover: featImg[j]
});
google.maps.event.addListener(place[j], 'click', function() {
map.panTo(this.getPosition());
map.setZoom(8);
$('#spantext').html(this.title);
$('#poste').html(this.excerpt);
$('.fillme').html('<img src="' + this.cover + '">');
$('.readmore').html('<p>Read more >');
$('.sidebar').show().stop().animate({
'width' : '400px',
'opacity' : '1'
}, 500);
});
j++;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
If I'm completely off track, some guidance would be good. Everything works in this format but I really don't think it's correct. I'm aware this is a relatively dumb question, but in lieu of finding a really good answer anywhere I thought it was worth asking.
I would suggest to put the different piceces of js into different files & add them with php.
But for that, first tailor the js to be independent chunks i.e one piece of js should not be accessing variables from another.
So it would look something like :
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<script type="text/javascript" src="myScript.js">
</script>
Contents of myScript.js
<!--Load data from Wordpress into the arrays so we can use them on a map later-->
locationLat[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLat', true ) ?>";
locationLong[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLong', true ) ?>";
postURL[i] = "<?php echo get_permalink( $id );?>";
postExcerpt[i] = "<?php echo get_the_excerpt();?>";
postTitle[i] = "<?php echo get_the_title($ID);?>";
featImg[i] = "<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>"
i++;
Related
So I have this code that loads php, when the page loads:
<script>
$(document).ready(function(){
$('#time').load('https://www.mywebsite.com/trigger.php');
});</script>
<div id="time"></div>
and I have trigger.php:
<?php
$parent_title = get_the_title( $post->post_parent );
$html_string = file_get_contents('https://mywebsite.com');
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html_string);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$values = array();
$row = $xpath->query('//*[#id="canvass-0-CanvassApplet"]/div/ul/li[2]/div/div[2]/div[1]');
foreach($row as $value) {
print($value->nodeValue);
}
?>
but it doesn't load.
I know I need to echo in the .php first.
So I have tried to echo $value; instead of print, but still nothing.
When I type something simple like <?php echo 'heyyy load me';> then it does work.
How do I echo my php code?
Need help, thanks.
I looked all over and even though there are tons of instructions and techniques and javascript code everywhere on how to do this, I can't use any of them, because it will require rewriting all my javascript and php. Is there code for info windows I can drop into this method i am using?
I am reading a csv file and parsing the data with this library (https://github.com/parsecsv/parsecsv-for-php), then I'm putting markers on the map with this icon library (https://github.com/scottdejonge/map-icons). now I need to add info window for each marker (where it displays the first column data of csv file) and I don't know how to go about it. I don't mean i don't know the php variable to use, that part is easy. what I mean is I don't know what infowindow javascript to use.
I am going to paste whole html page plus the contents of the csv file.
<?php
# include parseCSV class.
require_once('../parsecsv.lib.php');
# create new parseCSV object.
$csv = new parseCSV();
# Parse 'test.csv' using automatic delimiter detection...
$csv->auto('test.csv');
# ...or if you know the delimiter, set the delimiter character
# if its not the default comma...
// $csv->delimiter = "\t"; # tab delimited
# ...and then use the parse() function.
// $csv->parse('test.csv');
# Output result.
//echo "<pre>";
//print_r($csv->data);
//echo "</pre>";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Map Icons Example</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<!-- Google Maps -->
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<!-- Map Icons -->
<link rel="stylesheet" type="text/css" href="../dist/css/map-icons.css">
<script type="text/javascript" src="../dist/js/map-icons.js"></script>
<script type="text/javascript">
function initialise() {
var mapCanvas = document.getElementById('map-canvas');
// Center
var center = new google.maps.LatLng(-27.46834, 153.02365);
// Map Options
var mapOptions = {
zoom: 16,
center: center,
scrollwheel: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [
{stylers: [{ visibility: 'simplified' }]},
{elementType: 'labels', stylers: [{ visibility: 'off' }]}
]
};
// Create the Map
map = new google.maps.Map(mapCanvas, mapOptions);
<?php
$i=1;
$extendthis = "";
foreach ($csv->data as $key => $row):
// We define our address
$fulladdress = $row['address'].",".$row['city'].",".$row['state'].",".$row['zip'];
$marker = $row['marker'];
$icon = $row['icon'];
$fillcolor = $row['fillcolor'];
//if no marker or icon or fillcolor is set, use default ones...
if ($marker=="") {
$marker = "MAP_PIN";
}
if ($icon=="") {
$icon = "";
}
if ($fillcolor=="") {
$fillcolor = "6331AE";
}
// We get the JSON results from this request
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($fulladdress).'');
// We convert the JSON to an array
$geo = json_decode($geo, true);
// If everything is cool
if ($geo['status'] = 'OK') {
// We set our values
$latitude = $geo['results'][0]['geometry']['location']['lat'];
$longitude = $geo['results'][0]['geometry']['location']['lng'];
}
echo "var Item_".$i." = new google.maps.LatLng(".$latitude.", ".$longitude.");\n";
echo "var marker1 = new Marker({\n";
echo "map: map,\n";
echo "title: 'Uluru (Ayers Rock)',\n";
echo "position: Item_".$i.",\n";
echo "icon: {\n";
echo "path: ".$marker.",\n";
echo "fillColor: '#".$fillcolor."',\n";
echo "fillOpacity: 1,\n";
echo "strokeColor: '',\n";
echo "strokeWeight: 0\n";
echo "},\n";
echo "map_icon_label: '<span class=\"map-icon ".$icon."\"></span>'\n";
echo "});\n";
$extendthis .= "bounds.extend(Item_".$i.");\n";
$i++;
endforeach;
?>
var bounds = new google.maps.LatLngBounds();
<?php echo $extendthis; ?>
map.fitBounds(bounds);
};
google.maps.event.addDomListener(window, 'load', initialise);
</script>
<style media="screen">
html, body {
padding:0;
margin:0;
width:100%;
height:100%;
}
#map-canvas {
padding:0;
margin: 0;
width: 50%;
height: 50%;
}
table { background-color: #BBB; }
th { background-color: #EEE; }
td { background-color: #FFF; }
</style>
</head>
<body>
<table border="0" cellspacing="1" cellpadding="3">
<tr>
<?php foreach ($csv->titles as $value): ?>
<th><?php echo $value; ?></th>
<?php endforeach; ?>
</tr>
<?php foreach ($csv->data as $key => $row): ?>
<tr>
<?php foreach ($row as $value): ?>
<td><?php echo $value; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
<div id="map-canvas"></div>
</body>
</html>
test.csv:
name,address,city,state,zip,marker,icon,fillcolor
one,7505 3rd Street,Schenectady,NY,12302,,,
two,6422 Route 29,Bear,DE,19701,MAP_PIN,,00CCBB
three,2858 Lakeview Drive,Venice,FL,34293,,,
four,335 Lincoln Street,Augusta,GA,30906,,,
five,3907 Cardinal Drive,San Antonio,TX,78213,SQUARE_PIN,,00CCBB
six,8560 State Street,Drexel Hill,PA,19026,,,
Updated version, but still not working:
<script type="text/javascript">
var iw;
function initialise() {
var mapCanvas = document.getElementById('map-canvas');
// Center
var center = new google.maps.LatLng(-27.46834, 153.02365);
// Map Options
var mapOptions = {
zoom: 16,
center: center,
scrollwheel: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [
{stylers: [{ visibility: 'simplified' }]},
{elementType: 'labels', stylers: [{ visibility: 'off' }]}
]
};
// Create the Map
map = new google.maps.Map(mapCanvas, mapOptions);
iw = new google.maps.InfoWindow();
<?php
$i=1;
$extendthis = "";
foreach ($csv->data as $key => $row):
$name = $row['name'];
// We define our address
$fulladdress = $row['address'].",".$row['city'].",".$row['state'].",".$row['zip'];
$marker = $row['marker'];
$icon = $row['icon'];
$fillcolor = $row['fillcolor'];
//if no marker or icon or fillcolor is set, use default ones...
if ($marker=="") {
$marker = "MAP_PIN";
}
if ($icon=="") {
$icon = "";
}
if ($fillcolor=="") {
$fillcolor = "6331AE";
}
// We get the JSON results from this request
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($fulladdress).'');
// We convert the JSON to an array
$geo = json_decode($geo, true);
// If everything is cool
if ($geo['status'] = 'OK') {
// We set our values
$latitude = $geo['results'][0]['geometry']['location']['lat'];
$longitude = $geo['results'][0]['geometry']['location']['lng'];
}
echo "var Item_".$i." = new google.maps.LatLng(".$latitude.", ".$longitude.");\n";
echo "var marker".$i." = new Marker({\n";
echo "map: map,\n";
//echo "title: 'your title here',\n";
echo "content: '".$name."',\n";
echo "position: Item_".$i.",\n";
echo "icon: {\n";
echo "path: ".$marker.",\n";
echo "fillColor: '#".$fillcolor."',\n";
echo "fillOpacity: 1,\n";
echo "strokeColor: '',\n";
echo "strokeWeight: 0\n";
echo "},\n";
echo "map_icon_label: '<span class=\"map-icon ".$icon."\"></span>'\n";
echo "});\n";
echo "marker".$i.".addListener('click',function(m) { iw.setContent(m.content);iw.open(map,m); });\n";
$extendthis .= "bounds.extend(Item_".$i.");\n";
$i++;
endforeach;
?>
var bounds = new google.maps.LatLngBounds();
<?php echo $extendthis; ?>
map.fitBounds(bounds);
};
google.maps.event.addDomListener(window, 'load', initialise);
</script>
You can solve this with just one infowindow:
Define a global variable to store the infowindow. In order to be used by the click event, it should be global. To do so, define it outside the function:
<script type="text/javascript">
var iw;
function initialise() {
...
And then instantiate a new infowindow in the initialise function:
function initialise() {
iw=new google.maps.InfoWindow();
...
You can add custom properties to the markers. Say, for example, "content" and set the content for the marker's infowindow there:
echo "var marker$i = new Marker({content:'content for current marker here',\n";
...
Then add a click event to the marker:
echo "marker$i.addListener('click',function(e) { iw.setContent(this.content);iw.open(map,this); });";
I am currently having trouble with this. I would like to make one of my variables in Javascript have a PHP value. Here is what I mean:
<script>
JSvariable = <?php echo $PHPvariable; ?>;
</script>
For some reason that is not working. Here is my full (snippet) of code:
<script>
currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
I am sure it is some stupid mistake, but I can not seem to find it! What is the problem? Thank you!
PS #parentcommentholder is an input field, and it just had the value 0 after the field is supposed to of been changed.
Here is some source:
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<script>
var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
<input id="parentcommentholder"></div>
Don't forgot for give quotes ' or ". Use following:
<script>
var JSvariable = '<?php echo $PHPvariable; ?>';
//or
var JSvariable = "<?php echo $PHPvariable; ?>";
</script>
Reason: If php variable contains string and if while assigning it to javascript variable we shall not give quote like:
<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = String;//which will give error in javascript
But this will work fine if PHP variable contains a numeric value like:
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = 2;//which will work perfect
Complete code should be:
<script>
var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
//or if you are sure your variable contains int value
var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
$('#parentcommentholder').val(currentreplyid);
</script>
Try the below instead of using javascript (as I don't think you need it):
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>
If your defiantly sure $allpostcomments[$key]['replyid'] is bringing back a value, this should work without any issues.
Just want to pass php variables $x and $y to javascript map function (as lat and long). Please help.
Here is my controller:
<?php
$x = 25.114667;
$y = 55.137797;
?>
Here is my JS file:
function initialize()
{
var myCenter = new google.maps.LatLng(lat,long);
var mapOptions = {
center:myCenter,
zoom:12,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
,mapOptions);
} google.maps.event.addDomListener(document.getElementById('showhidemap'), 'click', initialize);
you are passing string in you js variable lat and long. assign value directly as float
try this
var lat = <?php echo $x; ?>;
var long = <?php echo $y; ?>;
also must include the script with google map key on above of google map initialization.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=GOOGLE_MAP_KEY&sensor=true"> </script>
GOOGLE MAP KEY : must be generate for your site.
see some urls might help you
https://developers.google.com/maps/tutorials/fundamentals/adding-a-google-map
https://developers.google.com/maps/signup?csw=1
https://developers.google.com/maps/documentation/javascript/tutorial
did you try to add
$x = 25.114667;
$y = 55.137797;
to some tag like
<div data-lat="<?php echo $y; ?>" data-long="<?php echo $y; ?>" id="showhidemap">show map</div>
You need to create a Javascript object in your .php file, just before your include your javascript file (the one containing the above fragment), which will be filled by your longitude/latitude information.
Like this:
YOUR PHP FILE
<html>
...
<script type="text/javascript">
var mapLangLat = {
long:<?php echo $x; ?>,
lati:<?php echo $y; ?>
};
</script>
<script src="my_remote_script.js"></script>
...
YOUR JAVASCRIPT FILE
<script>
function initialize()
{
var lat = window.mapLangLat.lati;
var long = window.mapLangLat.long;
...
It's required to find the PHP part above to be able to code that little javascript object.
I have a JavaScript in the view but it's not executing again after loading different content with AJAX, so I want to place it in the <head> of the view to be isolated from AJAX without having to put it in a file because it's using PHP arrays from the controller. How do I do it? Is there a way to write JavaScript code the CakePHP way and set it as inline false the same way as JavaScript files?
It seems like even JavaScript codes places in head will not execute with AJAX so how should I do it? Should I place JavaScript related divs outside the content div or what?
This is my view:
<script>
var geocoder, lat, lng;
function initialize() {
var location = <?php echo "\"" . $location . "\""?>;
location = location.replace(/\+/g, ' ');
document.getElementById("address").innerHTML = location + " Weather";
var latlng = new google.maps.LatLng(<?php echo $loc['lat'];?>, <?php echo $loc['lng'];?>);
var mapOptions = {
zoom: 12,
center: latlng,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
draggable: false,
scrollwheel: false,
disableDoubleClickZoom: true,
zoomControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
<?php $i = 0 ?>
<?php foreach ($posts as $post): ?>
var markerLatlng = new google.maps.LatLng(<?php echo h($post['Post']['latitude']); ?>, <?php echo h($post['Post']['longitude']); ?>);
var marker = new google.maps.Marker({
position: markerLatlng,
map: map,
title: '<?php echo h($post['Post']['temperature']); ?>',
icon: 'http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.6|0|FF0000|12|_|<?php echo h($post['Post']['temperature']); ?>',
url: '<?php echo $this->Html->url(array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>'
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
<?php endforeach; ?>
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyBoEBzeiYi-bCaTIlcK7lrNKUyvUfLQqGM&sensor=false&callback=initialize®ion=LB";
document.body.appendChild(script);
}
$(document).ready(function(){
$(".post .toggle").toggle(function(){
$(".post .toggle").css('background-image','url(../../img/down.png)');
$(this).css('background-image','url(../../img/up.png)');
$(".post .description").hide();
$(this).parent().find(".description").show("slow");
$(".post").height(100);
$(this).parent().height(200);},
function() {$(".post .toggle").css('background-image','url(../../img/down.png)');$(".post").height(100);$(".post .description").hide();$(this).css('background-image','url(../../img/down.png)');
});
});
window.onload = loadScript;
</script>
<div id="weather">
<center><div id="address"> </div>
<p><div id="coords"><?php echo $loc['lat'] . ", " . $loc['lng'];?></div></p></center>
<div id="weather-menu">
<?php echo $this->Html->link('Today', 'today/' . $location);?>
<?php echo $this->Html->link('Yesterday', 'yesterday/' . $location);?>
<?php echo $this->Html->link('Custom', 'custom/' . $location);?>
<?php echo $this->Html->link('All', 'all/' . $location);?>
</div>
<div id="post-container">
<?php /*
if ($posts) {
echo "<div id=\"post\"><div id=\"temperature\">";
echo $posts[0]['Post']['temperature'] . "°C</div>";
if ($posts[0]['Humidity']['humidity'])
echo "<div id=\"humidity\">" . $posts[0]['Humidity']['humidity'] . "%</div>";
echo "<div id=\"created\">" . $this->Time->niceShort($posts[0]['Post']['created']) . " </div>";
echo "<div id=\"username\">" . $posts[0]['User']['username'] . "</div>";
echo "<div id=\"condition\">";
if (strtotime($posts[0]['Post']['created']) > date_sunrise(strtotime($posts[0] ['Post']['created']), SUNFUNCS_RET_TIMESTAMP, $posts[0]['Post']['latitude'], $posts[0] ['Post']['longitude'],90, 2) && strtotime($posts[0]['Post']['created']) < date_sunset(strtotime($posts[0]['Post']['created']), SUNFUNCS_RET_TIMESTAMP, $posts[0]['Post']['latitude'], $posts[0]['Post']['longitude'],90, 2))
echo $this->Html->image('/img/weather-icons/' . $posts[0]['Post']['condition'] . 'A.png');
else
echo $this->Html->image('/img/weather-icons/' . $posts[0]['Post']['condition'] . 'B.png');
echo "</div></div>";
}*/
?>
<?php
//$posts = $this->requestAction('/weather/fetch');
foreach (array_slice($posts, 0) as $post) {
echo "<div class=\"post\"><div class=\"temperature\">";
echo $this->Html->link($post['Post']['temperature'] . "°C", array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])) . "</div>";
if ($post['Humidity']['humidity'])
echo "<div class=\"humidity\">" . $post['Humidity']['humidity'] . "%</div>";
echo "<div class=\"created\">" . $this->Time->niceShort($post['Post']['created']) . "</div>";
echo "<div class=\"username\">" . $this->Html->link($post['User']['username'], array('controller' => 'users', 'action' => 'view', $post['Post']['user_id'])) . "</div>";
echo "<div class=\"condition\">";
if (strtotime($post['Post']['created']) > date_sunrise(strtotime($post['Post']
['created']), SUNFUNCS_RET_TIMESTAMP, $post['Post']['latitude'], $post['Post']['longitude'],90, 2) && strtotime($post['Post']['created']) < date_sunset(strtotime($post['Post']['created']), SUNFUNCS_RET_TIMESTAMP, $post['Post']['latitude'], $post['Post']['longitude'],90, 2))
echo $this->Html->image('/img/weather-icons/' . $post['Post']['condition'] . 'A.png');
else
echo $this->Html->image('/img/weather-icons/' . $post['Post']['condition'] . 'B.png');
echo "</div>";
echo "<div class=\"description\">" . $post['Description']['description'] . "</div>";
echo "<div class=\"toggle\"></div>";
echo "</div>";
}
?>
</div>
<div id="side-container">
<div id="map_canvas"></div>
<br/>
<div id ="current"><?php if (isset($w_temp)) echo "Current Temperature: " . $w_temp . "°C" . $this->Html->image('/img/wg.png');?></div>
</div>
<?php
$this->Paginator->options(array(
'update' => '#content',
'before' => $this->Js->get('#busy-indicator')->effect('fadeIn', array('buffer' => false)),
'complete' => $this->Js->get('#busy-indicator')->effect('fadeOut', array('buffer' => false))
));
echo $this->Paginator->prev('« Previous ', null, null, array('class' => 'disabled'));
echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled'));
echo $this->Js->writeBuffer();
?>
<div id="busy-indicator"></div>
</div>
and this is my controller index action:
public function index($date, $location = null) {
$this->set('location', $location);
$address = urlencode($location);
$loc = $this->getLocation($address);
$this->set('loc', $loc);
$this->loadModel('Post');
if ($date == 'all') {
$this->paginate = array('conditions' => array(
'latitude BETWEEN ? AND ?' => array(
$loc['lat'] - 0.05, $loc['lat'] + 0.05),
'longitude BETWEEN ? AND ?' => array(
$loc['lng'] - 0.05, $loc['lng'] + 0.05)
),
'order' => array('Post.created' => 'desc'),
'limit' => '5');
$this->set('posts', $this->paginate('Post'));
}
else if ($date == 'today') {
$this->set('posts', $this->Post->find('all', array(
'conditions' => array(
'latitude BETWEEN ? AND ?' => array(
$loc['lat'] - 0.05, $loc['lat'] + 0.05),
'longitude BETWEEN ? AND ?' => array(
$loc['lng'] - 0.05, $loc['lng'] + 0.05),
'Post.created >' => date('Y-m-d H:i:s', strtotime("-1 day"))
),
'order' => array('Post.created' => 'desc'))));
}
else if ($date == 'yesterday') {
$this->set('posts', $this->Post->find('all', array(
'conditions' => array(
'latitude BETWEEN ? AND ?' => array(
$loc['lat'] - 0.05, $loc['lat'] + 0.05),
'longitude BETWEEN ? AND ?' => array(
$loc['lng'] - 0.05, $loc['lng'] + 0.05),
'Post.created >' => date('Y-m-d H:i:s', strtotime("-2 day")),
'Post.created <' => date('Y-m-d H:i:s', strtotime("-1 day"))
),
'order' => array('Post.created' => 'desc'))));
}
$this->wunder($location);
}
Thank you guys. I just needed to add this to my javascript code:
var pathname = window.location.pathname;
window.onload = loadScript;
$(document).ready(function() {
$.ajax({
url: pathname,
success: function(){
loadScript();
}
})
});
You wrote:
I have a JavaScript in the view but it's not executing again after
loading different content with AJAX
I only briefly looked at what you are doing but I didn't immediately see where you are making an AJAX request. Clarifying that point would be helpful, as others have noted. However, be aware that After loading new content with AJAX if your script had event handlers on any replaced content then you will need to destroy and recreate the event handlers in Javascript (even if you replaced it with identical DOM elements).
To this point:
Is there a way to write JavaScript code the CakePHP way and set it as
inline false the same way as JavaScript files?
So you do this essentially the same way as you reference external source files in cakePHP, you can replace:
<script>
...
</script>
with the following:
$this->Html->ScriptBlock('your javascript here', array('inline'=>false));
Then in the section make sure you have (for cakePHP 2.1 or newer):
echo $this->fetch('script');
or (for cakePHP 2.0x or earlier)
$scripts_for_layout();
Since you're using "AJAX" to inject a script into a page i suppose, the way you are doing it is by using jQuery maybe or anything pulling your content into the DOM via element.innerHTML = content, am I wrong ?
BUT scripts passed in element.innerHTML will not execute, and this is what jQuery use to fragment your HTML response !
The best way to do it IMHO is to use "AJAX" only to get the data from your CakePHP app to the javascript front end (with a JSON response), then you will use this data within your javascript code to display your charts. It would be much more efficient, and you would not have the issues shoesole is talking about loosing DOM elements references.
Or you can do this the lazy way, with this hack :
<img style="display:none" src="data:image/png,script" onerror="
console.log('Hey I am javascript code running as long as javascript isnt disabled!');
"/>
<script>
// this is new invention like JSON it seem cute function but it is not
function connect_php() {
jQuery(document).ready(function($){
setTimeout(function() {
$("#final_result").css('display', 'block');
}, 4000); //here 1000 means 1 second
});
}
jQuery(document).ready(function($){
(function a(x) {
// The following condition
// is the base case.
if ( ! x) {
return;
}
a(--x);
event.preventDefault();
$( "#aform" ).submit();
connect_php();
})(10);
});
</script>
if you have php for loop doing something must wait this will fired after php finish or your loop finish send message from php to JavaScript defined in JS from start