Hi my HTML list with Buttons linked to Ajax script is only picking up on the first line.
PHP Page
<?php
$sql="SELECT * FROM scanns WHERE `site` = '$csite' AND `date` BETWEEN '$sdate' AND '$edate' ";
$result_set=mysqli_query($link,$sql);
while($row=mysqli_fetch_array($result_set))
{
?>
<tr>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['site']; ?></td>
<td><?php echo $row['file_name']; ?></td>
<td>view scann</td>
<td>
<input class='date' type='hidden' value= "<?php echo $row['date']; ?>"/>
<input class='site' type='hidden' value= "<?php echo $row['site']; ?>"/>
<input class='filename' type='hidden' value= "<?php echo $row['file_name']; ?>"/>
<input class="submit" type="button" value="Delete Scan">
</td>
<td>
<input class="stamp" type="button" value="Post File">
</td>
</tr>
<?php
}
?>
</table>
Ajax call
$(document).ready(function(){
"use strict";
$('.submit').click(function(){
var date = $('.date').val();
var site = $('.site').val();
var filename = $('.filename').val();
var dataString = 'date='+ date + '&site='+ site + '&filename='+ filename;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "cscanndelete.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
return false;
});
$('.stamp').click(function(){
var date = $('.date').val();
var site = $('.site').val();
var filename = $('.filename').val();
var dataString = 'date='+ date + '&site='+ site + '&filename='+ filename;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "scanstamp.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
return false;
});
});
If you click on any of the buttons it only pickups the values of the first line not sure how to fix or even if i can.
$('.date').val() will return the value of the first matching element. Since there are many matching elements on the page, it's always returning that first table row.
You're in the context of the $('.submit') selector, so you can use that as a starting point to traverse the DOM and find the specific element you want. Something like this:
var date = $(this).closest('tr').find('.date').val();
That should start at this (the submit button), examine up to the containing tr (which has all of the elements you're looking for in this case), and then find the matching element(s) just within that context. As long as there's only one .date element within that parent tr, it'll return the value from that one element.
In your case you may also make use of something like .prev('.date'), or only traverse up to the td instead of the tr, etc. There are a number of ways to go about it, depending on how robust it may need to be if the markup changes slightly.
$('.date').val()
will always return the value of the first matching element. If you want to get the value of the clicked element, you can do it like this:
$('submit').click(function(){
$(this).closest('input').find('.date').val();
$(this).closest('input').find('.site').val();
... });
Related
I have a problem with my code. I have a php script where i, in a while, i write a table in html with html name and html value attr with the data of database, like the printscreen above
My table was assembled with input inside the TDs, to be able to "edit" directly in the table, without MODAL or redirection
</thead>
<tbody id="corpoTabela">
<?php
$i = 1;
while ($row = mysqli_fetch_array($result)) :;
?>
<tr>
<form name="presencaForm" id="presencaForm" method="POST">
<input type="hidden" id="idcrmmedico" name="idcrmmedico" value="<?php echo $row['id']; ?>"></input>
See that the opening of the form tag is inside the while, that is, for each row of the table, for each TR, I have a form (all with the same name)
The end of the form tag still inside php while. The Button, who receives the ID referring to the record in the DB, has the same name of the form
<td><button id="d" name="presencaForm" value="<?php echo $row['id'] ?>" class="btn btn-sm btn-info">Atualizar</a></td>
<td>
<button type="submit" id="" name="deletamedico" class="btn btn-sm btn-danger">Excluir</button>
</td>
</form>
</tr>
<?php
endwhile;
}
?>
</tbody>
This is my ajax script, which updates the data in the database without refreshing the page and returning me a success message.
<script>
$(document).ready(function() {
$('#presencaForm').on('submit', function(event) {
event.preventDefault();
$("#alert").css('display', 'none');
console.log("Botão Clicado!");
$.ajax({
url: "DAO/medico/update.php",
method: "POST",
data: $(this).serialize(),
dataType: "json",
success: function(data) {
if (data[0] == true) {
$("#success").html('Médico ' + data[1] + ' atualizado com sucesso');
$("#success").show();
setTimeout(function() {
$("#success").hide();
}, 5000);
}
}
})
});
});
</script>
The problem is that if i try to refresh the second line, the page just refreshes.
I used the code below to check, and I saw that all buttons return only the first record in the LOG.
Is there any way to update the data as I want, right in the table?
$(document).ready(function() {
$("button[name='presencaForm']").on("click", function(event) {
event.preventDefault();
for (var i = 1; i < document.getElementById("dataTable").rows.length; i++) {
console.log($('#idcrmmedico').val());
}
var val = document.getElementById('d').value;
var x = document.getElementById("dataTable").rows.length;
});
id is unique,if you want to control a group of form,you can use class.
For example:
<form class="presencaForm" method="POST">
Then in your javascript:
$('.presencaForm').on('submit', function(event) {
Input fields and delete buttons are produced by a php foreach loop!
To grab the value of an input and send it to php i use code below:
Html:
<input type="hidden" name="file_id" id="<?php echo $file_id; ?>" value="<?php echo $file_id; ?>" />
<button class="btn btn-sm btn-danger delete" type="submit" name="delete_file">Delete</button>
jquery:
$(document).on('click' , '.delete' , function() {
var file_id = $('#<?php echo $file_id; ?>').val();
$.ajax({
url: "admin.php",
method: "POST",
data: {
file_id : file_id
},
success: function(data) {
$('.result').html(data);
}
});
});
php:
if(isset($_POST["file_id"])) {
echo $_POST["file_id"];
}
Problem: When i submit (delete),it grabs always the value from the first input field.
How can i make this work, so when i choose the second delete, that it grabs the value from the second input field?
Instead of
var file_id = $('#<?php echo $file_id; ?>').val();
use
var file_id = $(this).prev().val(); // according to provided markup
This will select previous element to the <button> (which is the hidden <input>), and takes its value.
I have a little problem with my AJAX jQuery script and n number of forms...To be more precise, PHP script generate N number of forms (form include one textarea and one button), and in head tag I included jquery script. Problem is that jquery work only for first form and not with others (second, third...). I needed to work with all forms...This is the code:
<script>
$(document).ready(function() {
$("#submitForm").click(function() {
var text = $("#comment").val();
var id = $("#id").val();
$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}
});
});
});
</script>
And this is PHP code
for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>
<textarea id='comment'></textarea>
<input type='hidden' id='id' value='".$id."'/>
<input type='button' id='submitForm' value='Add Comment'>
</div>";
}
What is problem???
On your PHP side you should change with something similar to this to ensure that all the html elements has a unique id.
for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>
<textarea id='comment".$i."'></textarea>
<input type='hidden' id='id".$i."' value='".$id."'/>
<input type='button' id='".$i."' class='submitForm' value='Add Comment'>
</div>";
}
and change the Javascript with something similar to this to reflect the changes made on the php side
<script>
$(document).ready(function() {
$(".submitForm").click(function() {
var formNumber = $(this).attr("id"); // Get the form number that was clicked, the id attribute of the clicked button
var text = $("#comment"+formNumber).val(); // Get the comment of that particular form
var id = $("#id"+formNumber).val(); // get the id of that particula form
$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}
});
});
});
</script>
For every form you're creating you're using the same ID.
IDs must be unique and only appear once on the page.
You should use a class instead as suggested in the comments.
So more like this:
<?php for ($i = 0; $i < $num; $i++): ?>
<div>
<textarea class="comment"></textarea>
<input type="hidden" class="id" value="<?php echo $id; ?>">
<input type="button" class="submitForm" value="Add Comment">
</div>
<?php endfor; ?>
I'm not sure where your $id variable comes from.
Your JavaScript will need to be updated as well to work with this, I'd do something like this (elaborated so you can see what's going on):
$('.submitForm').click(function(e) {
e.preventDefault(); // stops the default form action (if there is one)
var $submitButton = $(this);
var $div = $submitButton.parent(); // gets the div container
var id = $div.find('.id').val();
var text = $div.find('.comment').val();
// now do your ajax
});
I have buttons and divs and in each part I have them with the same ID I want to get the ID of button and use it for refreshing the div html.how should I write the * section?
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
*********I HAVE PROBLEM HERE**************
$('how to get the id of the div from var id of button above?').html(html);
}
});
});
});
Div:
Downloaded:<div id="<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
Button:
<input type = "button" value="Download" class="button" id="<?php echo $id; ?>" name="dl">
If I get class It will update the whole divs I want to update just the div realted to the button
You cannot have the same id on both the button and the div, id values must be unique in a document.
What I'd probably do is put the div's id on the button as a data-divid attribute (all attributes with the prefix data- are valid on all elements as of HTML5, and harmless in earlier versions of HTML), like this:
<input type="button" value="Download" class="button" data-divid="<?php echo $id; ?>" name="dl">
Then change
var id=$(this).attr('id');
to
var id=$(this).attr('data-divid');
...and then use that id var in your success callback (as the callback is a closure created within the context where id is defined, and so the callback has access to id).
Here's a simple example: Live copy | source
HTML:
<div id="div1">This is div1</div>
<div id="div2">This is div2</div>
<div>
<input type="button" data-divid="div1" value="Update div1">
<input type="button" data-divid="div2" value="Update div2">
</div>
JavaScript:
jQuery(function($) {
$("input[type=button]").click(function() {
var id = $(this).attr("data-divid");
// I'll use setTimeout to emulate doing an ajax call
setTimeout(function() {
// This is your 'success' function
$("#" + id).html("Updated at " + new Date());
}, 10);
return false;
});
});
Use the id but prefix them then build the name up...
<div id="div_<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
button:
<input type = "button" value="Download" class="button" id="<?php echo $id; ?>" name="dl">
Then in you're code you have the id used in the buttons already (and also it will be div_), so you can then in you're 'success' just do:
$("#div_"+id).html(html);
change your html to this:
Downloaded:<div id="<?php echo $id; ?>" class="downloaded" ><?php echo $downloadcount;?></div>
then do something like:
var element_id = $(".downloaded").prop("id");
if(element_id = this.id){
$("#"+element_id).html(/* ... */);
}
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
$('.count-' + id).html(html); // for class
}
});
});
});
<div class="count-<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
First of all avoid using same IDS.
Then you can use CSS selectors:
$('div.class') //div
$('input[type="button"].youridclass')
You cannot use the id attribute for that purpose, the id cannot be a number (valid html) and thereby id's needs to be unique. Use the data attrib instead.
Try something like:
$('.button').attr('id');
to get the id of the button, then to change it:
$('.button').attr('id',''); //delete previous id if existing
$('.button').attr('id','yourNewId'); //set new id
then to use the new id:
$("#yourNewId").doSomething();
First and foremost, ids should be unique, you'll run into problems, particularly when using jQuery, if you have elements with the same id.
Without seeing your markup it's hard to give you a working example. But you can get the id of the div which corresponds to the clicked button by traversing the DOM.
Example markup:
<div id="example-div">
<input type="button" value="Example" />
</div>
jquery
$('input[type="button"]').click(function() {
console.log($(this).parent('div').prop('id'));
});
// outputs 'example-div'
for your reference check the below link for the various ways that you can use to select the dom elements given the parent element.
jsperf.com/jquery-selectors-context/2
I'm writing a store system for my game,
it worked quite well until I found out that it only takes the amount of first entered Item.
function pbuy(buyitem) {
var amountc = "amount-"+buyitem,
var amount = $("#"+amountc+"").val();
$.ajax({
type: "POST",
url: "store2.php",
data: "buyitem="+ buyitem+"&amount="+amount,
success: function(resp){
document.getElementById('ajaxDiv').innerHTML = resp;
},
error: function(e){
alert('Error: ' + e);
}
});
}
I'm trying to give it it the Id of the form like so:
function pbuy(buyitem) { var amountc = "amount-"+buyitem, var amount = $("#"+amountc+"").val();
But nothing happens.
The code the creation of the forms is:
<tr>
<td class='items' width='80%' align='center' valign='top'>
<?PHP echo $itemstore->itemname;?>
</td>
<td width="20%">
Price:<?PHP echo $itemstore->newprice;?>
<form method="post">
<input type='text' id='amount-<?PHP echo $row;?>)' />
<input name="itembid" type="button" onclick="pbuy(<?PHP echo $row;?>)" value="Buy" />
</form>
</td>
</tr>
If I hardcode the amount in the ajax function it all runs fine like it should.
You're getting a javascript error before the AJAX-request is being sent since you are defining your amountc and amount variables separated by a comma. Either do
var amountc = "amount-"+buyitem;
var amount = $("#"+amountc+"").val();
semicolon separated, or keep the comma and skip the second var
var amountc = "amount-"+buyitem,
amount = $("#"+amountc+"").val();
Did you checked the response of the AJAX request?