I have a button that when it is pressed calls an ajax function with some parameters and then the ajax posts some values on the database. The user might use this form a lot of times before he leaves the application or refreshes the page. Up to now, this works great!
In my last update, I added a checkbox that will hold one more piece of information that I want to be saved on the database using the aforementioned ajax function. So, when the button is pressed, I check if the checkbox is checked and I send to the ajax function true or false. Up to now, this works great too!
What doesn't work great, though, is the fact that the last features works properly only for the first time! Every other time the user hits the button, no matter what the checkbox checked state is, it will submit the state it was the first time. It is like the checkbox.checked property freezes after the button is pressed for the first time.
It might be irrelevant, but I also tried the same with toggle buttons and I get the same issue!
Do you have an idea on how to overcome this problem?
Thanks a lot!
Here is the code:
The form: It has 1 toggle button and 3 buttons that call the sendTask function.
<button type='button' class='btn btn-info' data-toggle='button' style='margin-top: 5px; width: 216px; height: 40px;' name='yesterday".$category['id']."' id='yesterday".$category['id']."'>This one was yesterday!</button></div>
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '1', yesterday".$category['id'].")'>0-15min</button>
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '2', yesterday".$category['id'].")'>15-60min</button>
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '3', yesterday".$category['id'].")'>60+min</button>
The sendTask function:
function sendTask(category, weight, checkbox){
var ieri = $(checkbox).hasClass('active');
TaskSubmit(category, weight, ieri);
};
The TaskSubmit function:
function TaskSubmit (taskidsubmitted, weight, ieri) {
$.ajax({
url: 'submit_task.php?taskid=' + taskidsubmitted + '&weight=' + weight + '&ieri=' + ieri,
success: function (response) {
if (response !== "fail") {
document.getElementById('score-label').innerHTML = response;
} else {
document.location = "index.php";
}
}
});
}
The problem is that this line:
var ieri = $(checkbox).hasClass('active');
only changes the fist time a button is pressed. All the other times keeps the first state (true or false).
I believe you should be using .prop().
function sendTask(category, weight, checkbox){
var ieri = ($(checkbox).prop('checked') != undefined);
TaskSubmit(category, weight, ieri);
};
The browser -should- remove this property if the checkbox is unchecked. If this is not the case, use console.log() to find out what it is doing.
In your html, you are passing yesterdaySomeCategory to the function, instead of "yesterdaySomeCategory". I am not sure what jQuery does with that, but the normal way of selecting an element is by $("#yesterdaySomeCategory"). Try changing it to
<button class='btn btn-".$buttoncolor."' id='btn-spec-small' type='button' onClick='sendTask(".$category['id'].", '1', \"#yesterday".$category['id']."\")'>0-15min</button>
Related
I am trying to use jquery to delete a row from a table when a button is clicked. The row is dynamically generated when the user clicks a + submit button.
Right now, when the button is clicked the form gets submitted. I'm trying to stop that with a return false. (Not sure how to implement prevent default in onclick)
I have tried 2 pieces of code. When using the onlick = 'return false;' on the button tag, it works fine. When I try to add a function call with it, it continues to submit the form and I'm at a wits end with this.
Variation 1 that doesnt work:
$('#tbl').append(
"<tr id='"+countCourses+"'>"+
"<td><button onclick='return delete_row();' style='border: 0; background: none;'>"+
"<i class='fa fa-minus-circle fa-lg' style='color:red' ></i></button></td>");
function delete_row(){
alert('hello');
return false;
};
Variation 2(also doesnt work):
$('#tbl').append(
"<tr id='"+countCourses+"'>"+
"<td><button onclick='return delete_row(); return false;' style='border: 0; background: none;'>"+
"<i class='fa fa-minus-circle fa-lg' style='color:red' ></i></button></td>");
function delete_row(){
alert('hello');
};
I also tried the return false in both places simultaneously but that doesn't work either. What am I doing wrong ?
Last Thing I tried was, this doesnt stop the submit either:
"<td><button class='remove' style='border: 0; background: none;'>"
$(document).ready(function(){
$('.remove').click(function(event){
event.preventDefault();
alert('test');
// var num = $(this).attr('value');
// console.log(num);
// $("#"+num).remove();
});
});
Why not use jQuery for this:
(function($, document){
$(document).ready(function($){
var countCourses = 'course-1'; //ids shouldn't start with a number (for testing)
$('#tbl').append(
"<tr id='"+countCourses+"'>"+
"<td>"+
"<button name='submit_delete' style='border: 0; background: none;'>"+
"<i class='fa fa-minus-circle fa-lg' style='color:red' ></i>"+
"</button>"+
"</td>"+
"<td>Foobar</td>"+ //for testing
"</tr>" //for testing
);
$('#tbl').on('click', 'button[name="submit_delete"]', function(e){
//return; //-- simply return before the remove action on some condition
$(this).closest('tr').remove(); //find the closest parent tr to the button and remove it
});
});
})(jQuery, document);
td{border:1px solid black;}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table id="tbl" >
</table>
I think the thing you were missing is $(this).closest('tr') - in the event handler this is the target of the event. So we can simply find the next parent row above this in the DOM and remove it.
event.preventDefault(); will prevent the default action of whatever it is your preventing. Since your already in the event handler it wont prevent your code in there from running there.
If you want to stop an actual form from submitting, both e.preventDefault() and return false will work from inside the event handler.
But, in your example:
$('.remove').click(function(event)
You have a class remove that I don't see on the button, but even if it was there you would need to use Event Delegation, because it's a dynamically rendered element. There is a good chance when you add a new row, your event is already bound and won't detect these new elements. Therefor you have to bind to a parent element that is present in the actual source code. Then you delegate it to the button as I did above. This way it can pick up those events and pass them to the dynamic elements.
That said it's been a long time since I looked up the docs on how jQuery handle events, it must have been like v 1.6 or something back in 2011 or so, that may have changed in the "mean" time... lol ... but I know this way works, so I just do it like that for the last 8 years or so. Well whenever they got rid of live anyway.
Cheers!
So i'm trying to use a table that generates multiple submit buttons per row. I'm doing this with a php while loop. Each button has a value of the corresponding "id" from the database. The table populates with everything from the database that has a status of "Ordered". On each row I can click a button that will change it to "Received" or "Cancelled". This is why I assigned a value of "id" to each button, so it only affects the status of the row that's being clicked. So far, all this is working fine but I would like to be able to do this using ajax instead of refreshing the page each time.
Currently I have this for my ajax:
$('#cancel').click(function(e) {
e.preventdefault();
//set value of cancel button to a variable
var value = $("#cancel").val();
$.ajax({
method: "POST",
url: "updatetable.php",
data: {cancel: value},
});
});
and this for my PHP:
//updatetable.php
if($_POST['cancel']) {
echo $_POST['cancel'];
}
the reason for the "if" statement is because I also need to click received but if yall help me figure this part out, i can go the rest of the way on my own.
Right now, I can't even get this to connect with a simple echo of the POST variable.
Just for reference, here is my html markup for the buttons:
<button type='submit' class='btn btn-danger' name = 'cancel' id = 'cancel' value='".$row['order_id']."'>Cancel</button>
<button type='submit' class='btn btn-success' name = 'received' id= 'received' value='".$row['order_id']."'>Received</button>
(the buttons are output by a PHP echo statement-hence the concats in the value setting)
I've tried to follow several tutorials but I can't figure out why this doesn't connect the right way. Perhaps I need to change it to an input with type "button" instead of button type submit? But then the actual value of the "value" would appear as the text instead of the word "cancel". Any help is appreciated.
you are going to want to put a unique identifier on your IDs. Here is what I would do (instead):
function cancelClick(btn){
e.preventdefault(); // I dont think this is needed
var value = $(btn).val();
$.ajax({
method: "POST",
url: "updatetable.php",
data: {cancel: value},
});
});
actually I would do this but that isnt what you used:
function cancelClick(btn){
var value = $(btn).val();
$.post("updatetable.php",{cancel: value});
});
then your UI like:
<button type='button'
class='btn btn-danger'
value='<?=$row['order_id'] ?>'
onClick="cancelClick(this)">Cancel
</button>
<button type='button'
class='btn btn-success'
value='<?=$row['order_id'] ?>'
onClick="otherFnName(this)>Received
</button>
edit: to perform a task on return you do something like this:
function cancelClick(btn){
var value = $(btn).val();
$.post("updatetable.php",{
cancel: value
}, function (d){
// here is where you will do stuff on return.
// I suggest first console.log(d); and see what is returning
// return (echo) a value to at least identify the row
// you are wanting to delete, if that is what you are attempting
// be sure the element you are attempting to manipulate has
// a unique identifier (id), and then do whatever.
// you can call a function from here also, to make it neater
// this area will `happen` when your ajax is complete.
});
});
I'm using php to create 'x' amount of buttons based on the rows from a db table.
Once the button is selected i want to pass the Variable onto the php so i can used this to load specific data from the database to the Modal.
This works for the first button click and loads the data to the modal as expected, however once i close the modal and open another modal the new userdata.php?uid=$var1 doesn't seem to get received in the php by the $var2 = $_GET['uid'] and the variable just remains the same as before.
Do i need to clear the uid in the php somehow?
The Button,
$var1 = $row["Scope_ID"];
echo "<button type='button' href='userdata.php?uid=$var1' class='btn btn-
info btn-lg' data-toggle='modal' data-button='$var1' data-
target='#myModal'>$var1</button>";
The PHP,
$var2 = $_GET['uid'];
echo "<h3>$var2</h3>";
the solution is,
$( document ).ready(function() {
$('#editBox').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
});
});
Ive got a table with buttons:
and Ive set specific ID's to each one but I dont see how I can access them all from a JQuery script so i can set a specific get to each one of them.
Edit:
All of the buttons have unique ids:
Shown in google chrome inspect element :
When I click REMOVE i want the row to get removed. I can do this and have done this with PHP via GET however I dont want to have to refresh the page every time I remove one. I tested doing it with JQuery .GET and it works fine however I dont want to have to make a new script to have to delete every single row, rather do it dynamically by getting the ID of the row and removing the row that the REMOVE button is in. Ive tried multiple ways of doing this but all I do is fail.
This is the script that prints the data in the table
function print_data($info1,$info2,$info3,$info4,$info5,$info6,$info7,$info8){
echo"<tr><td id='notice1id$info8'>$info1</td><td id='noticename$info8'>$info2</td><td id='noticetype$info8'>$info3</td><td id='noticecontent$info8'>$info4</td><td id='noticeshow$info8'>$info5</td><td id='noticeedit$info8'><a href='admincp.php?edit=1&editid=$info6'><div class='btn btn-success'>Edit</div></a></td><td id='noticeremove$info8'><input type='button' id='remove$info8' value='remove' onclick='removeMe();' class='btn btn-danger' name='$info8'></td><td style='display:none;'><p id='getid' name='$info8' style='display:none;'></p></td><td style='display:none;'><script> function removeMe() { alert($info8);}</script></td><input id='noticeid$info7' class='form-control' style='display:none;' type='text' name='$info8' value=$info7></td></tr>";
?><?php
}
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
print_data($row['NoticeID'],$row['NoticeName'],$row['NoticeType'],$row['NoticeContent'],$row['NoticeShow'],$row['NoticeID'],$row['NoticeID'],$row['NoticeID']);
}
JavaScript:
$(document).ready(function () {
var id = $("#getid").attr("name");
alert("#remove" + id);
$("#remove" + id).click(function () {
var getcontent = $("#noticeid4").val();
$("#notice1id5,#noticename5,#noticetype5,#noticecontent5,#noticeshow5,#noticeedit5,#noticeremove5").slideUp(300, function () {
// Animation complete.
});
});
});
I am trying to create a button, that whenever it is clicked (Onclick)
<button onClick="showUser(<?php echo $b?>)">Back</button>
it changes a value (number) so that the number can be retrieved by a function that will
be able to display information. Example I am calling the buttons next and back- if the button next is clicked, I want it to keep increasing it's value everytime I click it so that when it's number increases, different information will be accessed depending from that number, example when I first click the button (it would be value 1) information will be visible then when I click again it will increase to (2) and I will be able to see other information, the problem is that whenever I try to increase the value, the value increases only once.
I am doing this so that I will have information displayed and everytime the user clicks these buttons next and back, information sequentially will be shown- taken from a database.
I am using javascipt, php and sql.
Is what I am saying possible?
You could use an object, in which you set the two variables that you need to update on click:
var obj = {
nextClicked : 0,
prevClicked : 0
};
function buttonClick(type) {
if(type == "prev") {
obj.nextClicked++;
}
if(type == "next") {
obj.prevClicked++
}
}
<button type="button" onclick="buttonClick('next')">Next</button>
<button type="button" onclick="buttonClick('prev')">Prev</button>
Since you are using ajax, the variables would not reset, unless you refresh the page
You could use a php session to store the "page" number you're currently on and then increase or decrease based upon which button is clicked (you could use ajax or a simple form to send the event data).
use a hidden field to hold the value, and an onclick function to increase it and submit the form.
<?
if(!isset($_GET['count'])) {
$count = 0;
} else {
$count = $_GET['count'];
}
?>
<script type='text/javascript'>
function submitForm(x) {
if(x == 'prev') {
document.getElementById('count').value--;
} else {
document.getElementById('count').value++;
}
document.forms["form"].submit();
}
</script>
<form action='hidfield.php' method='get' name='form'>
<input type='hidden' name='count' id='count' value='<?php echo $count; ?>'>
</form>
<input type='submit' name='prev' value='prev' onclick="submitForm('prev')">
<input type='submit' name='next' value='next' onclick="submitForm('next')">
Add this to your webpage and refresh a few times.
<?php
session_start();
echo $_SESSION['count']++;
Can be tested here:
http://codepad.viper-7.com/qXdj8M