I have a php script that creates a table and each id in the table has an edit button. The edit button looks like this.
<button data-siteid="'.$row->site_sn_id.'" class="btn btn-link p-0 m-0" style="font-size:.7rem" id="editBtn" type="button" >Edit</button>
The number of buttons varies but I am trying to get the data-siteid passed to an ajax call like this.
$("#editBtn").on("click", function(){
var siteID = $(this).data('siteid');
$.ajax({
method: "POST",
url: "edit-modal.php",
data: {siteID: siteID}
})
.done(function( msg ) {
$('#editModal').modal('show');
$("#bodyContent").html(msg);
});
});
Its working on the first edit button of the table but it does nothing after that first button. It wont even open the modal.
The reason is because ID should be unique across your HTML page and it looks like you're defining multiple elements with the same ID.
So, instead, try adding and using a class selector:
<button class="... editBtn" ...
$(".editBtn").on("click", function() {
...
Related
How to update multiple data using AJAX ?
Example :
TableA
id : 1, 2
name : Jack, John
It's only working with id 1, when I am trying to edit name for id 2 it's not working.
I have try with this code but failed.
HTML/PHP :
...
while($row=mysqli_fetch_array($query)){
echo'
<form class="btn-group">
<input type="text" class="form-control" name="id_user" id="id_user" data-user="'.$row['id'].'" value="'.$row['id'].'">
<input type="text" class="form-control" name="id_status" id="id_status" data-status="'.$row['id'].'" value="'.$row['id'].'">
<button type="submit" id="likestatus" class="btn btn-primary btn-outline btn-xs"><i class="fas fa-thumbs-up"></i></button>
</form>
';
}
AJAX :
$(document).ready(function(){
$("#likestatus").click(function(){
var id_user=$("#id_user").data("user");
var id_status=$("#id_status").data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
The problem with your code is that ids should be unique, but in the loop you create elements with same id.
Use this in the event handler to find the siblings of the button that has been clicked - closest returns the parent of type form.
$(document).ready(function(){
$(".btn-primary").click(function(){
var $form = $(this).closest('form');
var id_user=$form.find('[name="id_user"]').data("user");
var id_status=$form.find('[name="id_status"]').data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
You might want to use your own class instead of .btn-primary because this affects all buttons on the page.
Judging from the incomplete PHP, it appears as if you're not assigning to $ruser within your loop. This would mean you're always posting the same id to like-status.php.
PS: Would've posted as comment, but I can't.
Make your ID unique so make them dynamic
<?php
$counter = 0;
while($row=mysqli_fetch_array($query)){
$counter++;
echo'
<form class="btn-group">
<input type="text" class="form-control" id="userid_$counter" data-user="'.$ruser['id'].'" value="'.$ruser['id'].'">
<input type="text" class="form-control" name="id_status" id="status_$counter" data-status="'.$rtimeline['id'].'" value="'.$rtimeline['id'].'">
<button type="submit" id="likestatus_$counter" class="btn btn-primary btn-outline btn-xs"><i class="fas fa-thumbs-up"></i></button>
</form>
';
}
?>
Then
<script type="text/javascript">
$(document).ready(function(){
$('[id^="likestatus_"]').on('click',function(){
var index = $(this).attr('id').split("_")[1];
var id_user=$("#user_"+index).data("user");
var id_status=$("#status_"+index).data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
You're using the id's multiple times. Thus your query for var id_user=$("#id_user").data("user"); always finds the first input field on the page. You should avoid using the same id multiple times on one page (see this Question).
You may subscribe to the jQuery submit event of the form and then search for the input fields within that form, to properly extract the id_user and status_user values. For that you have to add an appropriate event listener to the <form> element. To find the form I would recommend adding a css-class like like-status-form.
$(document).ready(function(){
// We're attaching a submit-event listener to every element with the css class "like-status-form"
$(".like-status-form").submit(function(event){
// Form get's submitted
// Prevent that the Browser reloads the page
event.preventDefault();
// Extract the user id and status from the form element (=== $(this))
var id_user = $(this).find('[name="id_user"]').data('user');
var id_status = $(this).find('[name="id_status"]').data('status');
// TODO Perform AJAX Call here
});
});
To detect the form elements one can use the jQuery Attribute Equals Selector.
Find a working example at https://jsfiddle.net/07yzf8k1/
I have the user reaction to a post thingy am working on.
it consist of
<button name="like" data-post-id="123">like</button>
<button name="dislike" data-post-id="123">dislike</button>
<button name="not bad" data-post-id="123">not bad</button>
<button name="crazy!" data-post-id="123">crazy!</button>
is there any way to submit this with out individually wrapping the buttons in a form?
You can bind an event listener to your buttons and use AJAX to handle the request.
Example using jQuery:
$('.btn').on('click', function(e){
e.preventDefault();
var name = $(this).attr('name');
var id = $(this).attr('data-post-id');
$.post( "/path/to/file", { name: name, id: id }, function(response){
console.log(response);
} );
})
I'm trying to add AJAX pagination to my calendar, to avoid reloading the entire site as the calendar is located in a secondary tab, that reset to the primary tab on a reload.
Usually my "NEXT MONTH"-button would be wrapped in a link, that refreshed the same page with a GET-value of the date like this:
<a href="?date=<?php echo $nextDate; ?>">
<button type="button" class="btn">
NEXT MONTH
</button>
</a>
Which works just fine. But when I'm trying to pass the $nextDate value in a form to AJAX, and reload the page, it's as though it's not picking up the POST-value.
HTML:
<form method="post">
<input type="hidden" class="form-control" name="the_date" value="<?php echo $prevDate; ?>" />
<button type="button" data-name="next-month" class="btn">
NEXT MONTH
</button>
</form>
Javascript:
$("body").on( "click", "[data-name='next-month']", function() {
var the_date = $(this.form).find(".form-control[name=the_date]").val();
ajaxRequest = $.ajax({
type: "POST",
url: "index.php",
data: { the_date: the_date}
}).done(function (result) {
alert(the_date)
$("#calendar_container").load("index.php #calendar_container");
})
});
Am I going about this the right way, or is there some sort of reason why POST-values aren't picked up when sending them to the same url? If you have any suggestions as to how I can solve this, it would make my day!
When you are sending data write parameter name as a string constant.
data: { "the_date": the_date}
not
data: { the_date: the_date}
You making ajax request twice. The second without any parameters.
So replace next line
$("#calendar_container").load("index.php #calendar_container");
with
$("#calendar_container").html(result);
Thanks for reading.
I'm trying to improve so I'm doing an example project to improve. I made a simple. voting system. I have number of contents which displayed by php each of them have up or down vote button. by the way I use twitter bootstrap.
this is the html code:
<html>
<button type="submit" class="btn btn-mini upvote" id="'.$data['ContentID'].'">
<i class="icon-arrow-up"></i>
</button>
<span id="voteresponse">'.$data['VoteSum'].'</span>
<button type="submit" class="btn btn-mini downvote" id="'.$data['ContentID'].'">
<i class="icon-arrow-down"></i>
</button>
</html>
the problem is when I lick up button which is class="upvote" all other buttons does same thing. because the data populated by php there are many of them.
this is my javascript.
<script>
jQuery(document).ready(function($){
$('.upvote').click( function(event) {
event.preventDefault();
$("#voteresponse").html('');
var voteID = $(".upvote").first().attr("id");
$.ajax({
url: "/ajax.php?Page=votetitle",
type: "post",
dataType: "json",
data: {id : voteID},
success: function(data, textStatus){
if(data.success == 'true'){
$('#voteresponse').html(data.message);
return true;
}else{
$('#voteresponse').popover({
title: 'Hata!',
content: data.message
});
}
},
error:function(){
$('#voteresponse').popover({
title: 'error!',
content: 'Server error'
});
}
});
});
});
</script>
and the php code is just usual database request.
<?php
if ( $_SESSION['UserID'] <1 )
die( print_r(json_encode(array('success'=>'false', 'message'=>'error for user!'))) );
print_r(json_encode(array('success'=>'true', 'message'=>$_POST['id'])))
?>
you can see the action here. if you click one of them all other up arrows do same thing. also is this approach right?
thanks. best regards
Only the first one "responds" when you click any of them... This is likely because of var voteID = $(".upvote").first().attr("id"); The voteID should be something like $(this).attr('id'); instead.
Note that you need to recognize which button was clicked, you can use for example $(this).parent()... That will give you to the upper DOM level of the clicked button (div media isotope-item) and from there you can modify only the content of that div.
try changing
var voteID = $(".upvote").first().attr("id");
to this
var voteID = $(this).first().attr("id");
or
var voteID = $(this).attr("id");
I have this page which let the user to decide yes or no. So I'm using Jquery Ajax so the user won't have to refresh his page. I have provided the button so the user may chose 'Yes' and immediately the button change to 'No'.
I represent '0' and '1' in mysql to indicate 'No' and 'Yes'. So when the user click the button, mysql will update the record '1' or '0'.
I managed to update the mysql by first click, but when come to second click, mysql won't take the order.
Here's my Jquery Ajax code:
<script type="text/javascript">
$("document").ready(function()
{
$(".roundbox_blue").click(function()
{
$(this).toggleClass("roundbox_orange roundbox_blue");
var element = $(this);
var noteid = element.attr("value");
var info = "report="+noteid;
$.ajax({
type: "POST",
url: "mcr_external_gen.php",
data: info,
success: function(msg){
}
});
});
$(".roundbox_orange").click(function()
{
$(this).toggleClass("roundbox_blue roundbox_orange");
var element = $(this);
var noteid = element.attr("value");
var info = "not_report="+noteid;
$.ajax({
type: "POST",
url: "mcr_external_gen.php",
data: info,
success: function(msg){
}
});
});
});
</script>
Then I have this code for the user to click:
<div class="show">
<button class="roundbox_blue" value="1"> Click </button>
<button class="roundbox_blue" value="2"> Click </button>
</div>
The PHP code that will parse the AJAX query is like this:
if(isset($_POST['report']))
{
$line_id = $_POST['report'];
$Portal->LoginDB('test');
mysql_query('UPDATE `ajax` SET `report` = "1" WHERE `id`="'.$line_id.'"');
}
if(isset($_POST['not_report']))
{
$line_id = $_POST['not_report'];
$Portal->LoginDB('test');
mysql_query('UPDATE `ajax` SET `report` = "0" WHERE `id`="'.$line_id.'"');
}
The problem I'm facing is, once the user click the button, mysql did update the record however, when the user click the button second time (meaning to cancel) mysql did not update the record accordingly.
I appreciate if you guys can help me out here..
You are only hooking the blue box on doc load.
change class of second button,
<div class="show">
<button class="roundbox_blue" value="1"> Click </button>
<button class="roundbox_orange" value="2"> Click </button>
</div>