How to get php echo data in jquery. i want dataDAY1 in jquery. i am using on progress bar. i use php and sql. i nedd total var total_goals and var goals_completed data from database
<div id="dataDAY1"><?php echo $row["ipoSize"]; ?></div>
<script>
$(document).ready(function(){
var total_goals = document.getElementById("dataDAY1")
// var total_goals = '$json_array';
var goals_completed = 3000;
var bar = new ProgressBar.Circle('#container', {
color: '#00b819',
strokeWidth: 4,
trailWidth: 4,
easing: 'easeInOut',
duration: 1400,
text: {
autoStyleContainer: false
},
from: { color: '#cecece', width: 4 },
to: { color: '#00b819', width: 4 },
step: function(state, circle) {
circle.path.setAttribute('stroke', state.color);
circle.path.setAttribute('stroke-width', state.width);
var value = Math.round(circle.value() * 100);
if (value === 0) {
circle.setText('');
} else {
circle.setText(value);
}
}
});
bar.text.style.fontFamily = '"Raleway", Helvetica, sans-serif';
bar.text.style.fontSize = '2rem';
bar.animate(goals_completed/total_goals); // Number from 0.0 to 1.0
});
</script>
try this...
for JQuery: var total_goals = $("dataDAY1").html();
for Javascript: var total_goals = document.getElementById("dataDAY1").innerHTML;
snippet:
var total_goals = $('#dataDAY1').html();
console.log(total_goals);
var total_goals_js = document.getElementById('dataDAY2').innerHTML;
console.log(total_goals_js);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dataDAY1">Your Data From Php Variable</div>
<div id="dataDAY2">Your Data From Php Variable 2</div>
Try this:-
var total_goals= <?php echo json_encode($json_array); ?>;
console.log(total_goals);
You can use php in javascript. See below code
<script>
var total_goals = "<?php echo $row['ipoSize']; ?>";
</script>
Related
im trying to do the following with my current script:
Saving Google Geo Location Informations in File, when the Visitor clicks "Accept Detection of my location"
Output Google Maps URL with the Information
<!DOCTYPE html>
<html>
<head>
<style>
#tripmeter {
border: 0px double black;
padding: 0px;
margin: 0px 0;
}
p {
color: #222;
font: 14px Arial;
}
span {
color: #00C;
}
</style>
</head>
<body>
<div id="tripmeter">
<p>
Starting Location (lat, lon):<br/>
<span id="startLat">???</span>°, <span id="startLon">???</span>°
</p>
<p>
Current Location (lat, lon):<br/>
<span id="currentLat">???</span>°, <span id="currentLon">???</span>°
</p>
<p>
Distance from starting location:<br/>
<span id="distance">0</span> km
</p>
</div>
<script>
window.onload = function() {
var startPos;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
document.getElementById("startLat").innerHTML = startPos.coords.latitude;
document.getElementById("startLon").innerHTML = startPos.coords.longitude;
}, function(error) {
alert("Error occurred. Error code: " + error.code);
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from locaton provider)
// 3: timed out
});
navigator.geolocation.watchPosition(function(position) {
document.getElementById("currentLat").innerHTML = position.coords.latitude;
document.getElementById("currentLon").innerHTML = position.coords.longitude;
document.getElementById("distance").innerHTML =
calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
position.coords.latitude, position.coords.longitude);
});
}
};
// Reused code - copyright Moveable Type Scripts - retrieved May 4, 2010.
// http://www.movable-type.co.uk/scripts/latlong.html
// Under Creative Commons License http://creativecommons.org/licenses/by/3.0/
function calculateDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
</script>
</body>
</html>
<meta charset="utf-8"/>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
</head>
<body>
<div id="pos" style="width:800px; height:600px;">
Detection Location..
</div>
<script>
function initialize(coords) {
var latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("pos"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "You"
});
}
navigator.geolocation.getCurrentPosition(function(position){
initialize(position.coords);
}, function(){
document.getElementById('pos').innerHTML = 'Failed to detect Location.';
});
</script>
<?php
$dns = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$ip = $_SERVER['REMOTE_ADDR'];
$rand2 = time();
$port= htmlspecialchars(
$_SERVER['REMOTE_PORT']);
$browser= htmlspecialchars(
$_SERVER['HTTP_USER_AGENT']);
$ausgabe="• I WANT TO SAVE THE GOOGLE MAPS URL WITH THE DETECTED LOCATION •";
$datum=date("d.m.Y, H:i:s");
$array = file("location.log"); // Datei in ein Array einlesen
array_unshift($array, "".$datum." ".$ausgabe."\n");
$string = implode("", $array);
file_put_contents("location.log", $string);
?>
</body>
</html>
Anyone has a good idea? :)
If you want to save the longitude and latitude into a file (please check the Google API terms of usage if you are even allowed to do that), you have to get the coordinates first, then send them to your server via AJAX.
The below examples are not "copy/paste" material, since I didn't try them out. Use them as a general guideline.
First, you need to create a script, that will get the coordinates:
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<div id="pos" style="width:800px; height:600px;">
Detection Location..
</div>
<script>
$(function(){
function initialize(coords) {
$.ajax({
url: 'saveLocation.php',
data: {
longitude:coords.longitude,
latitude:coords.latitude
},
error: function() {
$('#pos').html("Could not save location");
},
success: function(data) {
$('#pos').html("Location saved successfully");
},
type: 'POST'
});
}
navigator.geolocation.getCurrentPosition(function(position){
initialize(position.coords);
}, function(){
$('#pos').html('Failed to detect Location.');
});
});
</script>
</body>
</html>
On your server, you need a PHP script ""saveLocation.php":
<?php
$ausgabe=$_POST['longitude'].":".$_POST['latitude'];
$datum=date("d.m.Y, H:i:s");
$array = file("location.log"); // Datei in ein Array einlesen
array_unshift($array, "".$datum." ".$ausgabe."\n");
$string = implode("", $array);
file_put_contents("location.log", $string);
echo json_encode(array("success"=>"true"));
?>
I used jQuery to simplify some of the regular stuff, like sending data via AJAX or changing the inner HTML of an element.
Again, this code is not in working condition. It will not work if you just copy/paste it
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 save graphs on server side. i was succeeded up to save one graph. but i am unable to save more than one graph.
here i mentioned 2 graphs but nly one graph is going to save on server.
how it can be ?
my code is
<script type="text/javascript">
var totalCharts = 2;
function exportCharts(exportType)
{
for( var i = 0; i < totalCharts; i++ ) {
var num = i+1;
var id = "chart"+num+"Id";
exportchart(exportType,id);
}
}
function exportchart(exportType,id)
{
var chart = FusionCharts(id);
// Now, we proceed with exporting only if chart has finished rendering.
if (chart.hasRendered() != true)
{
alert("Please wait for the chart to finish rendering, before you can invoke exporting");
return;
}
// call exporting function
chart.exportChart( {exportFormat: exportType} );
}
</script>
<p align="center">
<input type="button" class="button" value="Export as PNG" onclick="exportCharts('PNG')" id="exportButtonPNG" />
</p>
<div >
<div id="average" style="text-align:center">Loading Chart... </div>
<div id="overall" style="text-align:center">Loading Chart... </div>
</div>
<script type="text/javascript" >
// Render the chart (See documentation for explanation of the codes below)
//echo renderChart("FusionCharts/MSColumn3D.swf", "", $strXML3, "average", 1100, 350);
var chart2 = new FusionCharts("FusionCharts/MSColumn3D.swf", "chart1Id", "600", "400", "0", "1");
chart2.setXMLUrl("average.xml");
chart2.render("average");
var chart1 = new FusionCharts("FusionCharts/MSColumn3D.swf", "chart2Id", "600", "400", "0", "1");
chart1.setXMLUrl("overall.xml");
chart1.render("overall");
</script>
<!-- Google Analytics Tracker Code Starts -->
<script type="text/javascript">
// analytics
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost
+ "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
if (typeof(_gat) == "object") {
var pageTracker = _gat._getTracker("UA-215295-3"); pageTracker._initData(); pageTracker._trackPageview();
}
</script>
How i can solve this?
You may need to chain the call to exportChart function of each chart you have.
var totalCharts = 2;
(function () {
var totalExported = 0,
exportType;
window.FC_Exported = function() {
exportchart();
};
window.exportchart = function(exportFormat) {
exportType = exportType || exportFormat || 'jpg';
totalExported++ ;
var chart = FusionCharts("chart" + totalExported + "Id");
if (totalExported > totalCharts) {
return;
}
if (chart.hasRendered() != true) {
alert("Please wait for the chart to finish rendering, before you can invoke exporting");
}
// call exporting function
chart.exportChart( {exportFormat: exportType} );
};
}());
I have form like this :
<input type='hidden' name='seq' id='idseq' value='1' />
<div id='add_field' class='locbutton'><a href='#' title='Add'>Add</a></div>
<div id='remove_field' class='locbutton2'><a href='#' title='Delete'>Delete</a></div>
<div id="idcover">
1.<br />
<div class="group">
<div class="satu"><input type='text' name='score[1][]' id='score[1][]'></div>
<div class="dua"><input type='text' name='weight[1][]' id='weight[1][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[1][]' id='weightscore[1][]'
disabled></div>
</div>
</div>
<br /><br />
<div id='idtotalcover' class='totalcover'>
Total <div class='total'><input type='text' name='total' id='idtotal' disabled /></div>
</div>
This is the jquery script:
<script type="text/javascript">
$(document).ready(
function ()
{
$("input[id^=score],input[id^=weight]").bind("keyup", recalc);
recalc();
var counter = $("#idseq").val();
$("#add_field").click(function ()
{
counter++;
$.ajax({
url: 'addinput.php',
dataType: "html",
data: "count="+counter,
success: function(data)
{
$('#idcover').append(data);
$('.dua input').keyup(function()
{
var $duaInput = $(this);
var weight=$duaInput.val();
var score=$duaInput.closest(".group").find('.satu input').val();
$.ajax({
url: "cekweightscore.php",
data: "score="+score+"&weight="+weight,
success:
function(data)
{
$duaInput.closest(".group").find('.tiga input').val(data);
}//success
});//ajax
});
}//success
});//ajax
});
});
function recalc()
{
var a=$("input[id^=score]");
var b=$("input[id^=weight]");
$("[id^=weightscore]").calc("(score * weight)/100",{score: a,weight: b},
function (s)
{
return s.toFixed(2);
},
function ($this){
//function($("[id^=weightscore]")){
// sum the total of the $("[id^=total_item]") selector
//alert($this);
//var sum = $this.sum();
var sum=$this.sum();
$("#idtotal").val(sum.toFixed(2));
}
);
}
</script>
This is the php code:
<?
$count=$_GET['count'];
echo"
<br>
$count
<div class='group' >
<div class='satu'>
<input type='text' name='score[$count][]' id='score[$count][]'>
</div>
<div class='dua'>
<input type='text' name='weight[$count][]' id='weight[$count][]'> %
</div>
<div class='tiga'>
<input type='text' name='weightscore[$count][]' id='weightscore[$count][]' disabled>
</div>
</div>";
?>
When I click the Add button, i cant get value on new form so that the new form cannot be calculated. What can i do to get total value on dynamic value ?
I remember reading this exact same question yesterday and I still have no idea of what you're trying to do.
Why are you adding inputs through AJAX instead of creating them in Javascript from the beginning? AJAX calls are expensive and are recommended to be used when you need to update/retrieve values from the server.
Why are you trying to do your calculations on the server side anyway? If you're dealing with dynamic input, you should be doing the calculations client side, then update the server when you're done.
Why do you use obscure name/id attribute values?
Anyway,
I created this example, it contains two different solutions, one with a ul and a table. Hopefully, the example matches what you're trying to do and might give you some insight.
I use a timer to update simulated server data. The timer is set to the variable update_wait. The other dynamic calculations are done client side.
I'll post the Javascript code as well, in case you don't like to fiddle
Example | Javascript
var update_server_timer = null,
update_wait = 1000; //ms
var decimals = 3;
/**********************
List solution
**********************/
function CreateListRow(){
var eLi = document.createElement("li"),
eScore = document.createElement("div"),
eWeight = document.createElement("div"),
eWeightScore = document.createElement("div");
var next_id = $("#cover li:not(.total)").length + 1
eScore.className = "score";
eWeight.className = "weight";
eWeightScore.className = "weightscore";
//Score element
var eScoreInput = document.createElement("input");
eScoreInput.type = "text";
eScoreInput.name = "score_"+next_id;
eScoreInput.id = "score_"+next_id;
eScore.appendChild(eScoreInput);
//Weight element
var eWeightInput = document.createElement("input");
eWeightInput.type = "text";
eWeightInput.name = "weight_"+next_id;
eWeightInput.id = "weight_"+next_id;
var eWeightPerc = document.createElement("div");
eWeightPerc.className = "extra";
eWeightPerc.innerHTML = "%";
eWeight.appendChild(eWeightInput);
eWeight.appendChild(eWeightPerc);
//Weightscore element
var eWeightScoreInput = document.createElement("input");
eWeightScoreInput.type = "text";
eWeightScoreInput.name = "weight_"+next_id;
eWeightScoreInput.id = "weight_"+next_id;
eWeightScore.appendChild(eWeightScoreInput);
$(eScore).keyup(function(){
CalculateListRow($(this).closest("li"));
});
$(eWeight).keyup(function(){
CalculateListRow($(this).closest("li"));
});
//item element
eLi.appendChild(eScore);
eLi.appendChild(eWeight);
eLi.appendChild(eWeightScore);
return eLi;
}
function CalculateListRowTotal(){
var fTotal = 0;
$("#cover li:not(.total) div:nth-child(3) input").each(function(){
var fVal = parseFloat($(this).val());
if(isNaN(fVal)) fVal = 0;
fTotal += fVal;
});
fTotal = parseFloat(fTotal.toFixed(decimals));
$("#cover li.total div input").val(fTotal);
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateListRow($Li){
var fScore = parseFloat($("div.score input", $Li).val()),
fWeight = parseFloat($("div.weight input", $Li).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("div.weightscore input", $Li).val(parseFloat(fRes.toFixed(decimals)));
CalculateListRowTotal();
}
$("#cover li div.weight input, #cover li div.score input").keyup(function(){
CalculateListRow($(this).closest("li"));
});
function AddListRow(){
$("#cover li.total").before(CreateListRow());
RestartUpdateServerTimer();
}
function RemoveListRow(){
$("#cover li.total").prev().remove();
CalculateListRowTotal();
}
$(".left_container .menu .add").click(function(){ AddListRow(); });
$(".left_container .menu .rem").click(function(){ RemoveListRow(); });
/**********************
Table solution
**********************/
function CreateTableRow(){
var eTr = document.createElement("tr"),
eTds = [document.createElement("td"),
document.createElement("td"),
document.createElement("td")];
var next_id = $("#cover2 tbody tr").length + 1;
$(eTds[0]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "score_"+next_id;
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eInput;
});
$(eTds[1]).append(function(){
var eRelativeFix = document.createElement("div"),
eInput = document.createElement("input"),
eExtra = document.createElement("div");
eRelativeFix.className = "relative_fix";
eInput.type = "text";
eInput.name = eInput.id = "weight_"+next_id;
eExtra.innerHTML = "%";
eExtra.className = "extra";
eRelativeFix.appendChild(eInput);
eRelativeFix.appendChild(eExtra);
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eRelativeFix;
});
$(eTds[2]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "weightscore_"+next_id;
return eInput;
});
for(i = 0; i < eTds.length; i++){
eTr.appendChild(eTds[i]);
}
return eTr;
}
function CalculateTableRowTotals(){
var $rows = $("#cover2 tbody tr"),
$totals = $("#cover2 tfoot tr th");
var fTotal = [];
//Each row
$rows.each(function(){
var $columns = $("td", this);
//Each column
$columns.each(function(i, e){
var fVal = parseFloat($("input", e).val());
if(isNaN(fVal)) fVal = 0;
if(isNaN(fTotal[i])) fTotal[i] = 0;
fTotal[i] += fVal;
});
});
for(i = 0; i < fTotal.length; i++){
fTotal[i] = parseFloat(fTotal[i].toFixed(decimals));
}
fTotal[1] = (fTotal[2]/fTotal[0]*100).toFixed(decimals)+"%";
fTotal[2] = parseFloat(fTotal[2].toFixed(decimals));
$totals.each(function(i, e){
$(this).text(fTotal[i]);
});
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateTableRow($Tr){
var fScore = parseFloat($("td:nth-child(1) input", $Tr).val()),
fWeight = parseFloat($("td:nth-child(2) input", $Tr).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("td:nth-child(3) input", $Tr).val(parseFloat(fRes.toFixed(decimals)));
CalculateTableRowTotals();
}
function AddTableRow(){
if($("#cover2 tbody tr").length == 0){
$("#cover2 tbody").append(CreateTableRow());
}else{
$("#cover2 tbody tr:last-child").after(CreateTableRow());
}
RestartUpdateServerTimer();
}
function RemoveTableRow(){
$("#cover2 tbody tr:last-child").remove();
CalculateTableRowTotals();
}
$(".right_container .menu .add").click(function(){ AddTableRow(); });
$(".right_container .menu .rem").click(function(){ RemoveTableRow(); });
$("#cover2 tbody tr td:nth-child(1) input, #cover2 tbody tr td:nth-child(2) input").keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
/**********************
Server data
- Simulates the data on the server,
- whether it be in a SQL server or session data
**********************/
var ServerData = {
List: {
Count: 3,
Total: 5.50
},
Table: {
Count: 3,
Totals: [65, 8.46, 5.50]
}
};
function UpdateServerData(){
//List
var ListCount = $("#cover li:not(.total)").length,
ListTotal = $("#cover li.total input").val();
//Table
var TableCount = $("#cover2 tbody tr").length,
TableTotals = [];
$("#cover2 tfoot th").each(function(i, e){
TableTotals[i] = parseFloat($(this).text());
});
var data = {
json: JSON.stringify({
List: {
Count: ListCount,
Total: ListTotal
},
Table: {
Count: TableCount,
Totals: TableTotals
}
})
}
//Update
$.ajax({
url: "/echo/json/",
data: data,
dataType: "json",
type:"POST",
success: function(response){
ServerData.List = response.List;
ServerData.Table = response.Table;
var displist = "Server data<h1>List</h1><ul><li>Count: "+ServerData.List.Count+"</li><li>Total: "+ServerData.List.Total+"</li></ul>",
disptable = "<h1>Table</h1><ul><li>Count: "+ServerData.Table.Count+"</li>";
for(i=0; i<ServerData.Table.Totals.length; i++)
disptable += "<li>Total "+i+": "+ServerData.Table.Totals[i]+"</li>";
disptable += "</ul>";
$("#server_data").html(displist+"<br />"+disptable).effect("highlight");
}
});
}
function RestartUpdateServerTimer(){
if(update_server_timer != null) clearTimeout(update_server_timer);
update_server_timer = setTimeout(function(){
UpdateServerData()
}, update_wait);
}
UpdateServerData();
Update
Since you have a hard time grasping the concept, here's a copy paste solution that will work for you without having to use AJAX. I would like to point out that your HTML markup and general coding is a total mess...
Example | Code
<script type="text/javascript">
$(document).ready(function(){
function CreateInput(){
var $group = $("<div>"),
$score = $("<div>"),
$weight = $("<div>"),
$weightscore = $("<div>");
var group_count = $("div.group").length+1;
$group.addClass("group");
$score.addClass("satu");
$weight.addClass("dua");
$weightscore.addClass("tiga");
var $input_score = $("<input>"),
$input_weight = $("<input>"),
$input_weightscore = $("<input>")
$input_score
.attr("name", "score["+group_count+"][]")
.attr("type", "text")
.attr("id", "score["+group_count+"][]");
$input_weight
.attr("name", "weight["+group_count+"][]")
.attr("type", "text")
.attr("id", "weight["+group_count+"][]");
$input_weightscore
.attr("name", "weightscore["+group_count+"][]")
.attr("type", "text")
.attr("id", "weightscore["+group_count+"][]")
.attr("disabled", true);
$input_score.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$input_weight.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$score.append($input_score);
$weight.append($input_weight);
$weightscore.append($input_weightscore);
$group.append($score)
.append($weight)
.append($weightscore);
return $group;
}
function CalculateGroup($group){
var fScore = parseFloat($(".satu input", $group).val()),
fWeight = parseFloat($(".dua input", $group).val()),
fWeightScore = parseFloat((fScore*(fWeight/100)).toFixed(2));
if(isNaN(fWeightScore)) fWeightScore = 0;
$(".tiga input", $group).val(fWeightScore);
CalculateTotal();
}
function CalculateTotal(){
var fWeightScoreTotal = 0;
$("#idcover div.group div.tiga input").each(function(){
var fTotal = parseFloat(parseFloat($(this).val()).toFixed(2));
if(isNaN(fTotal)) fTotal = 0;
fWeightScoreTotal += fTotal;
});
fWeightScoreTotal = parseFloat(fWeightScoreTotal.toFixed(2));
$("#idtotalcover div.total input").val(fWeightScoreTotal);
}
$(".satu input, .dua input").keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$("#add_field a").click(function(e){
$("#idcover").append(CreateInput());
e.preventDefault();
});
$("#remove_field a").click(function(e){
$("#idcover div.group:last-child").remove();
CalculateTotal();
e.preventDefault();
});
});
</script>
I have an image being created with gdimage, which has 40000 5x5 blocks linking to different user profiles and I want that when you hover over one of those blocks, AJAX will go and fetch that profile from the database by detecting the x and y co-ords when it is moved over the image.
Then when it is clicked, with the information it has obtained link to that users profile.
Here is what I have got so far:
Javascript/jQuery:
<script type="text/javascript">
jQuery.fn.elementlocation = function() {
var curleft = 0;
var curtop = 0;
var obj = this;
do {
curleft += obj.attr('offsetLeft');
curtop += obj.attr('offsetTop');
obj = obj.offsetParent();
} while ( obj.attr('tagName') != 'BODY' );
return ( {x:curleft, y:curtop} );
};
$(document).ready( function() {
$("#gdimage").mousemove( function( eventObj ) {
var location = $("#gdimage").elementlocation();
var x = eventObj.pageX - location.x;
var x_org = eventObj.pageX - location.x;
var y = eventObj.pageY - location.y;
var y_org = eventObj.pageY - location.y;
x = x / 5;
y = y / 5;
x = (Math.floor( x ) + 1);
y = (Math.floor( y ) + 1);
if (y > 1) {
block = (y * 200) - 200;
block = block + x;
} else {
block = x;
}
$("#block").text( block );
$("#x_coords").text( x );
$("#y_coords").text( y );
$.ajax({
type: "GET",
url: "fetch.php",
data: "x=" + x + "&y=" + y + "",
dataType: "json",
async: false,
success: function(data) {
$("#user_name_area").html(data.username);
}
});
});
});
</script>
PHP:
<?
require('connect.php');
$mouse_x = $_GET['x'];
$mouse_y = $_GET['y'];
$grid_search = mysql_query("SELECT * FROM project WHERE project_x_cood = '$mouse_x' AND project_y_cood = '$mouse_y'") or die(mysql_error());
$user_exists = mysql_num_rows($grid_search);
if ($user_exists == 1) {
$row_grid_search = mysql_fetch_array($grid_search);
$user_id = $row_grid_search['project_user_id'];
$get_user = mysql_query("SELECT * FROM users WHERE user_id = '$user_id'") or die(mysql_error());
$row_get_user = mysql_fetch_array($get_user);
$user_name = $row_get_user['user_name'];
$user_online = $row_get_user['user_online'];
$json['username'] = $user_name;
echo json_encode($json);
} else {
$json['username'] = $blank;
echo json_encode($json);
}
?>
HTML
<div class="tip_trigger" style="cursor: pointer;">
<img src="gd_image.php" width="1000" height="1000" id="gdimage" />
<div id="hover" class="tip" style="text-align: left;">
Block No. <span id="block"></span><br />
X Co-ords: <span id="x_coords"></span><br />
Y Co-ords: <span id="y_coords"></span><br />
User: <span id="user_name_area"> </span>
</div>
</div>
Now, the 'block', 'x_coords' and 'y_coords' variables from the mousemove location works fine and shows in the span tags, but it's not getting the PHP variables from the AJAX function and I can't understand why.
I also don't know how to make it so when the mouse is clicked it takes the variables taken from fetch.php and directs the user to a page such as "/user/view/?id=VAR_ID_NUMBER"
Am I approaching this the wrong way, or doing it wrong? Can anyone help? :)
Please see the comments about not doing a fetch with every mousemove. Bad bad bad idea. Use some throttling.
That said, the problem is, you're not using the result in any way in the success function.
Your PHP function doesn't return anything to the browser. PHP variables do not magically become available to your client-side JavaScript. PHP simply runs, produces an HTML page as output, and sends it to the browser. The browser then parses the information that was sent to it as appropriate.
You need to modify your fetch.php to produce some properly formatted JSON string with the data you need. It would look something like { userid: 2837 }. For example, try:
echo "{ userid: $user_id, username: $user_name }";
In your success callback, the first argument jQuery will pass to that function will be the result of parsing the (hopefully properly formatted) JSON result so that it becomes a proper JavaScript object. Then, in the success callback, you can use the result, in a way such as:
//data will contain a JavaScript object that was generate from the JSON
//string the fetch.php produce, *iff* it generated a properly formatted
//JSON string.
function(data) {
$("#user_id_area").html(data.user_id);
}
Modify your HTML example as follows:
User ID: <span id="user_id_area"> </span>
Where showHover is a helper function that actually shows the hover.
Here is a pattern for throttling the mousemove function:
jQuery.fn.elementlocation = function() {
var curleft = 0;
var curtop = 0;
var obj = this;
do {
curleft += obj.attr('offsetLeft');
curtop += obj.attr('offsetTop');
obj = obj.offsetParent();
} while ( obj.attr('tagName') != 'BODY' );
return ( {x:curleft, y:curtop} );
};
$(document).ready( function() {
var updatetimer = null;
$("#gdimage").mousemove( function( eventObj ) {
clearTimer(updatetimer);
setTimeout(function() { update_hover(eventObj.pageX, eventObj.pageY); }, 500);
}
var update_hover = function(pageX, pageY) {
var location = $("#gdimage").elementlocation();
var x = pageX - location.x;
var y = pageY - location.y;
x = x / 5;
y = y / 5;
x = (Math.floor( x ) + 1);
y = (Math.floor( y ) + 1);
if (y > 1) {
block = (y * 200) - 200;
block = block + x;
} else {
block = x;
}
$("#block").text( block );
$("#x_coords").text( x );
$("#y_coords").text( y );
$.ajax({
type: "GET",
url: "fetch.php",
data: "x=" + x + "&y=" + y + "",
dataType: "json",
async: false,
success: function(data) {
//If you're using Chrome or Firefox+Firebug
//Uncomment the following line to get debugging info
//console.log("Name: "+data.username);
$("#user_name_area").html(data.username);
}
});
});
});
Can you show us the PHP code? Do you use json_encode on the return data?
An alternative would be to simply make the image a background to a <div> container and arrange <a> elements in the <div> where you need them then simply bind with jQuery to their click handler.
This also has benefits if the browser does not support jQuery or javascript as you can actually put the URL you need in the HREF attribute of the anchor. This way if jQuery is not enabled the link will be loaded normally.
A skeleton implementation would look like this:
Example CSS
#imagecontainer {
background-image: url('gd_image.php');
width: 1000px;
height: 1000px;
position: relative;
}
#imagecontainer a {
height: 100px;
width: 100px;
position: absolute;
}
#block1 {
left: 0px;
top: 0px;
}
#block2 {
left: 100px;
top: 0px;
}
Example HTML
<div id="imagecontainer">
</div>
Example jQuery
$(document).ready(function(){
$("#block1").click(function(){ /* do what you need here */ });
});