Bootstrap3 toggle switch with ajax update to mysql - javascript

Hello and thank you for looking.
I have the slick new toggle effect for the checkbox (boostrap3) in place.
I would like to update my database each time the toggle is clicked.
A simple On or OFF entry will be perfect. Ofcourse it needs to be without
a page refresh.
HTML:
<span id="setQuickVar1">Enable Notifications<input id="QuickVar1" type="checkbox" class="make-switch" data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF" ></span>
<div id="resultQuickVar1"></div>
Javascript/Ajax:
var handleQuickSidebarToggler2 = function () {
// quick sidebar toggler
$('#setQuickVar1').click(function (e) {
$('body').toggleClass('make-switch');
$.post("quickRightSidebarDBUpdate.php", {"quickVar1a": $('#QuickVar1').val()},
function(data) {
$('#resultQuickVar1').html(data);
});
});
}
(I added a div to show my results)
quickRightSidebarDBUpdate.php
if ($_POST['quickVar1a']):
$quickVar1a = $_POST['quickVar1a'];
$query2 = "UPDATE test SET field1 = " . $quickVar1a . "";
endif;
I think I am close since the Db does get an entry of "on". I can set the check box to "checked" or leave it as above in the code and each time it enters "on" to the BD.
I'm not sure how the entry of "on" is even generated.
Thank you greatly for any help.
ANSWER BELOW...Well it works..but it's not pretty
I did an ugly version of what I want and it's working. Here's what I did.
HTML
<span id="setQuickVar1">Enable Notifications<input id="QuickVar1" type="checkbox" class="make-switch" data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF" <?php echo $checked;?> ></span>
<div id="resultQuickVar1"></div>
Javascript/Ajax
// Handles quick sidebar toggler2
var handleQuickSidebarToggler2 = function () {
// quick sidebar toggler
$('#setQuickVar1').click(function (e) {
$('body').toggleClass('make-switch');
//$(this).toggleClass('make-switch');
$.post("quickRightSidebarDBUpdate.php", {"quickVar1a": $('#QuickVar1').val()},
function(data) {
$('#resultQuickVar1').html(data);
});
});
}
quickRightSidebarDBUpdate.php
$sql = "SELECT * FROM `test`";
$result = mysql_query($sql)or die(mysql_error());
$r = mysql_fetch_array($result);
echo 'Finding:'.$r['quickVar1'].'<br>';
if($r['quickVar1'] == 'ON')
$quickVar1a = 'OFF';
else
$quickVar1a = 'ON';
$sql = "UPDATE test SET quickVar1 ='" . $quickVar1a . "'";
$result = mysql_query($sql)or die(mysql_error());
echo 'Updating To: '.$quickVar1a.'<br>';

Do it like this:
JS
$('#setQuickVar1').on('click', function() {
var checkStatus = this.checked ? 'ON' : 'OFF';
$.post("quickRightSidebarDBUpdate.php", {"quickVar1a": checkStatus},
function(data) {
$('#resultQuickVar1').html(data);
});
});
PHP
if (isset($_POST['quickVar1a'])):
$quickVar1a = $_POST['quickVar1a'];
$query2 = "UPDATE test SET field1 = '" . $quickVar1a . "'";
endif;
code not tested, let me know if does NOT work :)
Update 2
Here is a proper SQL query for the toggle:
$query2 = "UPDATE test SET field1 = '".$quickVar1a."' where field1 != '".$quickVar1a."'";

try this:
HTML:
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<input type="checkbox" data-toggle="toggle" data-onstyle="success" data-offstyle="danger" id="h_activate" name="host" value="1">
<p id="just"></p>
Ajax:
$('#h_activate').on('change', function(event, state) {
var checkStatus = this.checked ? 'ON' : 'OFF';
$.ajax({
url:"check.php",
method:"POST",
data:{"toogle": checkStatus},
success:function(data){
$('#just').html(data);
}
});
});
PHP: check.php
var_dump($_POST); //Allow you to see if php page getting post value or not.
$toogle= mysqli_real_escape_string($conn,$_POST['toogle']);
if(isset($toogle) && $toogle!=='')
{
$sql="update status set toogle='$toogle'";
if($conn->query($sql))
{
echo 'updated success';
}
}else{
echo 'error: not updated';
}
instead of directly updating the database first check ajax giving any response or not.

Related

Hidden div by Country code

I'm not a php-hero so, I try to hidden a section if the user not come from a specific country.
So I did this:
$.get("http://ipinfo.io", function (response) {
$("#country").html(response.country);
}, "jsonp");
<input hidden id="country" type="text" name="country" value="">
This work well and show me the country code (eg. IT).
Now I try to get this value and insert in a IF
$country = $_GET['country'];
$it = "IT";
<?php if ($country != $it): ?>
Code to hidden here...
<?php endif; ?>
What is it wrong here?
Change
$("#country").html(response.country);
to
$("#country").val(response.country);
Because php $_GET saves values.
Also I do not see a reason to do this:
$it = "IT";
<?php if ($country != $it): ?>
You can just do
<?php if ($country != "IT"): ?>
And last but not least you should not access $_GET directly. It is better to use function filter_input which in your case would be filter_input(INPUT_GET, 'country')
EDIT
I do not understand what is the hidden input for. But if you want to show or hide content depending on the country, and you get the country using ajax there is absolutely no need for this input.
Instead of making php condition (<?php if ($country != "IT")...) You can do it in js. Let's say that inside your condition there is a div with class content
Solution
Your html would look more or less like this
<div class="content">
<!-- Your content here -->
</div>
instead of php condition.
And in js you can do something like this
$.get("http://ipinfo.io", function (response) {
if (response.country == "IT") {
$(".content").hide();
}
}, "jsonp");
So what do we do here?
We check if country code equals "IT". If it is true we hide the content. And this is the same what you were doing in php (if country different than IT show content).
EDIT 2
Instead of hiding the div you can remove it
$(".content").remove();
Try hiding via javascript, ajax can run PHP scripts and bring it back into the DOM but you're better off using JS if you don't need a backendscript
$.get("http://ipinfo.io", function (response) {
var country = $("#country").html(response.country);
if(country != "IT"){ document.getElementByID("country").display = "none";
}, "jsonp");
<input hidden id="country" type="text" name="country" value="">
I use the ProcessWise cms, that have their own API. So this answer work only with the ProcessWise cms. ( the best one ;) )
<?PHP
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$user_ip = getUserIP();
echo "ip: " . $user_ip . "<br />";
$http = new WireHttp();
$url = "http://ipinfo.io/{$user_ip}/country";
$response = $http->get($url, ['country' => '']);
echo "Country: " . $response . "<br />";
echo "Successful response: " . $sanitizer->entities($response) . "<br />";
?>

Updating a MySQL Field when a checkbox is clicked using jQuery, AJAX and PHP

I need a checkbox to update a MySQL field from a 1 to 0 and vice versa when clicked. I want to use jQuery/AJAX and PHP to do this so I do not have to have the page re-loaded. I placed the code below but I cannot get it to work. I feel that I am very close.
Note: I know mysql_query is deprecated. This is an older project and I will be converting it soon but need this to work for now.
The form:
if($list_row['online'] == 0) {
echo '<input type="checkbox" name="online" id="' . $list_row['id'] . '" data-toggle="toggle" checked> ';
} else {
echo '<input type="checkbox" name="online" id="' . $list_row['id'] . '" data-toggle="toggle"> ';
}
The jQuery:
<script>
$('.online').mousedown(function() {
var id = $(this).attr('id');
if($(this).attr('checked')) {
var online = 1;
} else {
var online = 0;
}
$.ajax({
type:'GET',
url:'processes/process_item_online.php?',
data:'id= ' + id + '&online='+online
});
});
</script>
The PHP:
include '../connect.php';
// START IF LOGGED IN
session_start();
if (!isset($_SESSION['is_logged_in'])) {
header("location: login.php");
} else {
$login = true;
}
$id = $_GET['id'];
$online = $_GET['online'];
mysql_query("UPDATE `store_items` SET online=$online WHERE id='$id'");
Problem solved by using the $(document).ready(function() { code before the jquery.

How can I make the delete buttons fully functional with right ID using php, AJAX or MySQL?

I am having a little problem with this, every delete button is supposed to delete the record of its own id. If we click 164 it must delete the record of 164. It works fine if I remove the ajax and ask the form to validate directly, but if I use AJAX it only deletes the record of 1st record regardless of what button I press e.g. in current scenario it will always delete the record of 159 even if I press 164 button. My code gives the following output: Remember it works fine if I ask the form to validate directly from other PHP file.
This is my output please have a look at it. Its quite simple!
if(is_numeric($lumens) && $lumens < 5000 && $lumens >250){
if(is_numeric($THD) && $THD <= 20 && $THD >=0){
if(is_numeric($scaled_power_factor) && $scaled_power_factor >=0.9){
if(is_numeric($scaled_cct) && $scaled_cct <=5700){
if(is_numeric($scaled_cri) && $scaled_cri >=65){
if(is_numeric($scaled_input_power)){
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$id = $_SESSION['user_id'];
$query = "INSERT INTO scaling_performance_data SET
MODEL_NUMBER = '$model_number',
LUMENS = '$lumens',
scaled_luminaire_efficacy = '$lm_w',
scaled_input_power = '$scaled_input_power',
THD = '$THD',
SCALED_POWER_FACTOR = '$scaled_power_factor',
SCALED_CCT = '$scaled_cct',
SCALED_CRI = '$scaled_cri',
HOUSING_VARIATION = '$housing_variation',
user_id = '$id'
";
if($con->query($query)){
$sql = "SELECT * FROM scaling_performance_data WHERE user_id='$id';";
$result = $con->query($sql);
if($result){
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<form>
<table>
<tr>
<th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th><input type="button" name ="delete_id" id="delete_id" value="<?php echo $row['ID'];?>" onclick="vlid();"/></th>
</tr>
</table>
<script type="text/javascript">
function vlid(){
var delete_id = $('#delete_id').val();
alert(delete_id);
$.post('validator.php',{
postdelete_id : delete_id
},
function(data){
$('#del').html(data);
}
)
}
</script>
</form>
<?php
}
}
validator.php is:
$id = $_POST['postdelete_id'];
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$query="DELETE FROM scaling_performance_data WHERE ID='$id';";
if($con->query($query)){
echo "Your Result was deleted successful";
echo $id;
}else{
echo "There was a problem Please try again later";
}
}
The problem is that in your vlid() function, JQuery is only selecting the first element with id = delete_id. I would try passing the ID to the vlid() function like this:
<input type="button" ... onclick="vlid(<?php echo $row['ID'];?>)"/>
And then modify your vlid() function to accept the ID parameter.
Try var delete_id = $(event.target).val(); instead of: var delete_id = $('#delete_id').val();
1st ID must be unique so use
class="delete_id"
instead of
id="delete_id"
2nd remove onclick="vlid();" and use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var getValue = parseInt($(this).val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
});
});
});
and to remove the tr which deleted use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var thisBtn = $(this);
var getValue = parseInt(thisBtn .val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
thisBtn.closest('tr').remove();
});
});
});

Ajax call not working after page reload.

I have my home page in php with checkboxes by the names of brand and store list.and in the end one submit button which is given below
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_store_value(){
var d_value=[];
$('input[name="store"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function (e)
{e.preventDefault();
alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var store=get_store_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,store:store},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" />Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="store" value="JCPenny" />JCPenny
<br/>
<input type="checkbox" name="store" value="Supermart" />Suoermart
<br/>
<input type="checkbox" name="store" value="Target" />Target
<br/>
<button id="btnSubmit">sort</button>
<div id="results">
</div>
</body>
</html>
On click of submit,button it goes for ajax call and displays the result in results div.
<?php
include('connection.php');
$query=$_POST['ser'];
$query1=$_POST['store'];
echo $query;
echo $query1;
$query=explode(",",$query);
$query = array_filter($query);
$query1=explode(",",$query1);
$query1 = array_filter($query1);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $result1;
$parts = array();
$limit = 10;
$offset = 0;
if(!empty($query))
{
foreach( $query as $queryword ){
$parts[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$parts).') order by price asc';
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
print($brandsql);
echo "<br />";
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
$parts1=array();
if(!empty($query1)){
foreach( $query1 as $queryword1 ){
$parts1[] = '`STORE` LIKE "%'.$queryword1.'%"';
}
$storesql='SELECT * FROM XML WHERE ('.implode ('OR',$parts1).') order by price desc';
$storesql1=mysql_query($storesql);
$numrows1 = mysql_num_rows($storesql1);
$countArray=array();
print($storesql);
while($row = mysql_fetch_array($storesql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
?>
<?php
foreach($countArray as $array)
{
?>
<div>
hi</div>
<?php $i++; } ?>
But iF I refresh my page or press F5 from keyboard,after getting content in results div,it goes back to previous content i.e.first page with checkboxes and submit button.
Please tell me where m doing wrong in the code or what do i need to include so that after ajax call if i refresh the page,content should remain same,should not go to previous content...
Use setTimeout() to run a refresh on the page after X seconds inside the AJAX callback, after you display content.
You could use the _SESSION variable in your PHP script to store what checkboxes were selected most recently, and display results on your results div, appropriately.
Although, if a user clicks refresh he might want to reset the choices he made anyway. You could give him a warning that his changes will be lost if he refreshes.
window.onbeforeunload = function() {
return confirm("You have made changes to this form. Do you want to continue without saving these changes?");
}

how can i get my script/jquery-ajax to continue responding to clicks?

Still a programming and markup newbie...
I have several little in/out button that reads and writes back from a mysql table to track whether different users are available or unavailable. But I can only click the button once to change the status. After that, it stops responding. How can I get it to just keep working? Thanks!!!!
list.php
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$(".rating").on("click", function(){
var status = $(this).attr("id").substr(0,1);
var id = $(this).attr("id").substr(1);
var data = "id="+id+"&status="+status;
$.ajax({
type: "POST",
url: "rate.php",
data: data,
success: function(e){
$("#r"+id).html(e);
}
})
});
});
</script>
<style>.rating { cursor: pointer; }</style>
</head>
<body>
<?php
include ("headers.php");
$qq = mysql_query("SELECT * FROM $io");
while($rr=mysql_fetch_array($qq)){
$id = $rr["id"];
$content = $rr["status"];
include("buttons.php");
$list .= '<div style="border-bottom: 1px #32baed solid">'.$q[0].'
<div id="r'.$id.'"><img class="rating" id="'.$q[0].$id.'"
src="'.$color.'"> '.$status.'</div></div><br><br>';
}
echo $list;
?>
</body>
</html>
rate.php
<?php
include ("headers.php");
$id = $_POST["id"];
$status = $_POST["status"];
if($status == 0){
mysql_query("UPDATE $io SET status = 1 WHERE id='$id'");
}
else {
mysql_query("UPDATE $io SET status = 0 WHERE id='$id'");
}
include("buttons.php");
$list = '<img class="rating" id="'.$q[0].$id.'" src="'.$color.'"> '.$status;
echo $list;
?>
buttons.php
<?php
$q = mysql_query("SELECT status FROM $io WHERE id='$id'");
$q = mysql_fetch_array($q);
if($q[0]){
$color = "green.png";
}
else{
$color = "red.png";
}
?>
headers.php
<?php
$c = mysql_connect("localhost", "username", "password");
$db = mysql_select_db("likes", $c);
$io = 'io';
?>
Replace
$(".rating").on("click", function(){
With
$(document).on("click", ".rating", function(){
You have to do like this:
$(document).on("click", ".rating", function(){
//YOUR CODES HERE
});
And make sure that these codes are outside of document ready function.
Read the documentation for help on .on()

Categories

Resources