i'm new here. i just create a code which can read the data from mysql database.
But when i add in new data inside databse, my php page cant updated own automatic.
I want the page can updated automaticly withour press f5 button and refresh.
Can anyone help me solve this?
Get any misstake??
<script type="text/javascript">
function List(){
var ajaxRequest;
var selectedProduct = "";
var product = document.getElementById('product');
var output ="";
var k = 0;
// var name = new Array;
// var model = new Array;
var unitprice = new Array;
var queryString = new Array;
queryString = "&name=" + txtname + "&model=" + txtmodel + ;
ajaxRequest.open("GET", $productPrice + queryString, true);
ajaxRequest.send(null);
ajaxRequest.open("GET", $productPrice + queryString, true);
ajaxRequest.send(null);
<?php foreach ($productPrices as $price): ?>
name[k] = "<?php echo $price['Product']['txtname']; ?>";
model[k] = "<?php echo $price['Product']['txtmodel']; ?>";
k++;
<?php endforeach; ?>
k=0;
for (var i = 0; i < product.length; i++) {
k = product.options[i].value;
if (product.options[i].selected) {
output += '<tr>'+
'<td style="border-right: 0px; width:270px; text-align:center" id="ProductProduct'+k+'" name="data[Product][Product]['+k+']">'+name[i]+'</td>'+
'<td style="border-right: 0px; width:100px; text-align:left" id="ProductProduct'+k+'" name="data[Product][Product]['+k+']">'+model[i]+'</td>'+
'</tr>';
}
}
output = '<table style="width:500px; border: 0px;">'+output+'</table>';
document.getElementById('productTable').innerHTML = output;
}
</script>
You need some kind of repeated AJAX check in your page to see if there is new data in the database. You can do this using setTimeout or setInterval.
E.g.
function CheckData() {
List();
setTimeout(CheckData, 10000);
}
setInterval(function() {
List(); // your function
// Do something every 2 seconds
}, 2000);
this is jquery function this will help you.
Related
I have a websocket script that looks in blockchain to a specific address if someone sends btc. If the payment is done, the script will output with javascript innerHTML a message. Is there a way I can make to run a php script if this happens? Script below
<script>
var btcs = new WebSocket("wss:ws.blockchain.info/inv");
btcs.onopen = function(){
btcs.send(JSON.stringify({"op":"addr_sub", "addr":<?php echo json_encode($new_address, JSON_HEX_TAG); ?>}));
};
btcs.onmessage = function(onmsg) {
var response = JSON.parse(onmsg.data);
var getOuts = response.x.out;
var countOuts = getOuts.length;
for(i=0; i<countOuts; i++){
var outAdd = response.x.out(i).addr;
var address = <?php echo json_encode($new_address, JSON_HEX_TAG); ?>;
if(outAdd == address){
var amount = response.x.out(i).value;
var recAmount = amount / 100000000;
document.getElementByid("websocket").innerHTML = "Payment recieved: " + recAmount + "BTC <br>;
};
};
};
</script>
<p id="websocket">Monitoring transaction...</p>
I'm very new to coding and am creating an online system. Part of the system I have included Google Distance Matrix API which is JavaScript, whereas most of my other code is HTML or PHP. Unfortunately, I need the distance (which is calculated in JavaScript) to be in my PHP code so I can play about with it. I read I could use AJAX? I'm not terribly sure about what I'm doing but I had a go.
Before the page that includes the Google Map, there is a form. This means I have to use SESSION variables to move the data from the page before the Google page, to two pages after the Google page.. this is also where my Google script gets it's two locations to find the distance between. Which all works fine, I think.
PHP on Google page:
$date = $_POST['date'];
$time = $_POST['time'];
$length = $_POST['length'];
$numberofpeople = $_POST['numberofpeople'];
$useofbus = $_POST['useofbus'];
session_start();
$_SESSION['time'] = $time;
$_SESSION['date'] = $date;
$_SESSION['length'] = $length;
$_SESSION['numberofpeople'] = $numberofpeople;
$_SESSION['pickuplocation'] = $pickuplocation;
$_SESSION['destination'] = $destination;
$_SESSION['useofbus'] = $useofbus;
$pickuplocation = $_POST['pickuplocation'];
$destination = $_POST['destination'];
HTML on Google page:
</head>
<body onload="initialize()">
<div id="inputs">
<pre class="prettyprint">
</pre>
<form name="google" action="thirdform.php">
<table summary="google">
<tr>
<td> </td>
<td><input name="Continue" value="Continue" type="submit" ></td>
<td> </td>
</tr>
</table>
</form>
</div>
<div id="outputDiv"></div>
<div id="map"></div>
</body>
</html>
I won't post the JavaScript of the Google Matrix other than the AJAX:
var distance = results[j].distance.text;
$.get("thirdform.php", {miles:distance} );
I'm not sure if the code above is correct, I'm guessing I'm going wrong somewhere, probably here.
On the next page, (thirdform.php) PHP:
session_start();
$time = $_SESSION['time'];
$date = $_SESSION['date'];
$length = $_SESSION['length'];
$numberofpeople = $_SESSION['numberofpeople'];
$pickuplocation = $_SESSION['pickuplocation'];
$destination = $_SESSION['destination'];
$useofbus = $_SESSION['useofbus'];
var_dump($_SESSION);
echo "</br>";
$distance = $_GET['miles'];
echo "DISTANCE: " . $distance . "</br>";
I'm not able to get anything in the PHP variable $distance - it's empty. Am I coding incorrectly? I followed an example on-line from this website somewhere which claimed to work. I've read several articles and searched on Google and on this website but there doesn't seem to be a clear answer anywhere that isn't too complicated and relates to what I'm trying to do. I've read plenty of examples but they're all far too complicated for me to use and change to put into my code. There was some code I read where the page was sent straight to next page however I need to show the Google Map on my page and therefore need to use the button to move to the next page.
Could anyone give me a nudge in the right direction? Thanks.
JS:
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin = '<?php echo $pickuplocation; ?>';
var destination = '<?php echo $destination; ?>';
var destinationIcon = 'https://chart.googleapis.com/chart? chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
geocoder = new google.maps.Geocoder();
calculateDistances()
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
<script type="text/javascript">
var distance = results[j].distance.text;
$('.button-class').click(function() { $.get("thirdform.php", {miles:distance}, function (data){alert(data)} ); });
</script>
Since you are overriding the form action with the $.get, try removing the form and using a <button> instead of an <input> button.
Then have your ajax request run on that <button>.
Edit:
It's also worth noting that you should probably just send data from the php file. You can then do any other manipulation("DISTANCE: ", "<br />") in the html/js.
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 am not very experienced just a learner.
Now come to the question.
I have a dynamic table codes are below: works fine as intended.
<head>
<style type="text/css">
<!--
#tblitemsgrid
td {
padding: 0.5em;
}
.classy0 { background-color: #234567; color: #89abcd; }
.classy1 { background-color: #89abcd; color: #234567; }
th {
padding: 0.5em;
background:#39C;
text-align:center;
}
-->
</style>
<script type="text/javascript">
var INPUT_NAME_PREFIX = 'input'; // this is being set via script
var RADIO_NAME = 'totallyrad'; // this is being set via script
var TABLE_NAME = 'tblitemsgrid'; // this should be named in the HTML
var ROW_BASE = 1; // first number (for display)
var hasLoaded = false;
window.onload=fillInRows;
function fillInRows()
{
hasLoaded = true;
addRowToTable();
}
// CONFIG:
// myRowObject is an object for storing information about the table rows
function myRowObject(one, two, three, four, five)
{
this.one = one; // text object
this.two = two; // text object
this.three = three; // text object
this.four = four; // text object
}
/*
* insertRowToTable
* Insert and reorder
*/
function insertRowToTable()
{
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var rowToInsertAt = tbl.tBodies[0].rows.length;
for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
}
addRowToTable(rowToInsertAt);
reorderRows(tbl, rowToInsertAt);
}
}
/*
* addRowToTable
function addRowToTable(num)
{
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var nextRow = tbl.tBodies[0].rows.length;
var iteration = nextRow + ROW_BASE;
if (num == null) {
num = nextRow;
} else {
iteration = num + ROW_BASE;
}
// add the row
var row = tbl.tBodies[0].insertRow(num);
// CONFIG: requires classes named classy0 and classy1
row.className = 'classy' + (iteration % 2);
// CONFIG: This whole section can be configured
// cell 0 - text - Serial Number
var cell0 = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cell0.appendChild(textNode);
// cell 1 - input text - Account name
var cell1 = row.insertCell(1);
var txtInpACC = document.createElement('input');
txtInpACC.setAttribute('type', 'text');
txtInpACC.setAttribute('name', 'accname' + iteration);
txtInpACC.setAttribute('size', '40');
txtInpACC.setAttribute('value', iteration);
cell1.appendChild(txtInpACC);
// cell 2 - input box- Dr amount
var cell2 = row.insertCell(2);
var txtInpDR = document.createElement('input');
txtInpDR.setAttribute('type', 'text');
txtInpDR.setAttribute('name', 'DrAmount' + iteration);
txtInpDR.setAttribute('size', '10');
txtInpDR.setAttribute('value', iteration); // iteration included for debug purposes
cell2.appendChild(txtInpDR);
// cell 3 - input box- Cr amount
var cell3 = row.insertCell(3);
var txtInpCR = document.createElement('input');
txtInpCR.setAttribute('type', 'text');
txtInpCR.setAttribute('name', 'CrAmount' + iteration);
txtInpCR.setAttribute('size', '10');
txtInpCR.setAttribute('value', iteration); // iteration included for debug purposes
cell3.appendChild(txtInpCR);
// cell 4 - input button - Delete
var cell4 = row.insertCell(4);
var btnEl = document.createElement('input');
btnEl.setAttribute('type', 'button');
btnEl.setAttribute('value', 'Delete');
btnEl.onclick = function () {deleteCurrentRow(this)};
cell4.appendChild(btnEl);
// Pass in the elements you want to reference later
// Store the myRow object in each row
row.myRow = new myRowObject(textNode, txtInpACC, txtInpDR, txtInpCR, btnEl);
}
}
// CONFIG: this entire function is affected by myRowObject settings
function deleteCurrentRow(obj)
{
if (hasLoaded) {
var oRows = document.getElementById('tblitemsgrid').getElementsByTagName('tr');
var iRowCount = (oRows.length - 2);
if (iRowCount <1+1) {
alert('Your table has ' + iRowCount + ' row(s). Row count can not be zero.');
return
}
var delRow = obj.parentNode.parentNode;
var tbl = delRow.parentNode.parentNode;
var rIndex = delRow.sectionRowIndex;
var rowArray = new Array(delRow);
deleteRows(rowArray);
reorderRows(tbl, rIndex);}
}
function reorderRows(tbl, startingIndex)
{
if (hasLoaded) {
if (tbl.tBodies[0].rows[startingIndex]) {
var count = startingIndex + ROW_BASE;
for (var i=startingIndex; i<tbl.tBodies[0].rows.length; i++) {
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.one.data = count; // text
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.two.name = INPUT_NAME_PREFIX + count; // input text
var tempVal = tbl.tBodies[0].rows[i].myRow.two.value.split(' ');
tbl.tBodies[0].rows[i].myRow.two.value = count + ' was' + tempVal[0];
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.four.value = count; // input radio
// CONFIG: requires class named classy0 and classy1
tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
count++;
}
}
}
}
function deleteRows(rowObjArray)
{
if (hasLoaded) {
for (var i=0; i<rowObjArray.length; i++) {
var rIndex = rowObjArray[i].sectionRowIndex;
rowObjArray[i].parentNode.deleteRow(rIndex);
}
}
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'TableAddRow2NewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'TableAddRow2NewWindow';
// submit
frm.submit();
}
</script>
</head>
<body>
<form action="tableaddrow_nw.php" method="get">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Insert [I]" onclick="insertRowToTable();" />
<!--<input type="button" value="Delete [D]" onclick="deleteChecked();" />-->
<input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
</p>
<table border="0" cellspacing="0" id="tblitemsgrid" width=600>
<thead>
<tr>
<th colspan="5">Sample table</th>
</tr>
<tr>
<th>E.#</th>
<th>Account name</th>
<th>Debit</th>
<th>Credit</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</form>
</body>
</html>
This is a processing page:
<head>
<title>Table Add Row - new window</title>
<script language="JavaScript">
<!--
function printToPage()
{
var pos;
var searchStr = window.location.search;
var searchArray = searchStr.substring(1,searchStr.length).split('&');
var htmlOutput = '';
for (var i=0; i<searchArray.length; i++) {
htmlOutput += searchArray[i] + '<br />';
}
return(htmlOutput);
}
//-->
</script>
</head>
<body>
<b>MREDKJ's Table Add Row</b>
<br />
Below should be the name/value pairs that were submitted:
<p>
<script language="JavaScript">
<!--
document.write(printToPage());
//-->
</script>
</p>
</body>
</html>
the above displays a result:
accname1=1
DrAmount1=1
CrAmount1=1
input2=2+was2
DrAmount2=2
CrAmount2=2
input3=3+was3
DrAmount3=3
CrAmount3=3
input4=4+was4
DrAmount4=4
CrAmount4=4
how can I pass javascript variables into PHP (which is server side and client side) in the above case ?
thanks alot in advance.
The way to pass variables from client-side to server-side is via HTTP Request. So either you redirect to a PHP page passing in the variable as GET query strings or POST data or you can also do an AJAX call of either GET or POST.
You can use jQuery and ajax to pass these informations to server easy way
And remember. PHP isn't client side language
$.ajax({
'url': 'ajax.php',
'type': 'POST',
'data': 'accname1='+accname1+'&input1='+input1+'&input2='+input2+'&input3='+input3+'&DrAmount1='+DrAmount1+'&DrAmount2='+DrAmount2+'&DrAmount3='+DrAmount3+'&CrAmount1='+CrAmount1'&CrAmount2='+CrAmount2'&CrAmount3='+CrAmount3,
'success': function(){
alert('data sent');
}
});
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 */ });
});