Materialize switch - php

Good day.
Trying to create a checkbox (materialize switch), which, if you change it, submits the form. The problem is, that it returns the value as $_POST['statusValue'] ONLY if its originally not checked, if it is - returns null.
Any ideas?
<div class="switch">
<form method="post">
<label style="font-size: 10px">
Off
<input type="checkbox" value="<?php echo $q->questionnaire->questionnaire_id?>" name="statusValue" id="statusValue" onclick='this.form.submit()' <?php echo $q->questionnaire->questionnaire_status == 1 ? 'checked="checked"' : '';?»
<span class="lever"></span>
On
</label>
</form>
</div>

Your question is not clear. I guess what you are trying to achieve in check if the checkbox on the HTML was checked or not by the user.
Below, I wrote you a simple code of how achieving that. After submitting the form the $statusValue variable will contain either "checked" or "not checked" depending on what the user did on the HTML page.
In your HTML (frontend):
<div class="switch">
<form method="post">
<label style="font-size: 10px">
<input type="checkbox" name="statusValue" onChange="this.form.submit()" />
<span class="lever"></span>
</label>
</form>
</div>
In your php (backend):
<?php
isset($_POST['statusValue'])
$statusValue = "checked";
else
$statusValue = "not checked";
?>
If I misunderstood you, comment here so I can help you further.

In this html code I create a function that has two parameters id and status that will pass throught it.
<div class="switch">
<form method="post">
<label style="font-size: 10px">
Off
<input type="checkbox" value="<?php echo $q->questionnaire->questionnaire_id?>" name="statusValue" id="statusValue" onclick="changeStatus('<?php echo $q->questionnaire->questionnaire_id ?>,'<?php echo $q->questionnaire->questionnaire_status ?>')" <?php echo $q->questionnaire->questionnaire_status == 1 ? 'checked="checked"' : '';?»
<span class="lever"></span>
On
</label>
</form>
</div>
Invoking the function changeStatus using Ajax function and avoiding to refresh the page in that time, you press the switch.
<script>
function changeStatus(id,status){
if(habilitado==2) {
var url = 'admin/funciones/desbloquearUsuario.php';
$.ajax({
type:'POST',
url:url,
data:{idUser:id},
error:function(){
alert("It coudn't be disabled");
}
});
}else {
var url = 'admin/funciones/bloquearUsuario.php';
$.ajax({
type: 'POST',
url:url,
data:{idUser:id},
error:function(){
alert("it couldn't be blocked");
}
});
}
}
}
</script>
For this php file desbloquear.php I unblock Users setting value 1
require_once "../../funciones/conexion.php" ;
conexion();
$idUser = $_POST['idUser'];
$habilita = 'UPDATE public."USUARIO" SET "Habilitado"=\'1\' WHERE
"ID"=\''.$idUser.'\'';
pg_query($habilita);
In your php code you can use this. Well in this case, in this php file I block users with the value 2 in my BD
<?php
require_once "../../funciones/conexion.php";
conexion();
$idUser = $_POST['idUser'];
$deshabilita = 'UPDATE public."USUARIO" SET "Habilitado"=\'2\' WHERE
"ID"=\''.$idUser.'\'';
pg_query($deshabilita);

Related

Posting form with ajax to self with no reload and filter back in form data with relevant business names

I'm trying to auto submit a form when a user clicks checkbox select (with ajax). I want to prevent the default reload, and then attempt to use the category checkbox values to repopulate the relevant business names, which the user will be able to select to retrieve the full company details.
Quite frankly, it's been driving me a bit mad! I've tried both post and get methods, and 100 other workarounds and I just can't get it to work
If I remove the e.preventDefault(); from my on submit function then the page reloads and I get the correct info across both category and name via $_GET. But problem I have is getting the ajax data passed back to the var_dump($_GET). It always stays empty aside from the URL.
Am I going about this in the wrong way?
Here's my form:
<form id="businessSearch" action="" type="get" enctype='multipart/form-data'>
<div class="col-md-6 business-cat">
<h2>Business Category</h2>
<div class="business-inner">
<input id="category" class="main" <?php if ( !isset($_GET['category']) || ($_GET['category'] == 'All')) { echo 'checked'; } ?> type="checkbox" name="category" value="All" /> All <br>
<?php foreach($data['businessCats'] as $category) : ?>
<input id="category" class="main" <?php if ( isset($_GET['category']) && ($_GET["category"] == $category->BusinessCategory)) { echo 'checked'; } ?> type="checkbox" name="category" value="<?php echo $category->BusinessCategory; ?>"> <?php echo $category->BusinessCategory; ?><br>
<?php endforeach; ?>
</div>
</div>
<div class="col-md-6 business-name">
<h2>Company Name</h2>
<div class="business-inner">
<?php if( isset($_GET['category']) && ($_GET['category'] != 'All')) : ?>
<?php foreach($data['businessCategoryListing'] as $businessCatListing) : ?>
<input id="name" class="sub" <?php if (isset($_GET["name"]) && ($_GET["name"] == $businessCatListing->company_name)) { echo 'checked'; } ?> type="checkbox" name="name" value="<?php echo $businessCatListing->company_name; ?>"> <?php echo $businessCatListing->company_name; ?><br>
<?php endforeach; ?>
<?php else: ?>
<?php foreach($data['getAllBusinessListings'] as $getAllBusinessListings) : ?>
<input id="name" class="sub" <?php if (isset($_GET["name"]) && ($_GET["name"] == $getAllBusinessListings->company_name)) { echo 'checked'; } ?> type="checkbox" name="name" value="<?php echo $getAllBusinessListings->company_name; ?>"> <?php echo $getAllBusinessListings->company_name; ?><br>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
</form>
<?php if ( isset($_GET['category']) && isset($_GET['name']) ) : ?>
<div class="clearfix"></div>
<div class="col-md-12 business-details">
<h2>Details</h2>
<div class="business-inner">
<h2><?php echo $data['businessListing']->BusinessName ?></h2>
<?php echo $data['businessListing']->BusinessDescription . '<br>' . $data['businessListing']->BusinessPhone . '<br>' . $data['businessListing']->BusinessWebsite . '<br>' . $data['businessListing']->BusinessAddress1 . '<br>' . $data['businessListing']->BusinessGrid . '<br>' ; ?>
</div>
</div>
<script>
$('input.main, input.sub').on('change', function() {
$('#businessSearch').trigger('submit');
});
$(document).ready(function () {
$('#businessSearch').on('submit', function(e) {
e.preventDefault();
var category = $('#category:checked').val(),
name = $('#name:checked').val();
$.ajax({
type: 'get',
data: { ajax: 1,category: category, name: name},
success: function(response){
//$('#response').text('category : ' + response);
}
});
});
});
</script>
I can see my output in the network tab in
I just cannot get it to filter back in the $_GET var_dump and then get the results to update correctly on my page whilst preventing the page reload.
Finally, here is how I'm calling that data from my db
public function getBusinessByCategory() {
$category = isset($_GET['category']) ? $_GET['category'] : '';
$this->db->query('SELECT * FROM business_directory WHERE category = :category and publish_status = "live" ORDER BY company_name ASC');
$this->db->bind(':category', $category);
$results = $this->db->resultSet();
return $results;
}
Can anyone give any pointers? I'm really stuck, and my head is about to explode!!!
If you want submit a form without reload the page then first do not user button type "submit" in HTML form. Instead of that use normal button and execute your ajax call when user click on that button.
If you will submit button then it will reload the page and it's default behaviour of the submit button type.

After ajax successful... how to recheck php if-else condition without refreshing page

when i click "add to cart" button... ajax successfully add product in database. and as a result he should recheck again php if-else condition. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the php code:
<?php
if(isset($products) && is_array($products) && count($products)){
$i=1;
foreach ($products as $data) { ?>
<div class="col-lg-3 col-md-4 col-sm-6" ">
<div class="tile">
<img class="prod_image" src="<?php echo base_url(); ?>../upload/<?php echo $data['image'] ?>">
<div class="prod_detail">
<p class="prod_name"><?php echo $data['name'] ?></p>
<p class="prod_name"><?php echo $data['weight'] ?></p>
<p class="prod_name"><?php echo $data['price'] ?></p>
<?php
//if product already add in cart
$isincart = get_product_from_cart($data['id']);
if($isincart < 1) { ?>
<button class="btn btn-primary" onclick="addtocart(<?= $data['hid'];?>,<?= $data['weight'];?>,<?= $data['price'];?>)">Add to cart</button>
<?php } if ($isincart > 0){
?>
<div id="prod_quant" class="add_btn_sec">
<form id="myform" method="POST" action="javascript:void(0)">
<input type="submit" onclick="quantitydec(<?= $data['id']; ?>)" value="-" class="qtyminus" field="quantity<?= $data['id']; ?>">
<input type="text" id="quantity<?= $data['id']; ?>" name="quantity<?= $data['id']; ?>" value="<?php echo ($isincart) ; ?>" class="qty">
<input type="submit" onclick="quantityinc(<?= $data['id']; ?>" value="+" class="qtyplus" field="quantity<?= $data['id']; ?>">
</form>
</div>
<?php
}
?>
</div>
</div>
</div>
<?php } $i++; } ?>
and ajax script is here
<script type="text/javascript">
function addtocart(p_id,p_weight,p_price)
{
$.ajax({
type: "POST",
url: "<?php echo site_url('index.php/addtocart/addtocart_ajax');?>",
data: {'id': id, 'name': name, 'p_wight': p_weight, 'p_price': p_price},
dataType: 'JSON',
success: function(response){
/*do something here*/
}
});
}
</script>
Can anyone suggest me how to recheck " if($isincart < 1) " condition without refreshing the page?
First of all,
PHP - is a server side language. PHP codes are interpreted at the server before the html file is sent to the browser. Please note that browser cannot interpret php codes.
Now AJAX - Ajax is a client-side script that communicates to and from a server/database without the need for a complete page refresh. The best definition I’ve read for Ajax is “the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page.”
Now coming to your question, if you want to run a php code after the AJAX success, you would need to send another AJAX request as the success function of the first AJAX request.
Hope this makes sense.

WordPress Plugin Admin Page - How to check if a checkbox is checked?

I added a checkbox to the setting page like this:
function abc_render_admin(){
global $abc_options;
ob_start(); ?>
<form id="abc-form" action="" method="POST">
<div>
<?php $options = get_option('abc_options'); ?>
<p>
<input id="abc_settings[update_date]" name= "abc_settings[update_date]" type="checkbox" value="1" <?php checked('1', $abc_options['update_date']); ?>/>
<label class="description" for="abc_settings[update_date]">
<?php _e('Option 1', 'abc'); ?>
</label>
</p>
<button id="abc_submit" name="abc-submit" class="button-primary"> <?php _e('Submit', 'abc'); ?> </button>
</div>
</form>
<div id="abc_results"></div>
<?php echo ob_get_clean();
}
The checkbox display nicely on the admin page. However, I couldn't figure out the correct way to check if the checkbox is checked. I've tried this (not working):
function abc_process_ajax(){
if($abc_options['update_date'] == true){
echo 'Checked';
}
}
add_action('wp_ajax_abc_show_results', 'abc_process_ajax');
I've also tried doing print_r($abc_options); but got nothing.
What is the correct way of checking a checkbox? I'm not very familiar with WordPress, any suggestions would be much appreciated.
By the way, the Ajax is working fine. Here's the script:
function abc_load_scripts($hook){
global $abc_settings;
if($hook != $abc_settings)
return;
wp_enqueue_script('abc-ajax', plugin_dir_url(__FILE__) .'js/abc-ajax.js', array('jquery'));
wp_localize_script('abc-ajax', 'abc_vars', array(
'abc_nonce' => wp_create_nonce('abc-nonce')
)
);
}
add_action('admin_enqueue_scripts', 'abc_load_scripts');
abc-ajax.js
jQuery(document).ready(function($){
$('#abc-form').submit(function(){
data = {
action: 'abc_show_results',
abc_nonce: abc_vars.abc_nonce
};
$.post(ajaxurl, data, function(response){
$('#abc_results').html(response);
});
return false;
});
});

How do I update input values with db values after a select OnChange with idealforms?

I'm using idealforms from elclanrs and I have a select which is filled from a database. OnChange I want to update the value of the input fields with information from the database. In this case, firstname, lastname. I tried it with AJAX but that didn't work out because when the form values where getting renewed, the whole idealforms makeup of the form vanishes.
I looked through stackoverflow and saw it was a fairly common problem but I still can't seem to work it out. I used this and it didn't work, maybe because I placed it in the wrong order?
This is my code:
<form id="my-form" action="EditAccountHandler.php" method="post">
<?php
include 'conn/dbConnect.php';
echo '<div><label>Gebruikers</label><select id="gebruiker" selected="$sUsername" name="selectedUser" onchange="updateInput(this.value)">';
$sqEditUser = mysql_query("SELECT * FROM account a, persoon p WHERE a.idSuper = p.idUser", $con);
while($row = mysql_fetch_array($sqEditUser))
{
$iIdUser = $row['idUser'];
$sFirstname = $row['Voornaam'];
$sLastname = $row['Achternaam'];
$sUsername = "{$sLastname}, {$sFirstname}";
echo "<option value='$iIdUser'>$sUsername</option>";
}
echo "</select></div>";
?>
<script>
function updateInput(<?= json_encode($sFirstname); ?>)
{
document.getElementById("naam").value = <?php echo json_encode($sFirstname); ?>;
}
</script>
<div><label>Voornaam</label><input id="naam" name="naam" type="text"/></div>
<div><label>Achternaam</label><input id="anaam" name="anaam" type="text"/></div>
<div>
<button id="reset" type="button">Reset</button>
<button type="submit">Wijzigen</button>
</div>
</form>
This is what I'm trying to achieve:
Example picture
I'm not sure about what I am doing wrong. Can yo guys help me?
Edit
Removed code that was double in comparison with the first codesnippet.
Added echo
Removed action="EditAccountHandler.php"
Added idealforms validation code
Replaced with final code
<div id="main">
<h3>Wijzig Account</h3><br />
<form id="myselect" action="" method="post">
<div>
<label>Gebruikers</label><select id="gebruiker" selected="$sUsername" name="selectedUser" onchange="this.form.submit()">
<?php
include 'conn/dbConnect.php';
$sqUser = mysql_query("SELECT * FROM account a, persoon p WHERE a.idSuper = p.idUser", $con);
while($row = mysql_fetch_array($sqUser))
{
$iIdUser = $row['idUser'];
$sFirstname = $row['Voornaam'];
$sLastname = $row['Achternaam'];
$sUsername = "{$sLastname}, {$sFirstname}";
echo "<option value='$iIdUser'>$sUsername</option>";
}
?>
</select>
</div>
</form>
<script>
var options = { onFail: function(){alert('Selecteer een persoon')}};
var $myform1 = $('#myselect').idealforms(options).data('idealforms');
$myform1.focusFirst();
</script>
<?php
if(!empty($_POST['selectedUser']))
{
$sqGetUser = mysql_query("SELECT * FROM persoon WHERE idUser = '$_POST[selectedUser]'", $con);
while($row = mysql_fetch_array($sqGetUser))
{
$sFname = $row['Voornaam'];
$sLname = $row['Achternaam'];
}
?>
<form id="my-form" action="EditAccountHandler.php" method="post">
<div><label>Voornaam</label><input id="naam" name="naam" value="<?php echo htmlspecialchars($sFname); ?>" type="text"/></div>
<div><label>Achternaam</label><input id="anaam" name="anaam" value="<?php echo htmlspecialchars($sLname); ?>" type="text"/></div>
<div>
<label>Rechten</label>
<label><input type="radio" name="rechten" value="Administrator"/>Administrator</label>
<label><input type="radio" name="rechten" value="Contentmanager"/>Contentmanager</label>
<label><input type="radio" name="rechten" value="Administratie"/>Administratie</label>
<label><input type="radio" name="rechten" value="Medewerker"/>Medewerker</label>
<label><input type="radio" name="rechten" value="Klant" checked/>Klant</label>
<label><input type="radio" name="rechten" value="Gast"/>Gast</label>
<label><input type="radio" name="rechten" value="MedeKlant"/>MedeKlant</label>
</div>
<div>
<button id="reset" type="button">Reset</button>
<button type="submit">Wijzigen</button>
</div>
</form>
</div>
</div>
<script>
var options =
{
onFail: function()
{
alert( 'Vul alle velden correct in.' )
},
inputs:
{
'anaam':
{
filters: 'required name',
},
'naam':
{
filters: 'required name',
},
}
};
var $myform = $('#my-form').idealforms(options).data('idealforms');
$('#reset').click(function(){ $myform.reset().fresh().focusFirst() });
$myform.focusFirst();
</script>
<?php
}
?>
I think you are messing client code with server code.
Once the onChange event is fired, you have to reload the page for example onChange="this.form.submit()" and you verify if(!empty($_POST["selectedUser"])) then you fill the fields of the form with the data you can obtain with a new SQL query, where id = $_POST["selectedUser"].
In this case you don't need the updateuser function.
If you use AJAX, you would need the updateuser function, but you have got to get rid of the json_encode methods which execute on server, and with ajax everything is in the client part. It would be simply: "function updateuser(id)".
You can use jquery to do the ajax call to get the info, and then you fill the form fields.
EDIT:
Examining the new code you provide. I see one error, you are using htmlspecialchars function but you are not echoing it, ;-). You should use "echo ...".
For the form, you should use "this.form.submit()" if you are inside the form labels.
If you use jquery it would be something like this:
<script type="text/javascript">
$("#selectedUser").change(function()
{
if(this.form.elements['selectedUser'].value!="")
{
this.form.submit();
}
});
</script>

Change the value of 1 input into the value of another input on click

another JQuery question, I wanted to change the value of the hidden input based on the value of another hidden input. I'm having some trouble with this already. here's my code so far. This is not working but I think you can already get the idea of what I'm trying to do with this:
HTML code:
<div>
<div id="search_result_fake_container">
<div id="search_result_fake_div2"></div>
<form method="GET" id="getattendees">
<input type="text" id="search_result_fake2" value="<?php if(!empty($event_selected)){echo $event_selected;} else{echo "Select Event";}?>" name="event_name">
<input type="hidden" id="search_result_fake2_id" value="<?php if(!empty($event_selected)){echo $event_selected;} else{echo "0";}?>" name="event_id">
</form>
</div>
<div id="search_result_present_list2">
<?php foreach ($events as $events1): ?>
<div class="search_result_list_item2" id="search_result_item_12" style="text-align:center;"><?php echo $events1['event_name']; ?></div>
<input type="hidden" id="event_id" value="<?php echo $events1['event_id']; ?>">
<?php endforeach ?>
</div>
</div>
and the JQuery:
$("#search_result_fake_div2").live("click", function () {
$("#search_result_present_list2").show("fast");
$('body').one('click',function() {
$("#search_result_present_list2").hide();
});
event.stopPropagation();
});
$(".search_result_list_item2").live("click", function () {
$("#search_result_fake2").val($(this).html());
$("#search_result_fake2_id").val($("#event_id").val());
$("#getattendees").trigger('submit');
$("#search_result_present_list2").hide();
});
I use GET just to check if the values are moving and I'm not that sure if the line $("#search_result_fake2_id").val($("#event_id").val()); is really working.
Add the event parameter to your #search_result_fake_div2 click handler, like so:
("#search_result_fake_div2").live("click", function (event) {
^--------HERE
Because otherwise you will have a javascript runtime error when you try to use it later in:
event.stopPropagation();

Categories