Multiple countdown timers using a PHP loop - php

What I'm trying to do is output data from my database using PHP. Alongside this data I'd like to include a countdown timer using the data from my database. Naturally, the timer is done using JavaScript but I'm struggling to work out how to include the PHP variable in the JavaScript code and then loop through all my results, including an instance of the timer on each row.
I'm testing over here: http://www.lineswritten.co.uk/Countdown/ - The red 'timer here' is where I'd want the top 4 instances of 'waiting...' to be. These four instances aren't included in my loop.
I presume this would be done with $count++ but I'm not sure how to code this all up.
My JavaScript timer has been grabbed from here: http://jsfiddle.net/HSx9U/
The code is the following:
JavaScript
var count1 = new countDown(new Date('2010/12/11 10:44:59'),'counter1', 'tomorrow 10:45')
,count2 = new countDown(new Date('2010/12/25'),'counter2', 'first christmas day 2010')
,count3 = setTimeout(function(){
return new countDown(new Date('2011/12/25'),'counter3', 'first christmas day 2011');
},2000)
,count4 = setTimeout(function(){
return new countDown(new Date('2100/01/01'),'counter4', 'a new era starts');
},4000);
function countDown(startTime, divid, the_event){
var tdiv = document.getElementById(divid)
,start = parseInt(startTime.getTime(),10)
,the_event = the_event || startTime.toLocaleString()
,to;
this.rewriteCounter = function(){
var now = new Date().getTime()
,diff = Math.round((start - now)/1000);
if (startTime > now)
{
tdiv.innerHTML = diff +' seconds untill ' + the_event;
}
else {clearInterval(to);}
};
this.rewriteCounter();
to = setInterval(this.rewriteCounter,1000);
}
HTML
<div id="counter1">waiting...</div>
<div id="counter2">waiting...</div>
<div id="counter3">waiting...</div>
<div id="counter4">waiting...</div>
HTML Table/PHP loop
<table>
<tr>
<th id="logo">Logo</th>
<th id="name">Name</th>
<th id="discount">Discount</th>
<th id="length">Sale Length</th>
<th id="time">Time Remaining</th>
<th id="what">On What</th>
<th id="small-print">Small Print</th>
<th id="link">Link to Sale</th>
</tr>
while ($row = mysql_fetch_array($result)) {
$discount = $row['discount'];
$product = $row['product'];
$terms = utf8_decode($row['terms']);
$brand_name = $row['brand_name'];
$code = $row['code'];
$link = $row['link'];
$logo = $row['logo'];
$length = $row['length'];
<tr>
<td headers="logo"><?php echo $logo;?></td>
<td headers="name"><p><?php echo $brand_name;?></p></td>
<td headers="discount"><p><?php echo $discount;?></p></td>
<td headers="length"><p><?php echo $length;?></p></td>
<td headers="time"><p style="color:#F00;">timer here</p></td>
<td headers="what"><p><?php echo $product;?></p></td>
<td headers="small-print"><p><?php echo $terms;?></p></td>
<td headers="link"><p>Redeem</p></td>
}
</table>
I presumed I could change the new Date('2010/12/11 10:44:59') to new Date('$newDate') but it didn't work.

Geting stuff from PHP to javascript is best done using PHP's json_encode() function. You can feed it an array like this:
$array = ('item1', 'item2');
echo '<script type="text/javascript">';
echo 'var myarray = '.json_encode($array).';';
// iterate etc here
echo '</script>';

Related

Return instead of echo in WP plugin

This is probably a stupid question, but I'm new to coding so here goes :-).
I'm trying to create a simple plugin for WordPress. The plugin gets data from a MySQL database and echos out a table with the results. My problem is when I use echo the plugin is places first on the page even if i put the shortcode in the middle of the page. I understand that is because I use echo instead of return. I just don't get how to use return in my case. Any help would be much appreciated :-).
Here's my code:
$get_runners = $connection->prepare('SELECT first_name, last_name, nick_name, FROM database WHERE status = :status ORDER BY first_name ASC');
$get_runners->execute([status=>'success']);
// Create the table
echo '
<table id="Table" class="start-list-table">
<thead>
<tr class="start-list-tr">
<th scope="col">Name</th>
<th scope="col">Club</th>
</tr>
</thead>
<tbody>
';
// Get the runner object:
$runners = $get_runners->fetchAll();
foreach($runners as $runner){
if($runner->nick_name)
{
$runner_name = $runner->first_name.' "'.$runner->nick_name.'" '.$runner->last_name;
}
else
{
$runner_name = $runner->first_name.' '.$runner->last_name;
}
echo '
<tr class="start-list-tr">
<td data-label="Name">'.$runner_name.'</td>
<td data-label="Club">'.$runner->club.'</td>
</tr>';
}
echo '</tbody>
</table>';
}
add_shortcode( 'startlist', 'create_startlist' );
You want to assign your output to a variable, instead of echoing:
$get_runners = $connection->prepare('SELECT first_name, last_name, nick_name, FROM database WHERE status = :status ORDER BY first_name ASC');
$get_runners->execute([status=>'success']);
// Create the table
$output = '
<table id="Table" class="start-list-table">
<thead>
<tr class="start-list-tr">
<th scope="col">Name</th>
<th scope="col">Club</th>
</tr>
</thead>
<tbody>
';
// Get the runner object:
$runners = $get_runners->fetchAll();
foreach($runners as $runner){
if($runner->nick_name)
{
$runner_name = $runner->first_name.' "'.$runner->nick_name.'" '.$runner->last_name;
}
else
{
$runner_name = $runner->first_name.' '.$runner->last_name;
}
$output .= '
<tr class="start-list-tr">
<td data-label="Name">'.$runner_name.'</td>
<td data-label="Club">'.$runner->club.'</td>
</tr>';
}
$output .= '</tbody>
</table>';
return $output;
}
add_shortcode( 'startlist', 'create_startlist' );
This uses concatenation to continue to fill the variable through your function. You then set the return to the $output variable.
Firstly read more about Shortcodes Output : https://codex.wordpress.org/Shortcode_API#Output
There are two ways that I can think of at this moment.
Using ob_start... basically you need to wrap you code in ob_start()
function create_startlist() {
ob_start();
/* CODE HERE */
return ob_get_clean();
}
Second is to use a concatenation operator
function create_startlist() {
$output = '';
$output .= 'OUTPUT HERE';
return $output;
}

How to add +1 to var with href?

I have this quantity (var name: $Quantidade) displayed from a cart and need to add + and - hrefs to make it increase/decrease value.
Quantity:
quantity
Full table:
table
The quantity var always starts at 1.
All my attempts have failed.
Here is some code for the table (works if the + href is removed):
<table class="cart" width=700px cellpadding="0" cellspacing="0" style="border: 1px;" rules="none" align="center">
<tr height=40px align="center">
<td>Product</td>
<td>Price</td>
<td></td>
<td>Quantity</td>
<td></td>
<td>Delete</td>
</tr>
<?php
// Carrinho
$total=0;
foreach($_SESSION['venda'] as $Prod => $Quantidade):
$SqlCarrinho = mysqli_query($conect,"SELECT * FROM produto WHERE id= '$Prod'");
$ResAssoc = mysqli_fetch_assoc($SqlCarrinho);
echo '<tr height=40px align="center">';
echo '<td>'.$ResAssoc['descricao'].'</td>';
echo '<td>'.number_format($ResAssoc['preco'],2,",",".").'€</td>';
echo '<td>-</td>';
echo '<td>'.$Quantidade.'</td>';
echo '<td>+</td>';
echo '<td>x</td>';
$total += $ResAssoc['preco'] * $Quantidade;
echo '</tr>';
endforeach;
echo '<tr height=40px>';
echo '<td colspan="6" align="right">Total: '.number_format($total,2,",",".").'€</td>';
echo '</tr>';
echo'</table>';
Here is some code for the sessions I use:
session_start();
if(isset($_POST['more'])){ $_SESSION['venda'] [$_GET['par']] = $_GET['par'] + 1 ; }
if(isset($_SESSION['venda'])){}
else{ $_SESSION['venda'] = array(); }
if(isset($_GET['par'])){ $_SESSION['venda'] [$_GET['par']] = 1 ; }
if(isset($_GET['del'])){
$Del = $_GET['del'];
unset($_SESSION['venda'][$Del]);
Everything works until I add the + href, then it disformats the table:
broken table
I have confirmed its not a css error, the href is gone with/without css.
You need to remove the # in the link.
<a href="?more=true&par='.$Prod.'>+</a>
instead of
<a href="#?more=true&par='.$Prod.'>+</a>
When sending requests to your server, the browser ignores everything after the first #. Your GET parameters are not sent with the request currently.
Update
Check out the marked line. It resets venda → par every time par is set (which is always the case if you want to increase your value). Maybe you also want this to initialize the var. In this case you need to fix the if statement (if(!isset($_GET['par'])){ /* ... */ }). Venda gets reseted too.
session_start();
if(isset($_POST['more'])){ $_SESSION['venda'] [$_GET['par']] = $_GET['par'] + 1 ; }
if(isset($_SESSION['venda'])){}
else{ $_SESSION['venda'] = array(); }
// This line
if(isset($_GET['par'])){ $_SESSION['venda'] [$_GET['par']] = 1 ; }
if(isset($_GET['del'])){
$Del = $_GET['del'];
unset($_SESSION['venda'][$Del]);
Update 2
I think you want the code like this:
session_start();
// First, check if all vars are initialized
// Init if 'venda' is NOT set
if (!isset($_SESSION['venda'])) {
$_SESSION['venda'] = array();
}
// Init if 'venda['par'] is not set
if (isset($_GET['par']) && !isset($_SESSION['venda'][$_GET['par']])) {
$_SESSION['venda'][$_GET['par']] = 1;
}
// Run the updates/deletions
// Increase if 'more' is set
if (isset($_POST['more']) && isset($_GET['par'])) {
$_SESSION['venda'][$_GET['par']] += 1;
}
// Delete
if (isset($_GET['del'])) {
$Del = $_GET['del'];
unset($_SESSION['venda'][$Del]);
}

Update stock price using ajax

I am doing a small personal web portfolio in order to learn web development. I have a list of all the stocks that I have "bought" and I would like to update the price in real-time from yahoo finance. I can already do the price update but I override the table that I display the stocks with a new one that is called using javascript.
I know there must be a cleaner way. I am trying to update the price using javascript but I don't think I am doing everything right.
Here is what I have so far.
Portfolio.php displays all the stocks I have
<?php foreach ($shares as $row): ?>
<tr >
<td><?php echo $row["symbol"];?></td>
<td><?php echo $row["name"];?></td>
<td style="text-align: right;"><?php echo $row["shares"];?></td>
<td id="price" style="text-align: right;">$ <?php echo number_format($row["price"],2);?></td>
<td style="text-align: right;"><?php
$change = number_format($row["change"],2);
echo sprintf( "%+1.2f", $change );
echo " ( ";
echo $row["pct"];
echo " )";
?></td>
<td style="text-align: right;">$ <?php echo $row["dayGain"];?></td>
<td style="text-align: right;">$ <?php echo number_format($row["total"],2);?></td>
</tr>
<?php endforeach; ?>
</table>
<script type="text/javascript" src="../html/js/update.js" ></script>
Then I have update.php which returns all the stock information from yahoo finance as a json
<?php
// configuration
require("../includes/config.php");
//query user's portfolio
$rows = query("SELECT * FROM shares WHERE id = ?", $_SESSION["id"]);
$cash = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
//create array to store the shares
$shares = array();
//for each of the user info
foreach($rows as $row){
$yql_base_url = "http://query.yahooapis.com/v1/public/yql";
$yql_query = "select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22".$row['symbol']."%22)%0A%09%09";
$env = "env=http%3A%2F%2Fdatatables.org%2Falltables.env";
$yql_full_query = $yql_base_url . "?q=" . $yql_query . "&format=json&" . $env;
$session = curl_init($yql_full_query);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($session);
$stock = json_decode($json);
if($stock->query->results !== false){
$shares [] = array(
"symbol" => $stock->query->results->quote->symbol,
"price" => $stock->query->results->quote->LastTradePriceOnly
);
}
}
$return = array("price" => $shares );
echo json_encode($return);
?>
And the third file is update.js in which I am trying to have javascript
$(document).ready(function(){
function stock() {
$(function() {
$.getJSON('../update.php',function(result){
$("div#price2").html(result.price);
});
});
stock();
setInterval(stock(), 10000);
});
});
If I go directly to update.php I can view the prices as json. I think the problem lies with the update.js file but I cannot figure out what the problem is. I cannot even print Hello from update.js in the price field.
What I am trying to do is display the stocks that I have stored in the database and then update the price using ajax and javascript. Any help would be appreciated. Thanks in advance.
Use php's json functions coupled with a .getJSON to update it... Here's some example code:
// pull_stock_price.php
<?php
$return = array("content" => "New Stock Price: $2000");
json_encode($return);
?>
// Jquery to pull stock price once every 10 seconds:
function stock() {
$(function() {$.getJSON("pull_stock_price.php",function(result){
$("#StockPrice").html(result.content);
});
});
stock();
setInterval(stock, 10000);
// HTML!
<td><div id="StockPrice"></div></td>
What this does: Every 10 seconds the user's browser will pull pull_stock_price.php and will take the content provided from the json and update . You can have pull_stock_price.php pull from the database, curl or really anywhere and format the data how you want it.

Issue with accessing a value from a table with jquery

Hey guys I am trying to get a specific name from a table. Here is my code:
$(document).ready(function () {
$("#NotesAccessor").click(function () {
var notes_name = $(this).document.getElementById("#user_table");
alert(notes_name);
run();
});
});
Here is the above this is where I am trying to access the associated username with which table row was click with the #notesAccessor
Table:
.........
<td>
$csvusername
</td>
.........
<td>
";
if ($checkNotes[1] == 'No')
{
echo "None";
}
if ($checkNotes[1] == 'Yes')
{
echo "<a href='#' id='NotesAccessor'>Click to access</a>";
}
echo "
</td>
........
My question is - how do I get the $csvusername of the associated NotesAccessor so I can then send this to a dialog in Jquery and open of the notes of that one person I need to get.
Hope this makes sense.
update:
here is full table:
<table class='results'>
<tr class='firsttr' style='background:gray;'>
<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
<td>Phone</td>
<td>Username</td>
<td>Password</td>
<td>Status</td>
<td>Combined Single Limit</td>
<td>Bodily Injury Each Person</td>
<td>Bodily Injury Each Accident</td>
<td>Property Damage</td>
<td>Address</td>
<td>Notes</td>
<td>#</td>
</tr>"; $j = 0; while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { $val = 1; $csvfirst
= $row; $csvfirstname = $csvfirst['firstname']; $csvlastname = $csvfirst['lastname'];
$csvemail = $csvfirst['email']; $csvphone = $csvfirst['phone']; $csvusername
= $csvfirst['username']; $csvpassword= $csvfirst['password']; $csvstatus
= $csvfirst['status']; $csvnotes = $csvfirst['notes']; $csl = $csvfirst['Combinedlimit'];
$bodyinj = $csvfirst['bodyinjur']; $eachacc = $csvfirst['bodyinjureachacc'];
$propertydmg = $csvfirst['propertydmg']; // Select the current employees
address $psql = "SELECT MailingAdrs FROM insuranceverificationdisclaimer
WHERE TraineeUsername =:user"; $psth= $DBH->prepare($psql); $psth->execute(array(':user'
=> $csvusername )); while ($prow = $psth->fetch(PDO::FETCH_ASSOC)) { $pcheck
= $prow; $address = $pcheck['MailingAdrs']; } if ($csvstatus != "No Longer
Work Here" && $csvstatus == "Confirmed"){ //check to see if notes exist
if (empty($csvnotes)) { $checkNotes = 0; } else { $checkNotes = 1; } $memberfirstnamearray[$j]
= $csvfirstname; $memberlastnamearray[$j] = $csvlastname; $memberemailarray[$j]
= $csvemail; $memberphonearray[$j] = $csvphone; $membercsl[$j] = $csl;
$memberbodyinj[$j] = $bodyinj; $membereachacc[$j] = $eachacc; $memberpropertydmg[$j]
= $propertydmg; $memberstatus[$j] = $csvstatus; $memberaddress[$j] = $address;
$j++; $i++; echo "
<tr>
<td>$csvfirstname</td>
<td>$csvlastname</td>
<td>$csvemail</td>
<td>$csvphone</td>
<td class='user_table'>$csvusername</td>
<td>$csvpassword</td>
<td>$csvstatus</td>
<td>$csl</td>
<td>$bodyinj</td>
<td>$eachacc</td>
<td>$propertydmg</td>
<td>$address</td>
<td>"; if ($checkNotes == 0) { echo "None"; } if ($checkNotes == 1) { echo
"<a href='#' id='NotesAccessor'>Click to access</a>"; } echo "</td>
<td>$i</td>
</tr>"; } }
</table>
You are mixing pure JavaScript with jQuery, you can solve it as follows.
First of all, you can put a class to identify the <td> with $csvusername, like class='td_with_csvusername' and then do this:
$(document).ready(function () {
$(".NotesAccessor").on("click", function () {
var td = $(this).parent().parent().find(".td_with_csvusername");
alert(td.html());
});
});
Posting the output HTML is better than the PhP version but I assume you have HTML similar to this:
<table>
<tbody>
<tr>
<td>UserName</td>
<td><a href='#' id='NotesAccessor'>Click to access</a>"</td>
</tr>
</tbody>
</table>
Then you can look for the previous sibling of the parent of the anchor by using jQuery's parent() and prev(), similar to this:
$(document).ready(function () {
$("#NotesAccessor").click(function () {
var notes_name = $(this).parent().prev().html();
alert(notes_name);
//run();
});
});
DEMO - Looking to the matching username column
If the above HTML is not like that then please post the exact output as it is important for knowing how to traverse to the matching td in the same tr when you click the anchor. Assuming that is what you are trying to achieve.
Edit
Only seen your update now. I know you already have a solution but for completeness I have added to this answer anyway in case it is useful to future users.
In your sample code you already have class on the user-name cell user_table. You can use that to target instead then. Also, given you said you will have several rows with the #NoteAccessor, you should change the id="NoteAccessor" to class="NoteAccessor" as ids have to be unique or it is invalid HTML. In addition jQuery only returns the first element with a matched id.
The script which you end up with is straight forward then using parent() as before but now you can also use prevAll() specifying the class selector:
$(document).ready(function () {
// using class ".NotesAccessor" instead of id "#NotesAccessor"
// as element is repeated in each tr
$(".NotesAccessor").click(function () {
var notes_name = $(this).parent().prevAll('.user_table').html();
alert(notes_name);
});
});
DEMO - Using parent() and prevAll('.user_table')

editing with AJAX and PHP\mysql

with plenty of visits i found helpful answers from all of you and hope this also give me some idea about my problem.
Basically i'm trying to edit mysql data with ajax. i have done with following code.
Step 1- i loaded data from server with following script
$("#editselected,#addselected").live("click", function(){
var whatto=$(this).attr('id');var edit_ids = new Array();
$(".selectable:checked").each(function() {
edit_ids.push($(this).attr('name'));
});
$("#editadd").load("ajaxloads/addedit.php?idarray="+edit_ids+"&action="+whatto,Hide_Load());
//centerPopup();//loadPopup();
});
AND ITs Server DATA is
if($selectall_action=='editselected'){ ?>
<table id="main" class="editallmainwidth">
<thead>
<tr>
<th scope="col" >Vendor</th>
<th scope="col" >ItemType</th>
<th scope="col" >ItemCode</th>
<th scope="col" >ItemName</th>
<th scope="col" >SerialNo</th>
<th scope="col" >AssetCode</th>
<th scope="col" >Ownership</th>
<th scope="col" >PO</th>
</tr>
</thead>
<tbody>
<?php
$ids= split(",",$selectall_id_array);
foreach($ids as $sid)
{
$stock=mysql_query("select * FROM $region where id='$sid'");
while($q=mysql_fetch_array($stock))
{
echo "<tr>";
echo "<td width=\"5%\"><input type='hidden' name='id_all' value='{$q[8]}' /><input type='text' name='vend_all' value='$q[0]' /></td>";
echo "<td width=\"5%\"><input type='text' name='type_all' value='$q[1]' /></td>";
echo "<td width=\"8%\"><input type='text' name='code_all' value='$q[2]' /></td>";
echo "<td width=\"20%\"><input type='text' name='desc_all' value='$q[3]' /></td>";
echo "<td width=\"10%\"><input type='text' name='seno_all' value='$q[4]' /></td>";
echo "<td width=\"5%\"><input type='text' name='acode_all' value='$q[5]' /></td>";
echo "<td width=\"2%\"><input type='text' name='os_all' value='$q[9]' /></td>";
echo "<td width=\"5%\"><input type='text' name='porder_all' value='$q[12]' /> </td>";
echo "</tr>";
}
}
?>
</tbody>
</table>
<fieldset id="add">
<input type="submit" id='editall' name="Modify" value="EditAll" /> </fieldset>
Step-2 Then I edited The loaded text boxes filled with server data and send back ajax request to server
$("#editall").live("click", function(){
var id_alledit = new Array();
var vendor_alledit = new Array();
var type_alledit = new Array();
var code_alledit = new Array();
var desc_alledit = new Array();
var seno_alledit = new Array();
var acode_alledit = new Array();
var os_alledit = new Array();
var po_alledit = new Array();
var isedited=$("#editall").val();
$("input[name='id_all']").map(function(index) {
id_alledit.push($(this).attr('value'));
});
var tcount=$("input[name='id_all']").length;
$("input[name='vend_all']").map(function(index) {
vendor_alledit.push($(this).attr('value'));
});
$("input[name='type_all']").map(function(index) {
type_alledit.push($(this).attr('value'));
});
$("input[name='code_all']").map(function(index) {
code_alledit.push($(this).attr('value'));
});
$("input[name='desc_all']").map(function(index) {
desc_alledit.push($(this).attr('value'));
});
$("input[name='seno_all']").map(function(index) {
seno_alledit.push($(this).attr('value'));
});
$("input[name='acode_all']").map(function(index) {
acode_alledit.push($(this).attr('value'));
});
$("input[name='os_all']").map(function(index) {
os_alledit.push($(this).attr('value'));
});
$("input[name='porder_all']").map(function(index) {
po_alledit.push($(this).attr('value'));
});
jQuery.ajax({
type:"POST",url:"ajaxloads/addedit.php",
data:"&id_arrays=" + id_alledit + "&vend_arrays=" + vendor_alledit + "&type_arrays=" + type_alledit + "&code_arrays=" + code_alledit + "&desc_arrays=" + desc_alledit + "&seno_arrays=" + seno_alledit + "&os_arrays=" + os_alledit + "&acode_arrays=" + acode_alledit + "&po_arrays=" + po_alledit + "&ifedited=" + isedited + "&tcount=" + tcount ,
complete:function(data){
//$("#main").load("ajaxloads/addedit.php",null,function(responseText){
//$("#main").html(responseText);
//$('tr:even',this).addClass("odd");
alert(data.responseText);
//});
}
});
//disablePopup();
return false;
});
AND Updation was done with the following server side code
if(isset($_POST[ifedited])=='EditAll')
{
$id_count= $_POST[tcount];
$idarray=split(",",$_POST[id_arrays]);
$vendarray=split(",",$_POST[vend_arrays]);
$typearray=split(",",$_POST[type_arrays]);
$codearray=split(",",$_POST[code_arrays]);
$descarray=split(",",$_POST[desc_arrays]);
$senoarray=split(",",$_POST[seno_arrays]);
$acodearray=split(",",$_POST[acode_arrays]);
$osarray=split(",",$_POST[os_arrays]);
$poarray=split(",",$_POST[po_arrays]);
//print_r($idarray);
for($i=0;$i<=$id_count;$i++)
{
//echo $id_count;
echo $idarray[$i];
echo $typearray[$i];
echo $vendarray[$i];
echo $codearray[$i];
echo $descarray[$i];
echo $senoarray[$i];
echo $acodearray[$i];
echo $osarray[$i];
echo $poarray[$i];
mysql_query("update Query");
}
}
*Every thing working fine but it seems like steps for this are being used are
quite lengthy and may cause a performance issue.
i Need if some can suggest me a better way of doing all this. Or if JSON is better option? and if it is then how i can Creat A JSON with associative arrays.
Thanks*
I reccomend you use JSON to do it. If you have a JSON returned like this
{
"foo": "The quick brown fox jumps over the lazy dog.",
"bar": "ABCDEFG",
"baz": [52, 97]
}
Use jQuery to grab it like this
$.getJSON('ajax-mysql/json.php', function(data) {
$('.result').html('<p>' + data.foo + '</p>'
+ '<p>' + data.baz[1] + '</p>');
});
Update: Sending the data back to mysql. Javascript
var data = new Array();
data[0] = $("input1").val();
data[1] = $("input2").val();
data[2] = $("input3").val();
etc...
var mysql_field=new Array();
mysql_field[0] = 'field1';
mysql_field[1] = 'field2';
mysql_field[2] = 'field3';
var jq = new Array();
for(i=0;i<data.length;i++){jq[i] = mysql_field[i]+'=\''+data[i]+'\'';}
jq=jq.join('&');
you can replace data and mysql_field with the current variables you have. Now here's how you would update it with jQuery..
$(".submit").click(function(){
$.post("/ajax-update.php",'"'+jq+'"',function (output){
$("somediv").html(output); // the output on /ajax-update.php after data is submitted
});
});
and on the ajax-update.php file you could use something like
$field[0] = $_POST['field1'];
$field[1] = $_POST['field2'];
$field[2] = $_POST['field2'];
$db->query_update("table",$field,"id=1"); //update where id=1
That query is how you would do it, using this great mysql wrapper class at http://www.ricocheting.com/code/php/mysql-database-class-wrapper. Check it out it'll make your life really easy. All you do is put this at the top of your php file
require("Database.class.php");
$db = new Database("server_name", "mysql_user", "mysql_pass", "mysql_database");
for this question : "how i can Creat A JSON with associative arrays.". Try using the json_encode function.
You could also :
stop using the [deprecated] split function that uses regex and use the explode function.
use quotes on your array's call like here : $_POST[tcount] : $_POST['tcount']
while isset returns boolean, this test is quite weird : if(isset($_POST[ifedited])=='EditAll'){
stop using SELECT * FROM ... but write SELECT field1, field2 FROM ....
add a third parameter to this call : mysql_fetch_array($stock, MYSQL_NUM)
here :
foreach($ids as $sid)
{
$stock=mysql_query("select * FROM $region where id='$sid'");
try using the IN operator of the WHERE clause to avoid multi-queries.
Your code is very difficult to read because not well parsed but still, there are lots of improvements that should affect performances ...

Categories