I have a form that can delete records from a MySql database using ajax and jQuery. I'm trying to get the jQuery to only select the relevant record passed to it and not just delete the top row of records which it does at the moment. I think I need to get
<div class="'.$id.'">
from my form and make it a data attribute that can be selected. Hope I'm making myself clear. Many thanks.
<script type="text/javascript">
//Delete Review
$(document).ready(function(){
//Need to get $id here.
$(".deleteReview").click(function (e) {
e.preventDefault();
var username = $("#username").val();
var film_id = $("#film_id").val();
var id = $("#id").val();
$.post('ajax_deleteReview.php', {
username: username,
film_id: film_id,
id: id
}, function(data) {
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(500);
$("#message").fadeOut(2500);
});
return false;
});
});
</script>
<form>
<div class="'.$id.'">
<input type="hidden" id="username" name="username" value="'. $username.'">
<input type="hidden" id="film_id" name="film_id" value="'.$film_id .'">
<input type="hidden" id="id" name="id" value="'.$id .'">
<button type="submit" id="" class="btn btn-danger btn-xs pull-right">delete</button>
</form>
</div>
I would recommend you to use data-* prefixed attributes to persists your data.
HTML
<div data-id="'.$id.'" data-username="'. $username.'" data-filmid="'.$film_id .'" class="deleteReview">
<button type="submit" id="" class="btn btn-danger btn-xs pull-right">delete</button>
<div >
Then you can fetch it using .data(key)
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute
Script
//Delete Review
$(document).ready(function(){
//Need to get $id here.
$(".deleteReview").click(function (e) {
e.preventDefault();
var username = $(this).data("username");
var film_id = $(this).data('filmid');
var id = $(this).data('id');
......
return false;
});
});
First in your PHP do something like this, you add the data attributes to your delete button since you are not actually submitting a real form. I also moved the deleteReview class to the button.
print '<button type="submit" class="deleteReview" data-id="'.$id.'" data-film-id="'.$film_id.'" data-username="'.htmlentities($username).'" class="btn btn-danger btn-xs pull-right">delete</button>';
Then, in your jQuery, update click event callback like so:
$(".deleteReview").click(function (e) {
e.preventDefault();
var username=$(this).data('username');
var film_id=$(this).data("film-id");
var id=$(this).data('id');
/* the rest of your code */
The data attributes become accessible easily with jQuery using $(this).data('some-attribute-name')
Related
I'm trying to create a modal popup that contains a confirmation delete button when I press delete on my index view, that button contains the ID of the object you are going to delete, I get it with jquery and replace the form action with it.
My problem is replace it not just replacing the placeholder ID on my action form, its replacing whole route with something like http://localhost/project/public/logout.
Delete button on my index.blade.php:
<button type="button" class="btn btn-outline-danger" data-toggle="modal" data-target="#deleteModal" data-id="{{$category->id}}"><i class="far fa-trash-alt"></i> Delete</button>
Form on modal:
<form action="{{route('categories.destroy', ['id' => 'placeHolderId'])}}" method="POST">
#csrf
#method('DELETE')
<button type="button" class="btn" data-dismiss="modal">Cancel</button>
<button class="btn btn-danger" type="submit">Delete</button>
</form>
Jquery function that replaces the placeholderId on form action attribute:
$(document).ready(function() {
$('#deleteModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var placeHolderId = button.data('id');
var modal = $(this);
var action = $('form').attr('action');
modal.find('form').attr("action", action.replace('placeHolderId', placeHolderId));
});
});
Result:
<form action="http://localhost/project/public/logout" method="POST">
Expected result:
<form action="http://localhost/project/public/manager/categories/1" method="POST">
give the submit form another id, and on jQuery find the form by that Id, cause right now, its gettign the first form on the DOM and thats logout form
basically put id="categoriesForm" and on jQuery $("#categoriesForm").submit()
$(document).ready(function() {
$('#deleteModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var placeHolderId = button.data('id');
var modal = $(this);
var action = $('#categoryForm').attr('action');
modal.find('#categoryForm').attr("action", action.replace('placeHolderId', placeHolderId));
});
});
or what you can do, is capture when the form is submit, then prevent the default, do the confirmation pop up and then submit
<form action="{{route('categories.destroy', ['id' => 'placeHolderId'])}}" method="POST" id="categoryForm">
#csrf
#method('DELETE')
<button type="button" class="btn" data-dismiss="modal">Cancel</button>
<button class="btn btn-danger" type="submit">Delete</button>
</form>
$(document).ready(function() {
$("#categoryForm").on('submit', function(e) {
e.preventDefault();
var confirmDelete = confirm("Are you sure you want to delete this category!");
if(confirmDelete) {
$(this).submit()
}
})
});
I have a button which send me the values of input checkboxes via an ajax call.
<input type="checkbox" class="delete" value="PHP" /> PHP <br />
<input type="checkbox" class="delete" value="ASP" /> ASP <br />
<button type="button" class="checkbox_value_delete">Delete</button>
The ajax:
$('.checkbox_value_delete').click(function(){
var checkboxes_delete = [];
$('.delete').each(function(){
if($(this).is(":checked")) {
checkboxes_delete.push($(this).val());
}
});
checkboxes_delete = checkboxes_delete.toString();
$.ajax({
url:"",
method:"POST",
data:{ checkboxes_delete:checkboxes_delete },
success:function(data){
$('.result').html(data);
}
});
});
This works fine!
Now i want to add to more buttons and bind the selectors to the data in the same ajax call. is that possible or do i have to create 3 standalone ajaxes for this?.
Buttons:
<button type="button" class="checkbox_value_delete">Delete</button>
<button type="button" class="checkbox_value_copy">Copy</button>
<button type="button" class="checkbox_value_move">Move</button>
Something like below:
$('.checkbox_value_delete, checkbox_value_copy, checkbox_value_move ').click(function(){
var checkboxes_delete = []; // bind to 1st selector
var checkboxes_copy = []; // bind to 2nd selector
var checkboxes_move = []; // bind to 3rd selector
// and so on...
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 am trying to send form data using ajax. My index page the records are showing after having been fetched using ajax from remote page.
Below is my page image.
Each record has comment box I want to store these comments in a data base using ajax.
Below is my jquery
$(function(){
$('body').on('submit','.comment_p',function(){
var post_id = $("#post_id").val();
var com_dis= $("#comment_disc").val();
var cominfo = 'id=' + post_id + '&disc=' + com_dis;
if(com_dis=='')
{
alert('Please add your comment');
} else{
$.ajax({
type:"POST",
url:"/comment_update.php",
data:$(".comment_p").serialize(),
success: function(data){
alert(data);
}
});
}
return false;
});
});
i used body on click because these records are loaded from remote page.
and my form is below
<div class="panel-zesteve-textarea">
<form method="post" id="'.$row['id'].'" class="comment_p">
<input id="post_id" type="hidden" name="post_id" value="'.$row['id'].'">
<textarea id="comment_disc" name="comment_disc" rows="2" cols="48"></textarea>
<button id="com_submit" type="submit" class="btn btnbg">Post comment</button>
<button type="reset" class="[ btn btn-default ]">Cancel</button>
</form>
nowWhen I click on post, comment is working for one record that is the last record. I need to send id no. and textarea value to php page to update in mysql, but both comments are showing same record id and comment. It's not working for sencond one
Try to reference the form with $(this)
data: $(this).serialize(), instead of `data:$(".comment_p").serialize(),`
Im trying to make something like this http://demos.99points.info/facebook_wallpost_system/ which is a comment system. I have the ajax code below except i don't know how to uniqely select textareas. The challenge is that the number of posts is variable so all of the posts need to be uniquely identified so that when the data is put into the database i know which post it relates to.
JQUERY:
<script type='text/javascript'>
$('document').ready(function(){
$('.commentContainer').load('../writecomment.php');
//commentContainer is a class so it applies to all of the textareas, but i need this selector to be unique
$('.submitCommentBox').click(function(){
//these are the selectors that i can't get to work right
var comment = $('').val();
var postid = $('').val();
$.post('../comment.php',
{
comment: comment,
postid: postid,
},
function(response){
$('#commentContainer').load('../writecomment.php');
$('.commentBox').val('');
}
}
return false;
}):
});
</script>
HTML/PHP
<?php while ($row=mysql_fetch_assoc($query)){
echo"
<p name='singlePost'>$post[$f]</p>
<div id='commentContainer'></div>
<textarea class='commentBox'></textarea>
<input type='button' value='submit' class='submitCommentBox'>";
}
basically the HTML/PHP generates for each post on the page as to create a textarea and subimt button for each post. therefore the user can comment on each post.
Using the markup in the link you provided, I would do something like:
var container = $(this).closest('.friends_area');
var comment = $(container).find('.commentbox').val();
var questionid = $(container).find('#hidden').val();
var answerid = $(container).find('').val();
A more correct solution would be something like:
HTML
<div id="posting">
<form method="post" action="">
<input type="hidden" name="record_id" value="123" />
<textarea name="comment"></textarea>
<button type="submit">Comment</button>
</form>
...
</div>
JS
$('#posting').on('submit', 'form', function(e) {
e.preventDefault();
var form = $(this).closest('form');
$.post($(form).attr('action'), $(form).serialize(), function() {
$('#commentContainer').load('../writecomment.php');
$('.commentBox').val('');
});
});