I have a page with 'favourite' button that when clicked runs an Ajax post and updates my db table 'favourite' accordingly user and book details.
The current process is as follows,
click button once > add book to favourite table > refresh page > display success div
click button again > delete book from favourite table > refresh page > display success div
What I would like to do now is on page load, check if the user has already added the book as a favourite, if so, set the class of this button to btn-success (green).
How do I achieve this? Do I need to give the button an attribute on page load and check this on page load?
I am quite new to php and js so any advice is appreciated. I have included my code for reference.
ajax
$(document).ready(function(){
$( "#fav" ).click(function(){
book_id = $(fav).val(); // set the value of the button as the book_id
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/checkFav',
data: {book_id:book_id},
success: function () {
window.location.reload(true);
}//end success
});//end ajax
});
});
checkFav php
$bookid=$_REQUEST['book_id']; //get this from ajax
$userid=$_SESSION['user_id']; //get this from session
$sql = "SELECT * FROM favourite WHERE book_id = :book_id AND user_id = :user_id";
... //execute
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (book_id, user_id) VALUES (:book_id, :user_id)";
... //execute
} else {
$sql = "DELETE FROM favourite WHERE book_id = :book_id AND user_id = :user_id";
... //execute
}
html
echo '<td>
<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button></td>';
echo '</tr>';
This is incorrect:
<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button>
You must specify that you want PHP code and you want to echo $book->id, like this:
<button id="fav" value="<?php echo $book->id; ?>" type="button" class="btn btn-default"></button>
Also, let's suppose you have a PHP function isFavorite, then
<button id="fav" value="<?php echo $book->id; ?>" type="button" class="btn btn-default<?php echo ((isFavorite()) ? (" btn-success") : ("")); ?>"></button>
There are two things you can do:
make a php function that checks if it is already a favorite or not and returns true or false and based on that add a class to the button like this:
$("#buttonId").addClass("btn-success");
if you already have this data when the page loads you can add a php code inline in the html like this:
if($favorite){
$class = "btn-success";
}
and then in the html
<button id="fav" value="<?php echo $book->id; ?>" type="button" class="btn <?php echo ($book->isFavorite()) ? 'favorite' : '';?>"></button>
Related
image table
Currently, I'm doing a system where is manager can assign the job to workers. I have a table listing. In this table listing, when I click at Job Order Number, there will be a popup modal. What I'm having right now is, if the job status is pending, I want to show a different popup modal . Do you guys have any idea how can I achieve that ?
Currently, I'm doing like this where I declare the modal popus using php class.
<td id="testing" data-id="<?php echo $row['jobregister_id'];?>" class = "<?php echo $row["job_status"]; ?>" data-target="doubleClick-info" onClick="document.getElementById('doubleClick-info').style.display='block'"><?php echo $row["job_order_number"]; ?></td>
<td><?php echo $row["job_priority"]; ?></td>
<td"><?php echo $row["job_status"]; ?></td>
and here is my ajax for job status pending
<div id="doubleClick-info" class="modal">
<div class="tabInfo">
<input type="radio" name="tabDoingInfo" id="tabDoingInfo1" checked="checked">
<label for="tabDoingInfo1" class="tabHeadingInfo"> Job Info </label>
<div class="tab" id="JobInfoTab">
<div class="contentJobInfo">
<div class="techClose" data-dismiss="modal" onclick="document.getElementById('doubleClick-info').style.display='none'">×</div>
<form action="homeindex.php" method="post">
<div class="info-details">
</div></form></div></div>
<script type='text/javascript'>
$(document).ready(function () {
$('body').on('click','.Pending',function(){
// $('.JobInfo').click(function () {
var jobregister_id = $(this).data('id');
// AJAX request
$.ajax({
url: 'ajaxhomepending.php',
type: 'post',
data: { jobregister_id: jobregister_id },
success: function (response) {
// Add response in Modal body
$('.info-details').html(response);
// Display Modal
$('#doubleClick-info').modal('show');
}
});
});
});
</script>
it all seems fine. i define the javascript using class. but when the class have no value, how do i define it ? do you guys have any idea how to do it. thank you so much.
Here I'm working on a simple withrawal page where users can select the amount they want to withdraw and submit afterwhich a bootstrap modal pops up confirming to the user that the request has been sent whilst updating the section in the db with the amount selected.
So far im facing no issues when user selects the amount and click on submit, the modal pops up but unfortunately the database is not updated, I can't fathom where i'm getting it wrong.
Here is the Php
<?php
// Define variables and initialize with empty values
$withraw = "";
$withraw_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate Withrawal
if(empty(trim($_POST["withraw"]))){
$withraw_err = "Please Choose a Amount.";
} else{
$withraw = trim($_POST["withraw"]);
}
// Check input errors before inserting in database
if(empty($withraw_err)){
// Prepare an insert statement
$sql = "UPDATE users SET withraw = (?) WHERE id = ".$id;
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_withraw);
// Set parameters
$param_withraw = $withraw;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
echo "";
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
Here is the code for the form im using.
<form onsubmit="openModal()" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" id="myForm" >
<div class="form-group <?php echo (!empty($withraw_err)) ? 'has-error' : ''; ?>">
<div style='width:50%;' class='selectt'><select name="withraw" class="form-control" value="<?php echo $withraw; ?>"><option >Choose Amount</option>
<option value="500">500</option>
<option value="1000">1,000</option>
<option value="1500">1,500</option>
<option value="2000">2,000</option>
<option value="2500">2,500</option>
<option value="3000">3,000</option>
<option value="3500">3,500</option>
</select>
</div>
<span class="help-block"><?php echo $withraw_err; ?></span>
</div>
<div class="form-group" >
<button type="submit" class="btn btn-info btn-lg" value="Submit">
Withraw <i class="fa fa-check-circle"></i> </button>
<button type="reset" class="btn btn-default" value="Reset"><i class="fas fa-redo"></i> Reset </button>
</div>
</form>
And I've added some javascript to load the bootstrap modal after the form is Submitted
<script>$('#myForm').on('submit', function(e){
e.preventDefault();
$('#myModal').modal('show');
});</script>
Here is where I'm completely lost as, when I remove the e.preventDefault() the form Updates the database row called withraw but the bootstrap does not load at all and I've been trying to set so that the bootstrap loads and the database row is updated as well I do not have more knowledge on how to tackle this situation as I read similar questions and some suggestions are to use Ajax but I have limited knowledge on how to do that.
I didn't post the bootstrap because i don't see it necessarily its a normal Bootstrap modal setup
I have an HTML form inside a very customised Opencart v2.3.0.2 site.
Onsubmit, the form executes two JS functions the following functions
1)myFunction2()adds a product and
2)myFunction()
submits the form data,
while routing to (action="index.php?route=checkout/checkout")
I need to force the user to login if they are not already logged in before these two functions execute. So, I would want to add another JS function that forces login before executing the next two JS functions. Maybe there is an easier way.
Opencarts built-in function for checking if a user is logged is $data['logged'] = $this->customer->isLogged();
Form Submit
<button type="submit" class="btn btn-success btn-lg"><a id="addtocart" onclick="myFunction2(); myFunction()">Continue to Checkout</a></button>
JS Functions
function myFunction2() { //adds product to cart............
$.get( "index.php?route=checkout/cart/addToCart&product_id=30", function( data ) {
$( "#myForm" ).addClass( "product-added" );
});
}
function myFunction() { //submits form option with associated variables.........
if($( "#myForm" ).hasClass( "product-added" )){
document.getElementById("myForm").submit();
}
}
So, Ideally to create a third JS function that executes first and checks if the user is logged. If user is logged continues with the second and third functions. If user is not logged "popup" with a login request, then once logged executes the second and third functions to checkout.
Wouldn't it be easier to simply disable the button if the user isn't logged in?
<?php $enabled_button = $logged == true ? "" : "disabled readonly"; ?>
<button type="submit" class="btn btn-success btn-lg" <?php echo $enabled_button; ?>><a id="addtocart" onclick="myFunction2(); myFunction()" <?php echo $enabled_button; ?>>Continue to Checkout</a></button>
Assuming that $logged is set properly by the controller, the expression will echo "disabled" & "readonly" values into the HTML element if the user is not logged in.
Alternatively, you can just add an if statement to either show the button or show a login button:
<?php if($logged) { ?>
<button type="submit" class="btn btn-success btn-lg"><a id="addtocart" onclick="myFunction2(); myFunction()">Continue to Checkout</a></button>
<?php } else { ?>
<button type="submit" class=btn btn-success btn-lg"><a id="login" onclick="yourLoginFunction">Login</a></button>
<?php } ?>
I've a list of all my users in a table. The last td element will contain a form,
either a form for opening the account or a form for closing the account based on if the user
is already been closed or not. I'm using jQuery AJAX form plugin from http://malsup.com/jquery/form/ which is working.
What I'd like to do is the change the value of button before the form is been submitted.
Here's my JS for now:
$(document).ready(function() {
$('form').ajaxForm({
beforeSubmit: function() {
$('form').find('input').val('Wait...');
},
success: function(data) {
$('body').html(data);
}
});
return false;
});
and here's my HTML markup:
<td>
<?php if($user['closed'] == 0):?>
<?php $attributes = ['class' => 'account']; ?>
<?php echo form_open('admin/closeAccount', $attributes);?>
<input type="hidden" name="user_id" value="<?=$user['user_id']?>"/>
<input type="hidden" name="user_email" value="<?=$user['email']?>"/>
<input type="submit" name="close_account" class="btn btn-danger btn-sm" id="trigger" value="Close" >
<?php echo form_close();?>
<?php else:?>
<?php $attributes = ['class' => 'account'];?>
<?php echo form_open('admin/openAccount');?>
<input type="hidden" name="user_id" value="<?=$user['user_id']?>"/>
<input type="submit" data-loading-text="Odota..." name="open_account" class="btn btn-success btn-sm" id="trigger" value="Open" >
<?php echo form_close();?>
<?php endif ?>
</td>
The problem is that every time I try to submit the form, it will now change the value of all buttons to "Wait..." instead of just the one I clicked. I tried
to replace $('form') with $(this) in $('form').find('input').val('Wait...'); but that didn't help me at all.
According to the plugin documentation (http://malsup.com/jquery/form/#options-object)
$form passed to beforeSubmit callback should give you access to the current form being submitted.
try:
$('form').ajaxForm({
beforeSubmit: function(arr, $form, options) {
$form.find('.btn').val('Wait...');
},
success: function(data) {
$('body').html(data);
}
});
Just try this code
$('.btn').val('Wait...');
or
$('.btn-danger').val('Wait...');
or
$('.btn-sm').val('Wait...');
Try adding more specificity to your CSS selector. Inside your ajaxForm() call try this to change submit button value:
$(this).find('input[type="submit"]').val('Wait...');
If i understood you right you need just change your selector to - $('input[type="submit"]').
So it will be -
$('form').find('input[type="submit"]').val('Wait...');
Or
use :submit selector
Your button has an id, why aren't you using that selector?
$("#trigger").val("Wait...");
Is the form itself loaded via ajax? If so then delegate.
$(document).on("customevent", "#trigger", function() {
$(this).val("Wait...");
});
and then in the beforesubmit just $(document).trigger("customevent");
I have a Ajax Submit button which shows up with a message Successfully Added. View Cart when clicked on Add to cart button. Right now Successfully Added. and View Cart message is show as a single button. Is there any way to separate out Successfully Added and View Cart button?
Add to cart button code:
<fieldset class="add-to-cart-box">
<legend><?php echo $this->__('Add to Cart') ?></legend>
<?php if(!$_product->isGrouped()): ?>
<input name="qty" type="hidden" class="input-text qty" id="qty" maxlength="12" value="1" /></span>
<?php endif; ?>
<button class="form-button" onclick="ajaxSubmit('<?php echo $this->getAddToCartUrl($_product) ?>', this)"><span><?php echo $this->__('Add to Cart') ?></span></button>
</fieldset>
Successfully Added. View Cart message and button code:
<script type="text/javascript">
function ajaxSubmit(url, button){
var pars = '';
var target = '';
var myAjax = new Ajax.Updater(target,url, {method: 'get', parameters: pars});
button.innerHTML = '<span>Successfully Added. View Cart</span>';
button.className = 'form-button-alt';
button.style.marginTop = '6px';
button.attributes["onclick"].value = 'setLocation(\'/checkout/cart/\')';
}
</script>
you are replacing the inner button html
button.innerHTML = '<span>Successfully Added. View Cart</span>';
instead replace the button with two button instances