I want to check a php variable in javascript and create an Array accordingly.
I tried this, but it's not working:
<script language="Javascript" type="text/javascript">
var phpvar1_large = <?php echo $var1_large ?>;
var phpvar2_large = <?php echo $var2_large ?>;
var phpvar3_large = <?php echo $var3_large ?>;
var phpvar4_large = <?php echo $var4_large ?>;
if(!phpvar1_large){
var imgArray = new Array(
'<?=$main_img; ?>'
);
}else if(!phpvar2_large){
var imgArray = new Array(
'<?=$main_img; ?>',
'<?=$var1_large; ?>'
);
}else if(!phpvar3_large){
var imgArray = new Array(
'<?=$main_img; ?>',
'<?=$var1_large; ?>',
'<?=$var2_large; ?>',
'<?=$var3_large; ?>'
);
}else if(!phpvar4_large){
var imgArray = new Array(
'<?=$main_img; ?>',
'<?=$var1_large; ?>',
'<?=$var2_large; ?>',
'<?=$var3_large; ?>'
);
}else if(phpvar4_large){
var imgArray = new Array(
'<?=$main_img; ?>',
'<?=$var1_large; ?>',
'<?=$var2_large; ?>',
'<?=$var3_large; ?>',
'<?=$var4_large; ?>'
);
}
</script>
However, if I don't use an if-statement, the array is created correctly:
<script language="Javascript" type="text/javascript">
var imgArray = new Array(
'<?=$main_img; ?>',
'<?=$var1_large; ?>',
'<?=$var2_large; ?>',
'<?=$var3_large; ?>',
'<?=$var4_large; ?>'
);
</script>
I appreciate your help very much!
I strongly recommend simply JSON-encoding your array.
$imgArray = array('img1.jpg', 'img2.jpg', etc);
echo 'var imgArray = ' . json_encode($imgArray);
I'm pretty sure your problem is that the boolean values you are writing via php are not being interpreted as boolean but strings, that is why it is always evalued as false.
you should write var phpvar1_large = <?php echo json_encode($var1_large); ?>;
You are welcome!
Related
My problem is about events for calendar, precisely speaking i dont know how to dynamically add data for events here is my code in view file
<div>
<?php $message = Message::model()->findAll(); ?>
<?php foreach($message as $messag): ?>
<?php $names[] = $messag['contacts']; ?>
<?php $date[] = $messag['send_datetime']; ?>
<?php endforeach; ?>
</div>
<script>
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: [
{
title: '<?php echo $names[0]; ?>',
start: '<?php echo $date[0]; ?>',
url: 'view/1'
},
{
title: '<?php echo $names[1]; ?>',
start: '<?php echo $date[1]; ?>',
url: 'view/2'
},
{
title: '<?php echo $names[2]; ?>',
start: '<?php echo $date[2]; ?>',
url: 'view/3'
},
{
title: '<?php echo $names[3]; ?>',
start: '<?php echo $date[3]; ?>',
url: 'view/4'
},
]
})
$('#calendar').fullCalendar('changeView', 'agendaWeek');
});
</script>
<div id='calendar'>
</div>
i dont know how to code it in such a way that it will add as many events as i have data in database. i would be very grateful if someone could help
I would load the events by ajax. You basically have two parts. The one file with datatable/javascript and the other file is the data source. It is a php file that gets all the data from database and outputs the events in json format.
to get the events from a the file use fullCalendar like this (simplified version):
$('#calendar').fullCalendar({
events: {url: 'myevents.php'}});
and in your myevents.php you make the usual database requests and out put your data like this:
<?php
//Do the Database stuff here...
//Here is a sample data for two events:
$events = array();
$agenda['allDay'] = true;
$agenda['start'] = '2014-08-25 12:00:00';
$agenda['end'] = '2014-08-30 12:00:00';
$agenda['title'] = "Hello World";
$agenda['id']= "1";
$events[] = $agenda;
$agenda['allDay'] = false;
$agenda['start'] = '2014-08-27 12:00:00';
$agenda['end'] = '2014-08-27 16:30:00';
$agenda['title'] = "Blah";
$agenda['id']= "2";
$events[] = $agenda;
echo json_encode($events);
exit();
I am trying to assign a php echo value to an input generated from a jquery function. But so far no luck. It breaks the function and no results are displayed along with the input field. What is the proper way for this scenario to display php value inside the query function.
PHP
$tablename = "table";
$next_increment = 0;
//$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll(\PDO::FETCH_ASSOC);
foreach($results as $value){
$next_increment = $value['Auto_increment'];
}
var nextAutoIncrement = '"'<?php echo $next_increment; ?>'"';
Jquery
newSection.children(':nth-child(1)').children(':first').attr('id', 'auto_id_' + newNum).attr('name', 'auto_id_' + newNum).val(nextAutoIncrement).hide();
Try this
<script language="javascript" type="text/javascript">
var nextAutoIncrement = '<?php echo $next_increment;?>';
</script>
Try like this:
<script language="javascript" type="text/javascript"
var nextAutoIncrement = <?php echo $next_increment; ?>;
</script>
<script>
//if it is anumber
var nextAutoIncrement = <?php echo $next_increment; ?>;
// if ity is a string
var nextAutoIncrement = '<?php echo $next_increment;?>';
</script>
In JS code there is require to define the <script> tag:
$tablename = "table";
$next_increment = 0;
$qShowStatusResult = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll(\PDO::FETCH_ASSOC);
foreach($results as $value){
$next_increment = $value['Auto_increment'];
}
<script type="text/javascript" >
var nextAutoIncrement = '<?php echo $next_increment; ?>';
</script>
I just registered to ask for help with google maps. I'm working on a project that allows me to insert various ads of homes in the google map on my site. I do not know why that position is never correct, at first I tried using the code below ...
Then I had to delete the variables city, street, state, and zipcode why they went to war. But without resolving anything. So go to the link to better understand the situation. The generated code is in the script tag to the top of the map div.
LINK
<script>var defaultmapcenter = {mapcenter: "<?php echo $ct_options['ct_home_map_center']; ?>"}; google.maps.event.addDomListener(window, 'load', function(){ estateMapping.init_property_map(property_list, defaultmapcenter); });</script>
<script>
var property_list = [];
var default_mapcenter = [];
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); $count++; ?>
var property = {
thumb: "<?php ct_first_image_tn_map() ?>",
price: "<?php currency(); ?><?php map_pin_price(); ?>",
fullPrice: "<?php currency(); ?><?php listing_price(); ?>",
bed: "<?php beds(); ?>",
bath: "<?php baths(); ?>",
size: "<?php echo get_post_meta($post->ID, "_ct_sqft", true); ?> <?php sqftsqm(); ?>",
street: "<?php the_title(); ?>",
city: "<?php city(); ?>",
state: "<?php state(); ?>",
zip: "<?php zipcode(); ?>",
latlong: "<?php echo get_post_meta(get_the_ID(), "_ct_latlng", true); ?>",
permalink: "<?php the_permalink(); ?>",
agentThumb: "<?php echo get_template_directory_uri(); ?>/img_resize/timthumb.php?src=<?php the_author_meta('ct_profile_url'); ?>&w=40&zc=1'",
agentName: "<?php the_author_meta('first_name'); ?> <?php the_author_meta('last_name'); ?>",
agentTagline: "<?php if(get_the_author_meta('tagline')) { the_author_meta('tagline'); } ?>",
agentPhone: "<?php if(get_the_author_meta('office')) { the_author_meta('office'); } ?>",
agentEmail: "<?php if(get_the_author_meta('email')) { the_author_meta('email'); } ?>",
isHome: "<?php if(is_home()) { echo "false"; } else { echo "true"; } ?>",
commercial: "<?php if(has_type('commercial')) { echo 'commercial'; } ?>"
}
property_list.push(property);
<?php
endwhile; endif;
wp_reset_query();
?>
</script>
<script>var defaultmapcenter = {mapcenter: "<?php echo $ct_options['ct_map_center']; ?>"}; google.maps.event.addDomListener(window, 'load', function(){ estateMapping.init_property_map(property_list, defaultmapcenter); });</script>
**Javascript:**
---------------
var estateMapping = (function () {
var self = {},
marker_list = [],
open_info_window = null,
x_center_offset = 0, // x,y offset in px when map gets built with marker bounds
y_center_offset = -100,
x_info_offset = 0, // x,y offset in px when map pans to marker -- to accomodate infoBubble
y_info_offset = -100;
function build_marker(latlng, property) {
var marker = new MarkerWithLabel({
map: self.map,
draggable: false,
flat: true,
labelContent: property.price,
labelAnchor: new google.maps.Point(22, 0),
labelClass: "label", // the CSS class for the label
labelStyle: {opacity: 1},
icon: 'wp-content/themes/reale/images/blank.png',
position: latlng
});
self.bounds.extend(latlng);
self.map.fitBounds(self.bounds);
self.map.setCenter(convert_offset(self.bounds.getCenter(), x_center_offset, y_center_offset));
var infoBubble = new InfoBubble({
maxWidth: 275,
content: contentString,
borderRadius: 4,
disableAutoPan: true
});
var residentialString = '';
if(property['commercial'] != 'commercial') {
var residentialString='<p class="details">'+property.bed+' '+property.bath+'';
}
var contentString =
'<div class="info-content">'+
'<img class="left" src="'+property.thumb+'" />'+
'<div class="listing-details left">'+
'<h3>'+property.street+'</h3>'+
'<p class="location">'+property.city+', '+property.state+' '+property.zip+'</p>'+
'<p class="price"><strong>'+property.fullPrice+'</strong></p>'+residentialString+', '+property.size+'</p></div>'+
'</div>';
var tabContent =
'<div class="info-content">'+
'<img class="left" src="'+property.agentThumb+'" />'+
'<div class="listing-details left">'+
'<h3>'+property.agentName+'</h3>'+
'<p class="tagline">'+property.agentTagline+'</p>'+
'<p class="phone"><strong>Tel:</strong> '+property.agentPhone+'</p>'+
'<p class="email">'+property.agentEmail+'</p>'+
'</div>'+
'</div>';
infoBubble.addTab('Details', contentString);
infoBubble.addTab('Contact Agent', tabContent);
google.maps.event.addListener(marker, 'click', function() {
if(open_info_window) open_info_window.close();
if (!infoBubble.isOpen()) {
infoBubble.open(self.map, marker);
self.map.panTo(convert_offset(this.position, x_info_offset, y_info_offset));
open_info_window = infoBubble;
}
});
}
function geocode_and_place_marker(property) {
var geocoder = new google.maps.Geocoder();
var address = property.street+', '+property.city+' '+property.state+', '+property.zip;
//If latlong exists build the marker, otherwise geocode then build the marker
if (property['latlong']) {
var lat = parseFloat(property['latlong'].split(',')[0]),
lng = parseFloat(property['latlong'].split(',')[1]);
var latlng = new google.maps.LatLng(lat,lng);
build_marker(latlng, property);
} else {
geocoder.geocode({ address : address }, function( results, status ) {
if(status == google.maps.GeocoderStatus.OK) {
var latlng = results[0].geometry.location;
build_marker(latlng, property);
}
});
}
}
function init_canvas_projection() {
function CanvasProjectionOverlay() {}
CanvasProjectionOverlay.prototype = new google.maps.OverlayView();
CanvasProjectionOverlay.prototype.constructor = CanvasProjectionOverlay;
CanvasProjectionOverlay.prototype.onAdd = function(){};
CanvasProjectionOverlay.prototype.draw = function(){};
CanvasProjectionOverlay.prototype.onRemove = function(){};
self.canvasProjectionOverlay = new CanvasProjectionOverlay();
self.canvasProjectionOverlay.setMap(self.map);
}
function convert_offset(latlng, x_offset, y_offset) {
var proj = self.canvasProjectionOverlay.getProjection();
var point = proj.fromLatLngToContainerPixel(latlng);
point.x = point.x + x_offset;
point.y = point.y + y_offset;
return proj.fromContainerPixelToLatLng(point);
}
self.init_property_map = function (properties, defaultmapcenter) {
var options = {
zoom: 1,
center: new google.maps.LatLng(defaultmapcenter.mapcenter),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
streetViewControl: false
};
self.map = new google.maps.Map( document.getElementById( 'map' ), options );
self.bounds = new google.maps.LatLngBounds();
init_canvas_projection();
//wait for idle to give time to grab the projection (for calculating offset)
var idle_listener = google.maps.event.addListener(self.map, 'idle', function() {
for (i=0;i<properties.length;i++) {
geocode_and_place_marker(properties[i]);
}
google.maps.event.removeListener(idle_listener);
});
}
return self;
}());
I took a couple of property objects from your live site and simplified the code. This seems to position the markers correctly. There's too much code in your question to tell exactly where you went wrong, but if you start with this demo, you can add your functionality back slowly and see where it breaks.
Demo:
Output:
Script:
var property_list = [
{latlong: "36.738884,15.022705"},
{latlong: "42.608127,14.067408"}
],
options = {
zoom: 4,
center: new google.maps.LatLng( 36.73, 15.02 ),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(
document.getElementById( 'map-canvas' ),
options
);
for( var index = 0; index < property_list.length; index++ ) {
var latlong = property_list[index]['latlong'].split(','),
latlng = new google.maps.LatLng( latlong[0], latlong[1] ),
marker = new google.maps.Marker( {position: latlng, map: map} );
marker.setMap( map );
};
HTML:
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>
CSS:
#map-canvas {
height: 300px;
width: 500px;
}
There is nothing wrong with your markers and the javascript-code, all(except one) of the markers are placed at the correct position.
The issue is your content. You may have noticed that the shadow of the 265k-marker is much darker than the 1k-marker. It's because behind that marker are 8 other markers, 9 of your markers are defined with an equal LatLng.
Only 1 marker is not shown, it's the marker with an empty latlong. The geocoding fails here because of the missing properties street,city,state and zip.
replace this line
var address = property.street+', '+property.city+' '+property.state+', '+property.zip+', '+property.country;
with these lines to remove the fields with empty values
var city = (property.city.trim() != '')?property.city.trim()+',':'';
var state = (property.state.trim() != '')?property.state.trim()+',':'';
var country = (property.country.trim() != '')?property.country.trim():'';
var address = city+state+country;
I am trying to append new comment to the old comment box .
Here is my code , Dont know why its not working
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$(".bsubmit").click(function () {
var id = $(this).parent().parent().attr("id");
var comm = document.getElementById(id).getElementsByClassName("commentadd")[0].value;
$.ajax({
type: "POST",
url: "comment.php",
data: {
id: id,
comm: comm
},
cache: false,
success: function () {
$('.addcomment').slideUp('slow', function () {
// POSTED IN DATABASE SUCCESS NOW APPEND The comment with other COMMENTS
document.getElementById(id).getElementsByClassName(".itemcomment").append('<div class="comm">
<a href="profile.php?id=<?php echo $_SESSION['
fbid ']; ?> class="comm_img"><img src=" <?php echo $_SESSION['
smallest ']; ?> width="50" height="50" /></a>
<p width="50"><strong>
</strong></p>
</div>');
});
$('#load').fadeOut();
}
});
return false;
});
});
});
</script>
I think the error is in the code inside the "slideUp" callback, so I think the correct way to do it is:
Using regular JavaScript:
$('.addcomment').slideUp('slow', function () {
var elem = getElementById(id).getElementsByClassName(".itemcomment")[0],
div = document.createElement("div"),
a = document.createElement("a"),
p = document.createElement("p"),
img = document.createElement("img"),
strong = document.createElement("strong");
div.className = "comm";
a.className = "comm_img";
a.href = "profile.php?id=<?php echo $_SESSION['fbid ']; ?>";
img.src = "<?php echo $_SESSION['smallest ']; ?>";
img.width = "50";
img.height = "50";
p.width = "50";
p.appendChild(strong);
a.appendChild(img);
div.appendChild(a);
div.appendChild(p);
elem.appendChild(div);
});
Using JQuery:
$('.addcomment').slideUp('slow', function () {
var html = '<div class=comm>';
html += '<a href="profile.php?id=' + "<?php echo $_SESSION['fbid'];?>" + 'class=comm_img>';
html += '<img src="' + "<?php echo $_SESSION['smallest']; ?>" + 'width="50" height="50" /></a>';
html += '<p width="50"><strong></strong></p></div>';
$(".itemcomment", "#"+id).append(html);
});
Hope it helps!
I wrote a code using jQuery plugin fullcalendar, and everything worked just fine, until I send an $.ajax request in the eventClick.
I tried to alert something in the eventClick and it worked, but the ajax request just doesn't work.
js code:
!function($)
{
$(document).ready(function() {
$("#eventDialog").dialog({
autoOpen : false,
modal : true
});
var date = new Date();
var d = date.getDay();
var m = date.getMonth();
var y = date.getFullYear();
$("#calendar").fullCalendar({
theme : true,
header : {
left : 'next,prev today',
center : 'title',
right : 'month,agendaWeek,agendaDay'
},
editable : false,
events : [
<?php
while ($event = mysql_fetch_array($selectevents))
{
$startd = explode(".", $event['start']);
$endd = explode(".", $event['end']);
$starth = explode(":", $event['starth']);
$endh = explode(":", $event['endh']);
?>
{
id : <?php echo $event['id']; ?>,
title : '<?php echo stripslashes($event['title']); ?>',
<?php
if ($event['allday'] == 1)
{
?>
start : new Date(<?php echo $startd[2]; ?>,<?php echo $startd[1]-1; ?>,<?php echo $startd[0]; ?>),
end : new Date(<?php echo $endd[2]; ?>,<?php echo $endd[1]-1; ?>,<?php echo $endd[0]; ?>)
<?php
}
else
{
?>
start : new Date(<?php echo $startd[2]; ?>,<?php echo $startd[1]-1; ?>,<?php echo $startd[0]; ?>,<?php echo $starth[0]; ?>,<?php echo $starth[1]; ?>),
end : new Date(<?php echo $endd[2]; ?>,<?php echo $endd[1]-1; ?>,<?php echo $endd[0]; ?>,<?php echo $endh[0]; ?>,<?php echo $endh[1]; ?>),
allDay : false
<?php
}
?>
}
<?php
$evNum--;
if ($evNum > 0)
echo ",";
}
?>
],
eventClick : function(event) {
var eid = event.id;
$.ajax({
type : "GET",
url : "getEvent.php",
data : "id=" + eid,
succuss : function(msg) {
var title = $("event title", msg).text();
var description = $("event description", msg).text();
var start = $("event start", msg).text();
var end = $("event end", msg).text();
var starth = $("event starth", msg).text();
var endh = $("event endh", msg).text();
$("#eventDialog").attr("title", title);
$("#eventDialog #edDescription").html(title);
eventDialog.dialog("open");
}
});
}
});
});
}(jQuery);
getEvent.php
$id = htmlspecialchars(mysql_real_escape_string($_GET['id']));
$selectevent = mysql_query("SELECT * FROM `calendar` WHERE `id`='$id'") or die(mysql_error());
$event = mysql_fetch_array($selectevent);
header("Content-Type: text/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="utf-8" ?>';
echo "<event>";
echo "<id>".$event['id']."</id>";
echo "<title>".stripslashes($event['title'])."</title>";
echo "<description>".$event['description']."</description>";
echo "<start>".$event['start']."</start>";
echo "<end>".$event['end']."</end>";
echo "<starth>".$event['starth']."</starth>";
echo "<endh>".$event['endh']."</endh>";
echo "</event>";
Can anybody point out the problem?
Thank's!
succuss??, i guess is this your problem , it should be "success"
Change succuss to success in your code it must be a typo.
Since jQuery $.ajax did not find the success handler in its settings it didn't do anything.