PHP / MySQL / AJAX - Update multiple data - php

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/

Related

AJAX Page with Boostrap Modal Form - Submit don't work

i searched a lot about this problem, but I didn't find a solution, yet.
At first a short description about my setup to make my problem clearer.
Settings.php Page with a Menu, where you can select different settings categories
By clicking on one menu point the corresponding loads by ajax and is displayed.
$('#content').load("http://"+ document.domain + "/domainhere/settings/menupoint1.php");
On the menupont1.php page I got a list with mysql data.
I implemented a "edit" button for each row - while clicking on the edit button, a boostrap modal appears with a form and the corresponding data filled in and ready to edit.
When i now click on "Save changes", the POST-Request is always empty.
To realize the form submit, I already tried several codes:
e.g.:
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
or
$(function(){
$('#editform').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#editform').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
At the moment:
while($xy= $xysql->fetch_assoc()) {
<div class="modal fade" id="edit-<?php echo $xy["id"] ?>" [..]>
<button id="submit>" class="btn btn-default">Save</button>
</div>
<script>
$(function() {
$('button#submit').click(function(){
$.ajax({
type: 'POST',
url: './test2.php',
data: $('form#modal-form').serialize(),
success: function(msg){
$('#test').html(msg)
$('#form-content').modal('hide');
},
error: function(){
alert('failure');
}
});
});
});
</script>
Maybe someone here could help me out with this problem?
thank you very much :)
I've set up a minimal example of how this would work:
example html of two modals, which are produced in a loop in your case.
I've now done it without a unique id, but with selecting via class.
<div class="modal">
<!-- // this classname is new and important -->
<form class="editform">
<input name="test" value="value1">
<button class="btn btn-default">Save</button>
</form>
</div>
<div class="modal">
<form class="editform">
<input name="test" value="value2">
<button class="btn btn-default">Save</button>
</form>
</div>
Your javascript would be something like this:
$(function() {
var formsAll = $('.editform');
// changed this to onSubmit, because it's easier to implement the preventDefault!
formsAll.on('submit',function(e){
e.preventDefault();
var formData = $(this).serialize();
console.log(formData);
// add your ajax call here.
// note, that we already have the formData, it would be "data: formData," in ajax.
});
});
Note, that I don't have your real html structure, so details might vary. But you get the idea.
also available here:
https://jsfiddle.net/a0qhgmsb/16/

Can a post request be sent via a button without a wrapping form

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

Send form data to php from ajax loaded records

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(),`

How can I get the data attribute from a php variable?

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

Jquery Ajax selectors

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('');
});
});

Categories