Inserting Opencart login check/force into JS funtion - javascript

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 } ?>

Related

Bootstrap Modal On Php Submit using Ajax

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

How to validate textarea and radio button in a loop

I need one help. I have some multiple textarea, radio button and dropdown list which are created by clicking on a button. I need to validate them for textarea has blank value, radio button check and dropdown select using JavaScript/jQuery. I am explaining my code below.
<div style="width:24%; float:left; padding:10px;">No of questions :
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" value="<?php if($_REQUEST['edit']) { echo $getcustomerobj->no_of_question; } else { echo $_REQUEST['no_of_question']; } ?>" type="text" onkeypress="return isNumberKey(event)">
</div>
<div style="padding-bottom:10px;">
Questions : <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" onClick="addQuestionField();"><input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-" onClick="deleteQuestionField();">
</div>
<script>
function addQuestionField(){
var get =$("#ques").val();
if(get==null || get==''){
alert('Please add no of questions');
}else{
var counter = 0;
if (counter > 0){
return;
}else{
counter++;
<?php
$status=array("status"=>'1');
$feeddata=$db->kf_answertype->find($ustatus);
?>
<?php
$status=array("status"=>'1');
$feeddatascale=$db->kf_scale->find($ustatus);
?>
for(var i=1;i<get;i++){
$('#container').append('<div><div style="width:24%; float:left; padding:10px;"> <textarea class="form-control" name="questions'+ i +'" id="questions'+ i +'" placeholder="Questions" style="background:#FFFFFF;" rows="2"><?php if($_REQUEST['edit']) { echo $getcustomerobj->questions; } else { echo $_REQUEST['questions']; } ?></textarea></div><div style="float:left;margin-top:37px;"><div style="float:left; margin-right:10px;"><?php foreach($feeddata as $v){?> <input type="radio" name="answer_type'+i+'" id="answer_type0" onClick="selectScale(this.value,'+i+');" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?> <?php }?></div><div style="float:left; margin-top:-10px;display:none;" id="scaleid'+i+'"><select class="form-control" id="nscale'+i+'" name="noofscale'+i+'"><option value="">Select Answer Type</option><?php foreach($feeddatascale as $v){ ?><option value="<?php echo $v['_id']; ?>" <?php if($getcustomerobj->no_of_scale == $v['_id'] or $_REQUEST['no_of_scale'] == $v['_id']){ print 'selected'; } ?>><?php echo $v['noofscale']; ?></option><?php } ?></select></div><div style="clear:both;"></div></div><div style="clear:both;"></div></div>');
}
}
}
}
</script>
Here when user will click on + button some multiple textarea, radio button and dropdown list dynamically. Here I need when my form will submit I need to check the validation of all whether those are not blank/checked. Please help me.
From what I can understand from the question, I have deduced that you have a form with input controls. The user can press '+' to replicate/clone a div containing all input thus providing an additional form filled with input controls. If this is the case, you can use the following for validation to ensure that all currently visible input controls have been filled with data.
Pre-requisite: Ensure that all forms are assigned the same class name.
Example:
var visibleDivs = $(".DisplayableDiv:visible"); // .DisplayableDiv name of all class containing form controls
var hasValue = true;
// loop over all visible divs
for(i = 0; i < visibleDivs.length; ++i)
{
$(visibleDivs[i]).find('input')
.each(function() { // iterates over all input fields found
if($.trim($(this).val()).length === 0) {
hasValue = false; // if field found without value
break;
}
});
}
if(hasValue === false) {
// handle validation logic here (prompt user to complete all input areas etc)
}
There are a number of problems with your code, but in particular you have the wrong approach.
Note that after the page is rendered and the DOM displayed, PHP has finished and no more PHP can run. So how do you do more stuff in PHP? Two options:
(1) Forms, or
(2) AJAX - it's pretty easy, see these simple examples
Ajax sends specified data to a backend PHP file. Note that you cannot post AJAX data to the same file that contains the AJAX javascript. You must use a second PHP file.
The backend PHP file receives the data, uses the incoming data (e.g. num of ques) to create new HTML in a $variable and then just echos that $variable back to the originating file, where it is received in the .done() function (aka the success function), as a variable (e.g. recvd). If you receive HTML code, then that code can be injected back into the DOM via methods like .append() or .html() etc.
Here is a rough approximation of how you might proceed.
$('#plus').click(function(){
addQuestionField();
});
$('#minus').click(function(){
deleteQuestionField();
});
function addQuestionField(){
var numques = $("#ques").val();
if(numques==null || numques==''){
alert('Please add no of questions');
return false;
}
var myAj = $.ajax({
type: 'post',
url: 'ajax.php',
data: 'numques=' + numques,
});
myAj.done(function(recvd){
$('#container').append(recvd);
});
}
<style>
#d1 {width:24%; float:left; padding:10px;}
#d2 {padding-bottom:10px;}
</style>
<div id="d1" style="">No of questions :
<input id="ques" class="form-control" placeholder="no of question" type="text" />
</div>
<div id="d2">
Questions :
<input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+">
<input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-">
</div>
Validating user-submitted data is a separate issue, but the basic idea is shown above when the $('#ques') value is validated -- if empty, we alert a message and return false to return control to the user.
Note that you can validate either client-side (jQuery) or server-side (PHP). The difference is that when you validate client-side, you can return control to the user without losing anything they typed. When you validate server-side, you must send back all the user-typed data and re-populate the controls manually (i.e. it's a lot more work)
Also note that if you validate client side, and you have ANY concern about hacking, then you must also re-validate server side because client-side validation can be easily hacked. But if it fails server-side validation you will know the user monkeyed with your validation and you can be less kind about re-populating their entries...
Here is a basic example of client-side field validation.

Multiple "link" submit buttons in one form

I would like to create a form with multiple submit link buttons. I know it can be done by using and specifying the name of <button> or <input type="button"> something like this:
In HTML:
<form action="" method="get">
Other form elements here...
<button type="submit" name="activated">Activated</button>
<button type="submit" name="pending">Pending</button>
<button type="submit" name="suspended">Suspended</button>
</form>
In PHP:
<?php
if(isset($_GET["activated"])) {
Activated codes here...
}
elseif(isset($_GET["pending"])) {
Pending codes here...
}
elseif(isset($_GET["suspended"])) {
Suspended codes here...
}
?>
I want the submit buttons to be done by using link, not <button> or <input type="submit"> something like this:
Activated
Pending
Suspended
I heard that it can be done by using JavaScript or JQuery but I don't know how, anyone knows?
Update: What I want to happen is when I clicked the "Activated" link for example, I want only to process the logic under isset($_GET["activated"]).
The reason behind:
The reason why I want to have a submit link buttons instead of normal submit button tags is that, I want to use this bootstrap dropdown button style to change the status of user(s) on table:
and it is based on links, so that's why.
PS: Sorry for bad English, not my native language.
You could use data attributes on your anchors, then load that attribute into a hidden field to check in your PHP code.
<form action="" method="post">
Activated
Pending
Suspended
<input type="hidden" id="actionName" name="actionName" value="" />
</form>
$('.anchor-btn').click(function(e) {
e.preventDefault();
$('#actionName').val($(this).data('name'));
$('form').submit();
});
<?php
if($_POST['actionName'] == "activated") {
Activated code goes here
}
...etc.
?>
Yes you can submit the form using jquery just add a class to your buttons and add a click handler
$(document).ready(function() {
$( ".buttons_class" ).click(function() {
$( "#target_form" ).submit();
});
});
so your buttons will look like this
<button type="button" name="activated" class="buttons_class">Activated</button>
<button type="button" name="pending" class="buttons_class">Pending</button>
<button type="button" name="suspended" class="buttons_class">Suspended</button>
if using anchors
Activated
Pending
Suspended
And in javascript
$(document).ready(function() {
$( ".buttons_class" ).click(function(e) {
e.preventDefault(); //This will stop the default anchor action
$("#target_form").attr("action", "yourphpfile.php?"+$(this).text()+"=true"); //This will send the text inside the anchor as a GET param.
$( "#target_form" ).submit();
});
});
However if I were you I would consider using POST instead of GET for this. and do something like this
$( ".buttons_class" ).click(function(e) {
e.preventDefault(); //This will stop the default anchor action
var paramName = $(this).text(); //get text inside anchor
$( "#target_form" ).submit(function(eventObj) {
$('<input />').attr('type', 'hidden')
.attr('name', paramName);
.attr('value', "something")
.appendTo('#form');
return true;
}); //Add hidden field
});
Change your isset to $_POST instead of $_GET, it will then use the name attributes.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['test1'])) {
###
} else if ($_POST['test2']) {
###
}
}
<form method="post">
<input name="test1" type="submit" value="TEST 1" />
<input name="test2" type="submit" value="TEST 2" />
</form>

set html button state based on query

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>

Disable another button once it has successfully submitted the form

I have a form with 2 buttons: Approve and Reject.
<input type="button" name="Approve" value="Approve" onClick="location.href='approve.php?user=<?php echo $row['icnum'];?>&states=1'">
<input type="button" name="Reject" value="Reject" onClick="location.href='approve.php?user=<?php echo $row ['icnum'];?>&states=2'">
I want to disable the "Reject" button once the "Approve" button is clicked. So, the user cannot reject the form again after it has been approved.
I have tried several attempts, like:
<input type="button" value="Send" onclick="javascript=this.disabled = true; form.submit();">
But this code does not work for me. Even if it's actually working, the button is just disabling itself, not the other button.
I'm using Chrome. Any idea on how to solve this?
EDIT: This is my process form in php.
<?php session_start();
include('../include/dbconnect.php');
$user = $_GET['user'];
$states = $_GET['states'];
if($user){
$approve = "UPDATE student SET status='$states' WHERE icnum='$user'";
$result = mysql_query($approve) or die(mysql_error());
if ($result) {
?>
<script type="text/javascript">
window.location = "index.php"
</script>
<?php }
}
?>
What can I edit into these codes if the action is ran in the server-side?
Remove the javascript= from OnClick. You only need javascript: (colon not =) for anchors' hrefs
<input type="button" value="Send" onclick="this.disabled=true; formName.submit();">
In jQuery:
$('input[name=Approve]').click(function () {
$('input[name=Reject]').prop({disabled: true});
});
Try below
<asp:Button ID="cmdSubmit" runat="server" Text="Submit" onclick="btnSumbit_Click" onclick="btnSumbit_Click" OnClientClick="this.style.display = 'none';"/>

Categories

Resources