I have php code that creates a table. For each item on the purchase order a new row is created and populated. The goal is when the purchase order is edited it gets posted back and saved in the database. Everything is working except my jQuery code will only iterate over the first row for however many rows I have. (So if I have three rows it will print the first rows cartid three times.)
Sorry if things look messy.
PHP Code:
<?php while($row = mysql_fetch_array($itemsquery)){?>
<tr class="item-row" id="<?php echo $row['cart_id']?>">
<td class="item-name"><div class="delete-wpr"><textarea><?php echo $row['on0'];?> <?php echo $row['itemname'];?></textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><textarea class="cartid"><?php echo $row['cart_id'];?></textarea></td>
<td><textarea class="cost" class="text-input" type="text"><?php echo $row['itemprice'];?></textarea></td>
<td><textarea class="qty" type="text" name="name"><?php echo $row['quantity'];?></textarea></td>
<td><span class="price" type="text">$<?php
$linecost = $row['quantity'] * $row['itemprice'];
echo $linecost;?></span></td>
</tr>
<?php }?>
jQuery statement to see what it has grabbed:
$(document).ready(function(){
$(".item-row").change(function() {
$((".cartid")).each(function(){
row = {
cartid: $(".cartid").val()
}
alert(row.cartid);
performAjaxSubmission();
})
});
It looks like you just have your selectors mixed up. You are wanting to iterate over each of the rows, but your selector is referencing $(".cartid"), which would always return the first result ever time.
This should fix your problem:
$(document).ready(function(){
$(".item-row").change(function() {
$(".item-row").each(function(){
var rowContext = $(this);
var row = {
cartid: $(".cartid", rowContext).val()
}
alert(row.cartid);
performAjaxSubmission();
});
});
You have extra () in your .cartid selector.
$(document).ready(function(){
$(".item-row").change(function() {
$(".cartid").each(function(){
row = {
cartid: $(".cartid").val()
}
alert(row.cartid);
performAjaxSubmission();
})
});
Also, shoudn't you be looping trough .item-row instead of .cartid?
You're iterating like this:
$(".cartid").each(function(){
row = {
cartid: $(".cartid").val()
}
Seems like you should be doing
$(".cartid").each(function(){
row = {
cartid: $(this).val()
}
Haven't checked the rest of the code.
EDIT:
$(".cartid").each(function(){
var cart = $(this);
row = {
cartid: cart.val()
}
Related
i'm printing a table in php where data is coming from mysql now i'm creating functionalities like searching and sorting so when i click on sort it sorts the data and when i click on search i get searched data now the problem is i want to perform sorting on searched data like for example i sorted the data and then i searched for words starting with a i.e i got results like adam,azan,anand so i want to perform resorting on these searched data and get data as adam,anand,azan
my approach is:
<?php
if(isset($_GET['search_btn'])){
$search=$_GET['search'];
$result=GetWords(mysqli_escape_string($conn,$search));
}
/*if(isset($_GET['q'])){
$id=$_GET['q'];
$result=GetWordsById($id);
}*/
if(isset($_GET['sort'])){
$sort=$_GET['sort'];
}
if(isset($_GET['sort'])){
if($sort=="asc"){
$result=SortContent();//Here Get Sort Content is a function calling Store Procedure SortContent which is working at first sorting
}
if($sort=="desc"){
$result=SortContent2();
}
}
else{
$result=GetAdminWords();
}
if(mysqli_num_rows($result)>0)
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<?php
while($row=mysqli_fetch_array($result)){
?>
<tbody>
<tr>
<td><?php echo $row['word'];?></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td><i class="fa fa-edit"></i> <a onClick="javascript: return confirm('Please confirm deletion');" href="view.php?id=<?php echo $row['id'];?>"><i class="fa fa-trash"></i></a> </td>
</tr>
</tbody>
<?php
}?>
and i'm talking in context of large amount of data i hope i have made myself clear and if possible how can i implement ajax using mysqli
You will need to trigger an event in JavaScript, which in turn will use your HTML search input, which is then sent to the server, where a query will be executed and the results returned (as HTML) to the JavaScript code, and finally placed back on the page. At least this is how I solve my ajax searches...
So the flow could be something like:
Input -> JavaScript event -> ajax -> result -> page
Here is some code that might get you started, though I haven't tested i myself:
HTML:
<input type="text" id="my_search_input">
<div id="my_search_result"></div>
JS (jQuery):
var $inputField = $( "#my_search_input" );
var $result = $( "#my_search_result" );
$inputField.on('keyup', function(){ //triggered when a pressed key is lifted
var searchTerm = $inputField.val();
$.ajax({
url:"/mySearch.php",
method:"post",
data:{searchTerm:searchTerm},
success:function(response){ //response contains the data from mySearch.php
var parsedResponse = JSON.parse(response);
var resultHtml = parsedResponse.html; //this is the array key of what the PHP script returns
$result.append(resultHtml);
}
});
});
PHP
$searchTerm = $_POST['searchTerm']; //$_POST['searchTerm'] is what we defined in data:{... in the ajax call
// here is where you need to retrieve data from your database
// the db result needs to be processed into HTML and assigned to a variable
$html = "<div>My result based on data</div>";
return json_encode(['html' => $html]);
I have a problem.
an array would return me some dynamically data from it.
<?php
foreach($ItemArray as $key => $value) {
echo '
<tr><td height="30" valign="middle">'.$value['nr'].'</td>
<td valign="middle">'.$value['product'].'</td>
<td valign="middle">'.$value['describe'].'</td>
<td valign="middle" id="price_'.$key.'">'.$value['price'].'</td>
<td valign="middle" class="box_darker" id="amount_'.$key.'">
<input name="Field_Amount_'.$key.'" id="Field_Amount_'.$key.'" class="Field_Amount" type="text" /></td>
<td valign="middle" id="price_'.$key.'">$key</td></tr>'; }
;?>
Now I would test if the value returns me the right one when click on belong field (td/price)
$(document).on('click', '[id^=price_]', function(){
var Amount = $('[id^=Field_Amount_]').val();
alert(Amount);
});
But nevermind wich field (td/price) in each row I click, it alert me only the value from first row! maybe because the data loads dynamically?
Sorry for that poor English.
That's because you perform your second search on the global scope as well, and val() will return the value from the first element. Use $(this).parent().find() instead:
$(document).on('click', '[id^=price_]', function(){
var Amount = $(this).parent().find('[id^=Field_Amount_]').val();
alert(Amount);
});
Alternately, you should also be able to use .closest():
$(document).on('click', '[id^=price_]', function(){
var Amount = $(this).closest('[id^=Field_Amount_]').val();
alert(Amount);
});
Your trigger event is working fine since every row reacts to the click.
What's "wrong" is the selector for the Field_amount. This always selects the first Field_Amount_ because the selector is working on the whole page.
Try using the .closest() function:
$(document).on('click', '[id^=price_]', function(){
var Amount = $(this).closest('[id^=Field_Amount_]').val();
alert(Amount);
});
Try This
$(document).on('click', '[id^=price_]', function(){
var key = $(this).attr('id').split('price_');
var amount = $("#Field_Amount_"+key[1]).val();
});
I am fetching a problem though I know it's not a big issue, but something is different to me as I new. I have a page which has a list of records, fetching from a database. Now one button is there , after clicking the records, one pop up will be opened up along with some data. Inside that pop up one another link is there called "restore", whenever , that linked will be clicked out the database has been updated. Now up to this its okay for me. But whenever, I close the pop up, my list of records should automatically changed as some records have been restored. But I am not getting the result until and unless I do not refresh the page. so how can I do this, please help me ....
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "restore-request-process.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
//return false;
});
});
in the restore-request-process.php page I just update the database and echo the id.
After the database update, call a function to update the front end or simply reload page using location.reload()
you need to have declared global function in parent window
function Update(){
//global function in parent, update div
}
on popup window call function
window.opener.Update();
that will automatic reload your div, and not all page, If it's not necessary
Suppose this is your listing format
<table>
<?php
foreach($results as $result) { ?>
<tr id="my_div">
<td><?php echo $result->name?></td>
<td class="delete" id="<?php echo $result->id?>"><img src="delete.png"/></td>
</tr>
<?php } ?>
</table>
In restore-request-process.php write a query which fetch all the result from database and just echo the result like this
$result = mysql_query("SELECT * FROM my_table");
while($row = mysql_fetch_array($result))
{
echo '<td>'. echo $row["name"].'</td>
<td class="delete" id="'. echo $row["id"].'"><img src="delete.png"/></td>' ;
}
and onsuccess replaced all the content inside the my_div with response text
CODE IS NOT TESTED
for more references you can go through this link
I'm an absolute beginner in the HTML/Php/JavaScript world. I'm trying to make this page:
dropdown list with titles of documents
when something is selected, populate input fields below with data from PostgreSQL to allow for update
submit button to update database with corrected values from user.
1 and 3 are ok (already tried this with an insert-only form).
My code looks like this (simplified, without dbconn):
echo "<select name='listedoc' size=1>";
while ($ligne = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo '<option value="'.$ligne['id_doc'].'">'.$ligne['doc_titre']. '</option>';
}
echo "</select>";
The input fields (simplified, there are 4 fields actually):
<p><form name="saisiedoc" method="post" action="docupdins.php"></p>
<table border=0>
<tr><td>Texte</td>
<?php
echo '<td> <textarea name="content" cols="100" rows="30"></textarea> </td>';
?>
</tr><tr>
<td colspan=2>
<input type=submit value="Valider la saisie" name="maj"> </td>
</tr>
</table>
</form>'
Then JQuery script :
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
});
});
</script>
The php to select fields (docsel.php):
<?php
include('../scripts/pgconnect.php');
$iddoc = $_POST['id'];
$sql="SELECT * FROM document where id_doc = $iddoc";
$result = pg_query($db, $sql);
if (!$result) {
echo "ERREUR<br>\n";
exit;}
$row = pg_fetch_row($result);
$doctyp = $row[1];
$doctitre = $row[2];
$docauteur = $row[3];
$doccontent =$row[4];
pg_free_result($result);
pg_close($db);
}
?>
Whatever I do, I can't get back values. I tried value="'.$doctitre'" in the input,
echo $doctitre, to no avail . Is my code logic correct ? Thank you for your help
you are close. the script docsel.php needs to return the data to the html-page.
you have it already setup to receive the data in the callback function
$.post("docsel.php", {id:id},function(data) {
$('textarea[name="content"]').text(data.content);
});
in order to have something in data.content, the php script sends json data:
$result = [];
$result['content'] = $doccontent;
echo json_encode($result);
maybe you need to read the docs on $.post and json_encode... good luck.
There are a couple of things you need to change here.
Firstly, and most importantly your docsel.php script has a gaping security hole. You should never ever ever place unsanitised input e.g. directly from a user, straight into a SQL query because it allows for SQL injection. Essentially, SQL injection allows a malicious user to end the programmers query and submit their own. To get round this you must sanitise any user input - so in this case pass the user input through the function pg_escape_literal() before putting it into your query.
Secondly, your docsel.php script must put out some kind of output for the AJAX request. You can do this by using echo and I would recommend you encode it into JSON. Code example:
$return_vals = array("doctype" => $doctyp, "doctitle" => $doctitre, "docauthor" => $docauteur, "doccontent" => $doccontent);
echo json_encode(array("document" => $return_vals));
Lastly, in your jQuery script, you aren't actually doing anything with the data that is returned from your AJAX post request. Inside the callback function, you need to then add the returned fields to your select dropdown. Code example:
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
//FILL THE DROPDOWN HERE
$(data).each(function(elem) {
$("#dropdown-id").append("<option value='" + elem.doctitle + "'>" + elem.doctitle + "</option>");
});
}, "json");
});
</script>
A mute and pedantic point, but when making requests for content then you should be using GET instead of POST.
I have a table created with PHP from an Sql Database that successfully displays the table information
using the following code example.
<table class="mytable loottable" id="guildmembers">
<?php
$query = mysql_query("SELECT $member.charname, $member.char_lvl, $trskill.skill_desc, .....
if (mysql_num_rows($query) > 0) {
while (false !== ($row = mysql_fetch_assoc($query))) {
echo '<tr id="'.$row['charname'].'">'; <-- setting row id here
echo '<td class="lootrow" id="memth1">'.$row['charname'].'</td>';
echo '<td class="lootrow" id="memth2">'.$row['rank_desc'].'</td>';
echo '<td class="lootrow" id="memth3">'.$row['class_name'].'</td>';
echo '<td class="lootrow" id="memth4">'.$row['char_lvl'].'</td>';
echo"</tr>\n";
}
mysql_free_result($query);
}
?>
</table>
Example of page source where i have verified that each table row is assigned the correct id.
<tr id="Calysta"><td class="lootrow" id="memth1">Calysta</td><td class="lootrow" id="memth2">Guild Leader</td><td class="lootrow" id="memth3">Inquisitor</td></tr>
<tr id="Rynanx"><td class="lootrow" id="memth1">Rynanx</td><td class="lootrow" id="memth2">Guild Leader</td><td class="lootrow" id="memth3">Mystic</td>
I am setting each table ROW ID to the first field which is always unique. Then i am trying to use this
ID in the following function to redirect users to a profile page when they click on a row in the table.
<script type="text/javascript">
$(document).ready(function () {
$("table.mytable").each( function() {
table = $(this);
if ($(table).attr("id")=="guildmembers") {
$(this).click(function(){
window.location.href = "http://eq2players.com"+
"/Kithicor/" + $(this).attr("id") + "/";
});
}
})
});
</script>
Which should open a new page in the browser with the following address for instance if the
first row is clicked : "http://everquest2.com/Kithicor/Calysta/"
Instead no matter which row is clicked the web url being created
is "http://everquest2.com/Kithicor/guildmembers/"
which is the Tables ID. not the ID of the row being clicked. I have tried various solutions
and cannot figure how to get the row ID in this click function. Any help with this would
much appreciated. Thanks.
Here you go, just did this quick, changed some things, please be mindful of using duplicate id's its BAD, you shouldn't. Also you over complicated your Javascript:
HTML EXAMPLE:
<table class="mytable loottable" id="guildmembers">
<tr class="linkRow" id="test1">
<td>test1</td>
</tr>
<tr class="linkRow" id="test2">
<td>test2</td>
</tr>
<tr class="linkRow" id="test3">
<td>test3</td>
</tr>
</table>
jQuery:
$(document).ready(function () {
$(".linkRow").each( function() {
id = $(this).attr("id")
$(this).click(function(){
window.location.href = "http://eq2players.com"+
"/Kithicor/" + id + "/";
});
});
});
jsFiddle Link:
http://jsfiddle.net/TJBX5/
You are installing your click handler on the table. Therefore, when you call $(this).attr("id"), you are asking for the table's id. You need to install the click handler on each row in the table.