Disabling HTML button on condition with PHP (WordPress Plugin) - javascript

I'm making a custom plugin for a WordPress powered page to disable a certain button on condition.
Context: To disable place order button if the user breached a certain credit limit.
I'm expecting that upon entering checkout page, the plugin will fire and check if the user exceeded the credit limit. If yes, it will then alert the user and disable the place order button.(OR create an overlay OR any other methods)
For now I have this:
function credit_limit_check()
{
/** page 13 is the check out page ID*/
if (is_page(13)) {
if (is_user_logged_in()) {
/* For reference purpose*/
/* get_user_meta( int $user_id, string $key = '', bool $single = false ) */
$ID = get_current_user_id();
$credit_val = get_user_meta($ID, 'credit_limit', true);
$outstanding_val = get_user_meta($ID, 'outstanding_credit', true);
$credit_breach = $credit_val - $outstanding_val;
if ($credit_breach <= 0) {
/*disable checkout button if not enough credit limit*/
echo '<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Place order" data-value="Place order" disabled>Place order</button>';
echo '<script>alert("You have exceeded your credit limit, please make sure you have no outstanding bill")</script>';
} else {
print_r("Huzzah! Good news! You have enough credit to proceed!");
}
} else {
print_r("Please login with your account before proceeding.");
}
}
}
The only problem is that the functions actually creates an extra button on top of the page instead of disabling the original button. So I am wondering if this is actually doable, or do I have to modify the html files directly to achieve what is intended.(Preferably not)
Now, I do see some similar questions, but all of them require directly applying php in the html tags. It is not applicable for my situation as I am creating a wordpress custom plugin. (Which is an individual php file).

Well I would solve this in two parts.
Step 1 . Adding proper notices.
function add_notices_for_checkout_credit()
{
if(is_checkout()) {
if (is_user_logged_in()) {
$ID = get_current_user_id();
$credit_breach = getUserCredit($ID);
if ($credit_breach <= 0) {
wc_add_notice( 'You have exceeded your credit limit, please make sure you have no outstanding bill', 'error' );
} else {
wc_add_notice( 'Huzzah! Good news! You have enough credit to proceed!', 'success' );
}
}
}
}
add_action( 'wp', 'add_notices_for_checkout_credit');
function getUserCredit($ID) {
$credit_val = get_user_meta($ID, 'credit_limit', true);
$outstanding_val = get_user_meta($ID, 'outstanding_credit', true);
$credit_breach = $credit_val - $outstanding_val;
return $credit_breach;
}
With less credit it shows.
When sufficient credit it shows.
Step 2 . Restricting button
function change_button($order_button)
{
if (is_user_logged_in()) {
$ID = get_current_user_id();
$credit_breach = getUserCredit($ID);
if ($credit_breach <= 0) {
$order_button_text = __( "No Credit", "woocommerce" );
$style = ' style="color:#fff;cursor:not-allowed;background-color:#999;text-align:center"';
return '<a class="button alt"'.$style.' name="woocommerce_checkout_place_order" id="place_order" >' . esc_html( $order_button_text ) . '</a>';
}
}
return $order_button;
}
add_filter( 'woocommerce_order_button_html', 'change_button');
This will disable the button, and you should be good to go.
Don't check for guest in your code, change it from your woocommerce setting. In Account setting mark it compuslory to login when checking out.
PS : For extra security use woocommerce_checkout_update_order_review to check if its a valid request because someone can create a submit button using developer tool.

Related

Change PHP variable using javascript or AJAX on the same page

I know this question has been asked alot of times, but I think in my case, I'm dealing with something different, or better saying, I need something different.
I'm using an open source that works as appointments booking but unfortunately, the client can choose the service and not the duration of it. I can recreate the same service by manually adding it more times with different minutes length but that way, in the dropdown menu, would be present alot of options and that's not what I'm looking for as a workaround.
So, what I thought of, was using a dropdown to select the time, and based on that selection, on the services dropdown menu, would show the ONLY the corresponding ones based on time.
THe site looks like this:
site
What I'm looking for, is that whenever I select the nr of hours... I ONLY GET the services that are part of that hour and not all of them.
I'm ok with using a button that refreshes the page as far as that works, but I can't create another file that then redirects here.
This is the part of the code interested in that:
<select id="select-service" class="col-xs-12 col-sm-4 form-control">
<?php
// Group services by category, only if there is at least one service with a parent category.
$has_category = FALSE;
foreach($available_services as $service) {
if ($service['category_id'] != NULL) {
$has_category = TRUE;
break;
}
}
if ($has_category) {
$grouped_services = array();
foreach($available_services as $service) {
if ($service['category_name'] == '2 HOURS' || $service['category_name'] == '1 HOUR' || $service['category_name'] == '3 HOURS') {
if (!isset($grouped_services[$service['category_name']])) {
$grouped_services[$service['category_name']] = array();
}
$grouped_services[$service['category_name']][] = $service;
}
}
// We need the uncategorized services at the end of the list so
// we will use another iteration only for the uncategorized services.
$grouped_services['uncategorized'] = array();
foreach($available_services as $service) {
if ($service['category_id'] == NULL) {
$grouped_services['uncategorized'][] = $service;
}
}
foreach($grouped_services as $key => $group) {
$group_label = ($key != 'uncategorized')
? $group[0]['category_name'] : 'Uncategorized';
if (count($group) > 0) {
echo '<optgroup label="' . $group_label . '">';
foreach($group as $service) {
echo '<option value="' . $service['id'] . '">'
. $service['name'] . '</option>';
}
echo '</optgroup>';
}
}
} else {
foreach($available_services as $service) {
echo '<option value="' . $service['id'] . '">' . $service['name'] . '</option>';
}
}
?>
</select>
I only use a single AJAX function for my platform. Below is a minimal example:
function ajax(method,url,param_id_container_pos,id_container)
{
var xhr = new XMLHttpRequest();
xhr.open(method,url,true);
xhr.onreadystatechange = function()
{
if (xhr.readyState=='4')
{
var type = xhr.getResponseHeader('content-type').split('/')[1];
if (method=='post')
{
if (type=='json')
{
var j = JSON.parse(xhr.responseText);
console.log(j);//Check your browser's developer network panel.
eval(j.javascript);//eval is frowned upon though just use to call a sequel JS function.
}
}
}
}
}
//Example uses:
ajax('get','admin/?ajax=account','inside','id_target');
var fd = new FormData();
fd.append('ajax','admin_post_account_approval');
fd.append('parameter1',object1);
fd.append('parameter2',object2);
ajax('post',path+'admin/',fd);
Your goal is to make your code minimal and highly reusable when possible.
In regards to the server and PHP you need to remember: never trust the user. That means you need to verify everything:
<?php
if (isset($_POST['ajax']) && $_POST['ajax']=='admin_post_account_approval')
{
if (!isset($_POST['parameter1'])) {/*error_handling*/}
else if (!isset($_POST['parameter1'])) {/*error_handling*/}
else if (![condition not met]) {}
else
{
if ([all conditions met])
{
header('Content-Type: application/json');
$array = array('javascript'=>'alert(\'Just a JavaScript alert triggered by PHP.\');');
die(json_encode($array));
}
}
}
?>
Server side code, PHP should be thought of like real life: always fail first and test the conditions for length, proper characters or improper characters in form parameters, etc.
Additionally I highly recommend having the server respond with JSON as I generally illustrated in the code above. Because I only write my own code and don't work with other people's code this is more of a generic response than attempting to target whatever software you're working with. Regardless if you enable error reporting and pay attention to your developer tools in whichever browser you're using you'll get there. Good luck.

how to change page title in wordpress

Im trying to change the_title() for my wordpress website page, however it changes all the text and I only what to change 'ORDER' to 'QUOTE' and leave the order number '#3344'. Could anyone help me with my if statement.
<?php
// Changeing Order title to quote
$page_id = get_the_ID();
if($page_id == '49')
{
$original_title = get_the_title();
$new_title = str_replace("ORDER","QUOTE","ORDER");
echo $new_title;
}
else {
the_title();
}
?>
Please have a close look at the docs. However - you have to use the wp_title() function:
Example code:
wp_title( string $sep = '»', bool $display = true, string $seplocation = '' )
Parameters:
$sep (string) (Optional) default is '»'. How to separate the various items within the page title.
$display (bool) (Optional) Whether to display or retrieve title.
(string) (Optional) Direction to display title, 'right'.
I'm pretty sure wp_title will do the job right :)
Some more information you can find here: !! hit me !!

How to execute button type

so i am trying to change my current design for an IoT porject i am experimenting with.
currently i am using "submit" as my button type but i don't like how the page refreshes.
so i did some digging online and found that ajax was my solution using the "button" type.
however i am very unfamiliar with jquery or ajax so im trying to do this.
currently this is my php function that captures the submit button.
if(isset($_POST['button']))
{
$id = $_POST['button'];
$sql = mysql_query("SELECT * FROM device WHERE Username = '".$_SESSION['Username']."' && DeviceID = '".$id."'");
$productCount = mysql_num_rows($sql);
if ($productCount > 0)
{
$row = mysql_fetch_array($sql);
$status = $row["Status"];
$et = "";
if($status == 1)
{
$et = "a";
$status = 0;
}
else
{
$status = 1;
}
exec("sudo python /var/www/html/light/script'".$id."''".$et."'.py");
mysql_query("UPDATE device SET Status = '$status' WHERE DeviceID = '$id'");
header( "refresh:0.01;" );
//ADD scripts here and also to capture data.
}
}
ignore the header(refresh) feature i was just trying to do a work around but nothing was satisfying my itch.
Any help or tips are greatly appreaciated
EDIT
also this is the button i have atm
<div class="col-md-2">
<button type="submit" name="button" id="button" value="'.$id.'" class="btn btn-default">Toggle '.$ddt.'</button>
</div>
you can use this post it may have what you are looking for and may help you solve your problem just check it out it seems to be talking about the same thing you are looking to do Post link

When using document.location and redirecting using header :location goes into infinite loop in php but not when using javascript

I am trying to redirect user to a different page after he clicks the delete button:-
So what happens is in the table if he clicks the delete button
if ($column_name1 === "DLT")
echo '<td class=center><a href=javascript:confirmDelete("#data/del.php?id=' . $res1[$i]['ID'] .'")></a></td>';<script>
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
</script>
so it basically goes to that URL which calls del.php script which deletes the row corresponding to that ID.
// A snippet of DEL.php
$qry = $report[$choice];
$stmt = oci_parse($connection,$qry);
$r=oci_execute($stmt);
if ($r) {
header( 'Location: http://localhost:8080/index.php#data/test1.php?param=10&edit=1' ) ;
}
when I used the HEADER(' Location: ') for redirecting to a different page in DEL.php it went into an infinite loop redirecting back to del.php
but when I used
if ($r) {
echo "<script>window.location = 'http://localhost:8080/index.php#data/test1.php?param=10&edit=1'</script>" ;
}
This work just fine .. .Why is that .. I am not able to comprehend?
Also if
if ($r) {
include('abc.php');
func_in_abc(1);
echo "<script>window.location = 'http://localhost:8080/index.php#data/test1.php?param=10&edit=1'</script>" ;
}
So calling this abc.php puts it into a loop again and it never redirects to the page I want??

creating a list/array of items from select

Background: I am using HTML/PHP/MySQL/ and Javascript if needed
What I have is a list of approximately 1000 people - I want to let the user select people, and then use the selected people to add them to a database.
I was thinking that each row of the table would have a unique link, and the link would either add that person to an array - or to some kind of list - and then at the end I can take that list and input it into the database..
I really want to have it that when somebody clicks a person's name - it automatically gets added to a list on lets say the left hand side - then once they are done, they can submit the list.
let me know if clarification is needed.
Thanks for your help!
I would go with:
Create page with space for smaller list on the left and list of people on the right.
Display people, with pagination, in table using something like this:
<table id="people">
<tr>
<td id="<?php echo $person['id']; ?>"><?php echo $person['name']; ?></td>
</tr>
</table>
When someone clicks on tr javascript code is executed to send post request with id the person. PHP file responsible for handling this stores the id in the $_SESSION['selectedPeople'] array or removes it from there if it is present. Also, when you click on td, .selected class is toggled and list of selected people on the left side is updated(for example, via getting JSON from PHP file and processing it to display in the table).
you can press submit at any time. It would:
a) take you to the other page and submit the list(you have $_SESSION['selectedPeople'] variable)
b) send an ajax call to page which will process $_SESSION['selectedPeople']
Some code:
selectHandler.php:
<?php
if($_POST && isset($_POST['id'])) {
$id = (int)$_POST['id'];
$action = '';
session_start();
if(!isset($_SESSION['selectedPeople'])) {
$_SESSION['selectedPeople'] = array($id);
$action = 'added';
} else {
if(in_array($id, $_SESSION['selectedPeople'])) {
$_SESSION['selectedPeople'] = array_diff($my_array, array($id));
$action = 'removed';
} else {
$_SESSION['selectedPeople'][] = $id;
$action = 'added';
}
}
echo json_encode(array('action' => $action));
}
?>
Javascript(+JQuery):
$(function () {
$('#people tr').click(function () {
var id = $(this).children('td[id]').attr('id');
$.post("selectHandler.php", { id: id })
.done(function( data ) {
if(data.action == "added") {
$(this).addClass('selected');
} else if(data.action == "removed") {
$(this).removeClass('selected');
} else {
alert('Some kind of error.');
}
}, "json");
refreshSelectedList();
});
});
I hope you get the idea.

Categories