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>
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 a test.html page which has two and four buttons. When the page loads, i want to retrieve data from mysql database using php and then use ajax to display that in the div. But there are four rows in the table. Also when button 1 is clicked values of row 1 should display, button 2 should display values of row2 ..... How to do it? I dont want to query the database for each button click.
test.html
<div id="q1"></div>
<div id="q2"></div>
<button type="button" data-value="1">1</button>
<button type="button" data-value="2">2</button>
<button type="button" data-value="3">3</button>
test.php
$sql = "SELECT q1, q1 FROM test WHERE test=1";
$result = mysqli_query($conn, $sql);
echo json_encode($result);
test.js
$().ready(function() {
'use strict';
var testid;
var string = "";
$("button").click(function(){
testid=$(this).data("value");
$.ajax({
type: 'POST',
dataType: 'json',
url: 'js/php/testpaper.php',
data: {
testid1: testid
}
}).done(function(data) {
});
});
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/
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");
Basically I have a list of files composed from a foreach loop that all have the same code except for the name, which carries the file_id for each file. My problem is that when I added an on-click pop-up event I lose the ability to fetch the current $(".flag") attribute name. Is there a way that I can pass it along the way so I can use it in the end?
PHP: (the user sees the link which they can click...remember there are several of these as a result from the foreach loop. I'm showing one for example)
echo "<td><a href='#' class='flag' name='$files[id]' >Click Here</a> ( $files[nums] )</td>";
jQuery: (on-click this will happen)
$(".flag").live('click', function() {
$(".pop").show("slow");
return false;
});
HTML: this div will popup
<div class="pop">
<form method="post" id="new_folder" >
<p><label for="folder">Reason for Reporting?</label><textarea id="report_reason" name="report_reason" maxlenght="100" style="resize:none" cols="30" rows="5">Please limit your response to 100 characters.</textarea></p>
<p><input type="submit" value="Submit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
</form>
</div>
jQuery: on submit I need to send the current $files['id'] and textarea value via ajax. The textarea sends the correct data, but the $(".flag") instead of being the id of the selected link it is the id of the first fetched id from the foreach loop
$("#message_submit").on("click", function(e){
var fileID = $(".flag").attr("name");
var text = $("#report_reason").val();
$(".pop").hide("slow");
$.ajax({
url: '<?php echo base_url().'home/report_file';?>',
type: 'POST',
data: { val: fileID, val2: text },
dataType: 'json',
success: function(output_string){
$(".success").text("You have flagged this file!!").show().css({"color" : "green", "margin-top" : "10px"});
$(".success").fadeOut(10000);
}
});
return false;
});
You can save the .flag link being clicked and later use it.
var flagClicked;
$(".flag").live('click', function() {
$(".pop").show("slow");
flagClicked = $(this);
return false;
});
$("#message_submit").on("click", function(e){
var fileID = flagClicked.attr("name");
....