Issue with accessing a value from a table with jquery - php

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')

Related

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]);
}

Custom simple pagination with jQuery and PHP - Finding myself stumped

So I'm working on my very first ever attempt at pagination (using simple Previous and Next buttons) on a for-fun project that I've undertaken. Below is all of the relevant code for my pagination system - I have left out the before and after, but I assure you that the table structure is valid.
Here is the jQuery I'm using with the elements I'm using to call the script:
<ul class="pager">
<li class="previous">< Previous</li>
<li class="next">Next ></li>
</ul>
<script>
$(document).ready(function() {
var page = 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
$('#pagination-prev').click(function() {
page = page - 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
});
$('#pagination-next').click(function() {
page = page + 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
});
});
</script>
When I viewed the page without the jQuery active, I saw 8 <tbody> elements filled with dummy data that had been properly classed and id'd by the PHP script. My issue is that when I view the page with the script active, it doesn't seem to be working out for me. It hides all .pagination-page elements as I want, but my output has nothing toggled to show. Below is the PHP that is generating the content that I am flipping through.
<?php
try {
$listed = $dbc->query("SELECT data1,data2,data3,data4 FROM `table` ORDER BY data3 DESC")->fetchAll(PDO::FETCH_BOTH);
$annPP = 15;
$totalRows = count($listed);
$lastPCount = $totalRows % $annPP;
$totalPages = ceil($totalRows/$annPP);
$place = 0;
for ($i=1;$i<=$totalPages;$i++) {
echo "<tbody class='pagination-page' id='page{$i}'>";
if ($i == $totalPages) {
// Only do the remaining rows
$pageMax = $place + $lastPCount;
} else {
// Do 15 rows
$pageMax = $i * 15;
}
for ($j=$place;$j<$pageMax;$j=$place) {
$row = $listed[$j];
echo "<tr>
<td style='width: 25%'>";
if ($isAdmin) {
echo '<label class="control-label"><input type="checkbox" name="delete[]" value="' . $row['0'] . '"> ';
}
echo "<a href='view.php?id={$row[0]}'>{$row[1]}</a>";
if ($isAdmin) {
echo '</label>';
}
echo "</td>
<td style='width: 60%'>{$row[2]}</td>
<td class='text-center' style='width: 15%'>";
$created = new DateTime($row[3]);
echo $created->format('Y/m/d') . "</td>
</tr>";
$place++;
}
echo "</tbody>";
}
}
?>
What did I miss? What's going on? Thanks!
Removing the .pagination-page to make my jQuery read as follows:
$("tbody[id='page" + page + "']").show;
Fixed the problem. Not quite sure I understand why this is, though.

append checkbox options to textarea that is load from database php

a user checks the type of zones and choose the type of change; this script will load the change description details from a database into a textarea field in html.
Then what I want to happend next is:
the descriptions text gets appended with the different zones the changes will take place within the html description textarea. I do not want the zones to be appended to my description data in my database. The issue is the appending of the different zones to the description field is not working..
I am using javascript to append the text. Can someone advice me why I need to correct my code?
<html>
<head>
<script language="JavaScript" type="text/javascript">
// who says we found anything? Maybe this id does not even exist.
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?change_type='+value;
data_center = [],
data_centers = "";
inputs = document.getElementsByTagName('input');
for (var x = 0, len = inputs.length; x < len; x++) {
{
if (inputs[x].type == "checkbox" && inputs[x].name == 'data_center[]') {
if (inputs[x].checked === true) {
data_center.push(inputs[x].value);
}
}
}
data_centers = (data_center.length > 0 ? ': ' + data_center.join(', ') : '') + '.';
document.getElementById('description').value += data_centers;
document.getElementById('impact').value += data_centers;
}
}
</script>
</head>
<?php
require_once("db_handler.php");
// $_REQUEST is both _GET and _POST
if (isset($_REQUEST['change_type'])) {
$change_type = mysql_real_escape_string($_REQUEST['change_type']);
} else {
$change_type = False;
}
$query = "SELECT `changeID` , `changeName` FROM `change`;";
$exec = mysql_query($query); // You need to be already connected to a DB
if (!$exec) {
trigger_error("Cannot fetch data from change table: " . mysql_error(), E_USER_ERROR);
}
if (0 == mysql_num_rows($exec)) {
trigger_error("There are no changes in the 'change' table. Cannot continue: it would not work. Insert some changeids and retry.", E_USER_ERROR);
}
$options = '';
while($row = mysql_fetch_array($exec))
{
// if the current pageid matches the one requested, we set SELECTED
if ($row['changeID'] === $change_type)
// who says we found anything? Maybe this id does not even exist.
$sel = 'selected="selected"';
else
{
// If there is no selection, we use the first combo value as default
if (False === $change_type)
$change_type = $row['changeID'];
$sel = '';
}
$options .= "<option value=\"{$row['changeID']}\" $sel>{$row['changeName']}</option>";
}
mysql_free_result($exec);
if (isset($_POST['description']))
{
$change_data = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO change ( changeID, description ) VALUE '{$change_type}', '{$change_data}' ) ON DUPLICATE KEY UPDATE description=VALUES(description);";
if (!mysql_query($query))
trigger_error("An error occurred: " . mysql_error(), E_USER_ERROR);
}
$query = "SELECT `changeID` , `changeName` FROM `change`;";
$exec = mysql_query($query); // You need to be already connected to a DB
// abbreviated unchanged code.
$query = "SELECT `description`, `impact` FROM `change` WHERE `changeID`='{$change_type}';";
$exec = mysql_query($query);
if (mysql_num_rows($exec) > 0)
{
// if it does, we're inside a textarea and we directly output the text
$row = mysql_fetch_array($exec);
$textareaDescription = $row['description'];
$textareaImpact = $row['impact'];
} else {
$textareaDescription = '';
$textareaImpact = '';
}
mysql_free_result($exec);
?>
<body bgcolor="white">
<form name="changeform" method="post" action="email_form.php">
<table>
<tr valign="top">
<td><b>Data Center</b></td>
<td><input name="data_center[]" type="checkbox" value="[Zone10]"/>[Zone10]
<input name="data_center[]" type="checkbox" value="[Zone11]"/>[Zone11]
</td>
</tr>
<tr valign="top">
<td><b>Change Type</b></td>
<td><select id="change_type" name="change_type" onChange="getData(this)""><?php print $options; ?></select></td>
</tr>
<tr valign="top">
<td><b>Description</b></td>
<td><textarea name="description" id="description" cols="50" rows="10"><?php print $textareaDescription; ?></textarea></td>
</tr>
<tr valign="top">
<td><b>Service Impact</b></td>
<td><textarea name="impact" id="impact" cols="50" rows="10"><?php print $textareaImpact; ?></textarea></td>
</tr>
<tr valign="top">
<td align="center" colspan="2"><input type="submit" value="submit change" /></td>
</tr>
</table>
</form>
</body>
</html>
The following lines look like there might be something wrong:
for (var x = 0, len = inputs.length; x < len; x++)
{
{
Unless that is syntax that I'm just not familiar with.
Is there any way you could show us the actual code, running? Looking at something like this is a bit hard to digest without being able to see it in action.

Multiple countdown timers using a PHP loop

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>';

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