how to keep checkbox checked even after page refresh - javascript

I have one checkbox on my form working with the database for active(1) and inactive(0) users to access via admin panel. All is working fine but the problem is its not keeping the record for the checboxes when the checkbox is checked or unchecked after refreshing/reloading the page. i want them to be remembered even after admin logout and login again. can any one help me out ?
Thanx in advance
Here is HTML :
<td><input type='checkbox' class='user_status'
id='user_status_<?php echo $data['user_reg_id']; ?>' value='' name = 'user_status'
onclick="userId(<?php echo $data['user_reg_id']; ?>)" />
Here is JS :
<script>
function userId(user_reg_id){
$(document).ready(function(){
var link = "<?php echo base_url();?>" ;
var st = $('#user_status_'+user_reg_id).is(":checked") ? 0 : 1;
$.post(link + "administration/um/user_status", {user_reg_id:user_reg_id, user_reg_status:st, ajax : 1}, function(data){
alert (st); //showing status 1 and 0 on alert
if (st == 1){
$("#user_status_").prop(":checked", true)
} else {
$("#user_status_").prop(":checked", false)
};
});
});
}
</script>

store checkbox value in database using ajax when you click on it..
also fetch from database checkbox value if checkbox value is 1 than checked ...otherwise uncheck :)

Since you need the data to be persistent, I would suggest using HTML5 localStorage. Depending on how persistent, you may need to save it in a database. I haven't tested this code and have not actually done this. It's meant to get you close to a working solution.
function isChecked(user_reg_id){
$(document).ready(function(){
$('#user_status_'+user_reg_id).on('click', function () {
if(localStorage && localStorage.getItem(user_reg_id)){
localStorage.removeItem(user_reg_id);
}else{
$('#user_status_'+user_reg_id).prop('checked', true);
}
}
});
}

Related

Updating a calculated field in the parent record after submitting/updating child record in a modal dialogue

I have a bit of an issue updating a calculated field of the parent form when submitting/updating a child record with a bootstrap 3 modal dialogue, from within the parent form.
I have this function in parent.js file:
function update_lineitems_subtotal() {
var qid = $j('[name=SelectedID]').val();
if (!isNaN(qid)) {
$j.ajax({
url: 'hooks/ajax_quote_subtotal.php',
data: {qid: qid},
success: function(data) {
$j('#LineItemsSubtotal').val(data);
$j('#Shipping').keyup();
}
});
} else {
$j('#LineItemsSubtotal').val('0');
$j('#Shipping').keyup();
}
};
And this is the ajax_quote_subtotal.php that runs with the ajax call above:
<?php
$currDir = dirname(__FILE__) . '/..';
include("$currDir/defaultLang.php");
include("$currDir/language.php");
include("$currDir/lib.php");
/* grant access to users with access to quotations table */
$od_from = get_sql_from('quotations');
if(!$od_from){
header('HTTP/1.0 401 Unauthorized');
echo "You do not have permission to access this page. If this behaviour is unexpected, please contact the system administrator";
exit;
}
$qid = intval($_REQUEST['qid']);
if(!qid) exit;
$parts_subtotal = sqlValue("select sum(Subtotal) from product_line_items where QuotationID='{$qid}' ");
$service_subtotal = sqlValue("select sum(Subtotal) from service_line_items where QuotationID='{$qid}' ");
$subtotal = $parts_subtotal + $service_subtotal;
sql("update quotations set LineItemsSubtotal='{$subtotal}' where QuotationID='{$qid}' ", $eo);
echo number_format($subtotal, 2);
?>
This is the function from child.js that closes the modal dialogue when the form is submitted and runs the update_lineitems_subtotal function from the parent.js
if($j('input[name=Embedded]').val()==1){
$j('form').submit(function(){
window.parent.jQuery('.modal').modal('hide');
setTimeout(function(){
parent.update_lineitems_subtotal();
}, 100);
})
}
This works as long as I do not remove setTimeout,however I do not feel like it is a good solution.
If the setTiemout is removed the record is created but it looks like the function runs before the child record is submitted, so the value of the subtotal field in the parent excludes the latest added record.
I have also tried this:
if($j('input[name=Embedded]').val()==1){
$j('form').submit(function(e){
e.preventDefault();
this.submit();
window.parent.jQuery('.modal').modal('hide');
parent.update_lineitems_subtotal();
})
}
This had similar results in Chrome and refused to even create a child record in Firefox.
Any help would be appreciated.
P.S. I am new to this, if you have time to explain the code you may suggest it would be greatly appreciated.

Display an alert based on a json data

I am having 2 portions of code (php and javascript).
In the PHP file, I use the function json_encode() to create a JSON data which will be sent to the Javascript file.
PHP FIle
<?php
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
$product_code = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove
if(isset($_SESSION["products"][$product_code])) {
unset($_SESSION["products"][$product_code]);
}
$total_items = count($_SESSION["products"]);
if($total_items == 0){
unset($_SESSION["products"]);
}else{
//Calculate total of items in the cart
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
$product_price = $product["price"];
$product_quantity = $product["quantity"];
$subtotal = $product_price * $product_quantity;
$total += $subtotal;
}
}
die(json_encode(array('items'=>$total_items, 'total'=>$total)));
}
?>
Javascript File
<script>
$(document).ready(function(){
$(".contentwrapper .content").on('click', 'a.removebutton', function() {
var pcode = $(this).attr("data-code"); //get product code
$.getJSON( "phpfile.php", {"remove_code":pcode}, function(data) {
alert(data.items);// the total number of item
});
});
</script>
Anytime the query $.getJSON( "phpfile.php", {"remove_code":pcode}... is successful, an alert is displayed showing the data.items. The problem I am facing is that, when data.items is greater than or equal to 1 the alert is prompted, but when data.items is equal to 0, no alert is prompted.
Kindly help me solve this problem
Looks like a PHP error. $total variable is only declared inside the 'else' condition, so when ($total_items == 0) $total is undefined. But as you've called die(json_encode(array('items'=>$total_items, 'total'=>$total))); the server doesn't have a chance to complain (maybe returning no data and hence no alert). If you try declaring $total = 0 before your condition it should also fix the issue, without having to die early.
One possibility is that actually data variable is undefined/null e.t.c., see this for example, second alert is not shown. Instead an error is shown on the browser console.
var data = {items:0};
alert(data.items);
data = null;
alert(data.items);
Adding die(json_encode(array('items'=>$total_items))); at the end of the condition if($total_items == 0) and it solves the problem. But I really can't explain what is happening. Up to now I do not really know the origin of the problem. Any explanation will be welcomed

Creating a Cookie to not vote again in a poll

I've created a simple [voting form] using jQuery AJAX and JSON. I want to know how to create a Cookie so that the user will not be able to vote more than once. Following is my code.
I am new to Cookies and jQuery. Please tell me how to complete my task.
JavaScript
<script>
$(document).ready(function(){
$("#poll").click(function(){
var count = '';
if (document.getElementById("vote1").checked) {
count = 0;
}
if (document.getElementById("vote2").checked) {
count = 1;
}
var jsonV= { "vote": count };
$.ajax({
type : "POST",
url : "poll_vote.php",
data : jsonV,
dataType: "json",
success : function ( responseText ){
console.log("Is working " + responseText);
$("#result").html( responseText.vote );
},
complete : function(){
$("#poll").slideUp();
},
error : function( error,responseText ){
// alert("Server not Responding. Sorry for the inconvenience caused. Please Try again Later");
console.log( error );
$("#result").html( error + responseText );
alert( count );
}
});
});
});
</script>
PHP
<?php
$vote = $_REQUEST['vote'];
$filename = "poll_result.txt";
$content = file($filename);
// $decode = json_decode($encode);
$array = explode("||", $content[0]);
$male = $array[0];
$female = $array[1];
if ($vote == '0') {
$male = $male + 1;
}
if ($vote == '1') {
$female = $female + 1;
}
$insertvote = $male."||".$female;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
$table = (
"<h2>Results:</h2>
<table>
<tr>
<td> Male :</td>
<td>
<img src='poll.gif'
width= ".(100*round($male/($female+$male),2)).
"height='20'>".
(100*round($male/($female+$male),2))." %" .
"
</td>
</tr>
<tr>
<td> Female :</td>
<td>
<img src='poll.gif'
width=". (100*round($female/($female+$male),2)) .
"
height='20'>".
(100*round($female/($female+$male),2))." %" ."
</td>
</tr>
</table>"
);
$list = array('vote' => $table);
$encode = json_encode($list);
echo $encode;
?>
HTML
<div id= "poll">
<h3> What is your Gender? </h3>
<form>
Male :
<input type ="radio" name ="vote" id="vote1" >
<br>
Female :
<input type ="radio" name ="vote" id="vote2" >
</form>
</div>
You would want to set a cookie when the user votes, and check for that cookie in PHP when a vote is submitted. If the cookie is already set, the vote should be discarded.
For example, using just PHP, it could look something like this:
if (!isset($_COOKIE['has_voted'])) {
// normal vote submission code goes here
// ...
// then we set a cookie to expire in 30 days
setcookie('has_voted', '1', mktime().time()+60*60*24*30);
} else {
// cookie already exists, user has already voted on this machine
// do not count the vote, flag an error to the user
}
It is worth noting that there are ways round this - the user could easily delete the cookie manually. In this case, you could also store the IP addresses of users who have already voted, but this can open up problems on shared machines and multiple machines behind a network.
Since it seems you're using PHP, you'll be able to implement a cookie to prevent multiple votes within your already existing script.
The syntax for setting a cookie in PHP is as follows:
setcookie("cookiename", "cookiedata", cookietime, "cookielocation");
Where "cookiename" is the name of the cookie, for example, "voted", "cookiedata" is the data stored in the cookie– "yes", for example. "cookielocation" is the location where the cookie is stored in the user's browser cache. Unless you know what you're doing, just set this to "/".
Cookietime is how long the cookie will sit in the users system until the browser automatically deletes it. Note that this doesn't prevent the user from deleting the cookie. For simplicity, I usually set the time as follows:
time()+60*60*24*days
Where days is how long the cookie will sit in the user's system (in days, of course).
To retrieve the value of a cookie so you're able to perform logic on it, try using:
if(isset($_COOKIE['cookiename'])) {
$valueOfCookie = $_COOKIE['cookiename'];
}
Make sure to use the if(isset()) to make sure the cookie has been set, before trying to retrieve the value.
Using these functions, your logic may look something like this when the user submits the form:
Check if the voting cookie is set
If it is, print an error message, else:
Continue to process the form data, and set the vote cookie
However, on a side note, if you're concerned about users potentially deleting their cookies so they can vote again, I might suggest that, rather than using cookies, you store users' IP addresses on the server-side, and deny them voting access if their IP address has already voted.
You could do this with sessionStorage, using only JS:
<script>
$(document).ready(function(){
$("#poll").click(function(){
var count = '';
if (document.getElementById("vote1").checked) {
count = 0;
}
if (document.getElementById("vote2").checked) {
count = 1;
}
var jsonV= { "vote": count };
if ( sessionStorage.getItem( 'voted' ) == 'true' ) {
alert('You have already voted!');
}else if ( sessionStorage.getItem( 'voted' ) == null ){
$.ajax({
type : "POST",
url : "poll_vote.php",
data : jsonV,
dataType: "json",
success : function ( responseText ){
console.log("It's working" + responseText);
$("#result").html( responseText.vote );
},
complete : function(){
$("#poll").slideUp();
sessionStorage.setItem('voted', 'true');
},
error : function( error,responseText ){
// alert("Server not Responding. Sorry for the inconvenience caused. Please Try again Later");
console.log( error );
$("#result").html( error + responseText );
alert( count );
}
});
}
});
});
</script>
What I have done here is added a session storage item in the
complete callback of your ajax call, so once it has completed the
item 'voted' will be set.
I have then wrapped the ajax call in an if condition which checks
the value of the storage item and if it is set then will not allow
you to vote (and instead bring up an alert)
Note that you can also you localStorage if you want the item to last longer as sessionStorage is cleared when the browser window is closed while localStorge will last until the user clears their cookies / browsing data.
And here is a little snippet you can use to clear the storage for testing purposes:
$('#clear').click(function(){
console.log(sessionStorage.getItem( 'voted' ));
sessionStorage.removeItem('voted');
console.log(sessionStorage.getItem( 'voted' ));
});
You will need the accompanying HTML with that:
<p id="clear">clear</p>

Button click counter save number

I have this fiddle where when the user clicks a button the counter works: http://jsfiddle.net/z66WF/
This is the code:
<button type="button" onClick="clickME()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
The problem is that I want the number to be saved, so for example:
user #1 clicks on the button 10 times
user #2 opens the site and the count is at 10, he clicks and now the counter starts 11
and so on with new users.
I'm trying to do this to keep track of how many times a file has been downloaded.
Any idea how can I do that?
Here you have a working simple exemple, wich write the counter in a simple txt file (no sql db needed)
<?php
$counterFile = 'counter.txt' ;
// jQuery ajax request is sent here
if ( isset($_GET['increase']) )
{
if ( ( $counter = #file_get_contents($counterFile) ) === false ) die('Error : file counter does not exist') ;
file_put_contents($counterFile,++$counter) ;
echo $counter ;
return false ;
}
if ( ! $counter = #file_get_contents($counterFile) )
{
if ( ! $myfile = fopen($counterFile,'w') )
die('Unable to create counter file !!') ;
chmod($counterFile,0644);
file_put_contents($counterFile,0) ;
}
?>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
jQuery(document).on('click','a#download',function(){
jQuery('div#counter').html('Loading...') ;
var ajax = jQuery.ajax({
method : 'get',
url : '/test.php', // Link to this page
data : { 'increase' : '1' }
}) ;
ajax.done(function(data){
jQuery('div#counter').html(data) ;
}) ;
ajax.fail(function(data){
alert('ajax fail : url of ajax request is not reachable') ;
}) ;
}) ;
</script>
</head>
<div id="counter"><?php echo $counter ; ?></div>
Download btn
You need a DB connection to do this.
When the button is clicked, by any user, the value from let's say: "downloaded_times" will be increased with 1.
so you will need a query like:
UPDATE table SET downloaded_times = downloaded_times + 1
this query will be called each time someone presses the button.
If you want to display it, before a certain user wants to start a download, you simply fetch the result from DB and the echo it. You can do more, if you want that field to be constantly refreshed, the fetching and echoing part should be in a ajax called PHP function, that will refresh the div (for instance) every 30 second or so :D
Hope this helps! :D

Executing php script on button click and returning value by ob_start

I have button which in enclosed by <a> tag. When clicked, it executes redirect.php script.
login.php - contains
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
redirect.php contains twitter authentication code. If authenticated successfully then gives id and name. I want to fetch these both value in index.php
Using ob_start(); I can receive values from php script to JS function via json.
But I am confused about how to manage the code in index.php to execute script on button click and receiving these two value also.
redirect.php
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$notweets = 5;
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
$id = $content->{'id'};
$name = $content->{'name'};
?>
Please let me know if you need further explaination.
Bottomline:
Rather executing redirect.php script on link click, I want it to execute via function on button click event.
Getting id and name from redirect.php to index.php after redirect script executed
I already have session_start() to manage the twitter session. So dont want to mess up using mutiple session if not necessary ..
UPDATE after david's answer
<body>
<input type="button" value="Run somePHPfile.php" id = "b1" />
<script>
$('#b1').click(function () {
window.location.href = 'redirect.php';
$.get('index.php', function(data) { //If I put this out side click then it gives undefined value for name and id before redirect.php gets executed
// data.id is the id
var id= data.id;
var name = data.name;
alert(name);
});
});
</script>
</body>
Apologize to say:
On button click redirect.php script executed. redirect.php includes other files, which finally reach to index.php. And index.php returns name and id.
So is this enough to manage it : $.get('index.php', function(data) { ... }
To bind to a click event of an HTML button, you would use JavaScript. Since you tagged the question with jQuery, I'll assume its use. The event handler would look something like this:
$('#loginButton2').click(function () {
window.location.href = 'redirect.php';
});
Note: This simulates an anchor click effectively. If you instead want to more closely resemble an HTTP redirect, you might want to use this instead:
window.location.replace('redirect.php');
As for the id and name values, how exactly does this flow return the user to index.php in the first place? Your redirect.php has, well, a redirect (though not all code paths result in that) so it kind of assumes non-AJAX interaction. (I think XHR follows redirects sometimes, but the behavior is different from one browser to another.)
If the redirect isn't terribly important and you just want to make an AJAX call to redirect.php, then you can do that with a simple AJAX request:
$.get('redirect.php');
In order to get those values back to the page, they'll need to be emitted from redirect.php. Something like this:
echo json_encode((object) array('id' => $id, 'name' => $name));
Then in the client-side code you would have those values available in the AJAX callback:
$.get('redirect.php', function(data) {
// data.id is the id
// data.name is the name
// use these values client-side however you need
});
<script>
$("#loginButton2").on('click',function(){
window.location.href="redirect.php";
});
</script>
and in redirect.php file
$_SESSION['id']=$id ;
$_SESSION['name']=$name;
and also
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
to
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>

Categories

Resources