I have a progress bar and a button.
When it reaches 100%, I use JQuery AJAX to check if the user already has an active giftcode in database or he doesen't. If he doesen't, I generate a new giftcode and insert it into the database.
The generating and inserting is working just fine. My problem is, I need the user account ID in the JQuery script. I'm currently using the hidden input method and it returns my account ID 0 every time, no matter which account I use.
This is the code on main page:
<div id ="resultDiv" style="text-align:center;"></div>
<input type="hidden" id="hdnSession" data-value="#Request.RequestContext.HttpContext.Session["ID"]" />
This is the JQuery file (where I check if user has active giftcode using AJAX):
$(function() {
var timer = 0;
$('#code').click(function () {
clearInterval(timer)
var value = 0;
timer = setInterval(function () {
value++;
$('.progress-bar').width(value + '%').text(value + '%');
if (value == 100) {
clearInterval(timer);
var sessionValue= $("#hdnSession").data('value');
$.post("checkcode.php",
{
ID: sessionValue
},
function(data)
{
$("#resultDiv").hide().html(data).fadeIn(1000);
});
}
}, 10);
})
});
And this is the .php file which does the checking:
<?php
include_once ('connect.php');
if(isset($_POST['ID']))
{
if(!empty($_POST['ID']))
{
$id = $_POST['ID'];
$select_user = "SELECT * from giftcodes WHERE UserID='$id'";
$query = mysqli_query($con, $select_user);
$row = mysqli_num_rows($query);
if(!$row) {
$randomcode = substr(md5(uniqid(mt_rand(), true)), 0, 8);
$insert_code = "INSERT INTO giftcodes (UserID, Giftcode) VALUES ('$id', '$randomcode')";
$query = mysqli_query($con, $insert_code);
echo'<br><hr><h1 style="color: #5cb85c;">Your generated gift code:</h1><br><pre><kbd style="background-color: #5cb85c; color: #000;">'.$randomcode.'<kbd></pre><hr><p class="small" style="font-weight:bold;">You can generate a new code in 24 hours.</p>';
} else {
echo 'You already have an active gift code!';
}
}
}
?>
So the problem is, var sessionValue= $("#hdnSession").data('value'); returns 0 every time although I'm sure the user $_SESSION['ID'] is set. If I generate a gift code, the UserID will get set to 0 every time.
If your "main page" is a php page you can use this (getting from php the $_SESSION['ID'] value and assign to value for the hidden input field
<div id ="resultDiv" style="text-align:center;"></div>
<input type="hidden" id="hdnSession" value="<?php echo $_SESSION['ID']; ?>" />
I can just use $_SESSION['ID'] in the PHP file.. don't know why I tried to get this so complicated. Sorry.
Related
What is the way to keep update the info about if user has got new notifications?
When page is opened it includes content of pageTop.php. There it checks database, if there are some unchecked notification. And loads note_NO or note_YES in base of query.
How is the approach to have new info at certain time period ?
Next page works on page load or refresh. But I don't want to reload header.php each time.
header.php:
<?php include_once("pageTop.php");?>
<div id="pageMidle"></div>
<div id="pageFoot"></div>
pageTop:
$sql = "SELECT id FROM note WHERE user='$l_user' AND did_read ='0' ";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$nrows = mysqli_num_rows($query);
if ($numrows == 0) {
$envelope = '<img src="images/note_NO.jpg" width="30" height="30" alt="Notes">';
} else {
$envelope = '<img src="/images/note_YES.gif" width="30" height="30" alt="Notes">';
}
html:
<div id="envolopeDIV">
<?php echo $envelope; ?>
</div>
You can use a session to keep track of time between requests in the backend. If your specified time period has passed, include the snippet for querying the database.
session_start();
const TIME_PERIOD = 123456;
$currentTimestamp = time();
$previousTimestamp = $_SESSION['previous_timestamp'] ?? 0;
if ($previousTimestamp + TIME_PERIOD > $currentTimestamp) {
// check notifications
}
$_SESSION['previous_timestamp'] = $currentTimestamp;
//...
I am building a website and I can not figure out one thing. I need a script that checks if 10 seconds have past since load time, then it would run another PHP script. But I am not sure if it is possible. I have attached my attempt at this problem. Any ideas? Thanks in advance!
if (
<script type="text/javascript">
function viewplus(){
}
setTimeout(viewplus, 10000);
</script>
)
$query = "SELECT * FROM users WHERE id=" . $rws2['id_user'];
$result2 = mysqli_query($db, $query);
$rws2 = mysqli_fetch_array($result2);
$views_total = $rws2['views_total'] + 1;
$views_week = $rws2['views_week'] + 1;
$views_today = $rws2['views_today'] + 1;
$id = $rws2['id'];
$query = "UPDATE users SET views_total='$views_total',views_week='$views_week',views_today='$views_today' WHERE id='$id'";
mysqli_query($db, $query);
It is possible using jQuery like this:
Put your code in a php file and call it after 10 seconds after page load with
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('index.php');
}, 10000);
});
</script>
Example of updating a table and receiving a status message:
if (isset($_POST['id'])&&
isset($_POST['var'])){
$con = new mysqli("localhost", "my_user", "my_password", "world");
$id = $con->real_escape_string($_POST['id1']); //In our example id is INT
$var = $con->real_escape_string($_POST['var']);
$result = $con->query("UPDATE table SET value = '$var' WHERE id = $id);
(!$result) ? echo "Update failed!" : "Update succeeded";
}
This will load the output of your php file(Update filed or succeeded) in a element (this case one with id some_id).
Another way which I DO NOT recommend is using PHP's sleep() function PHP Documentation
1 - addlist.php
In this page, I've only a text input. I can scan a barcode, that gives me a text result in the input (ex: "banana").
2 - validaiton.php
This page connect my SQL DataBase and checks if value put in the textbox of my other page (addlist.php) is in my DB.
3 - addlist.php
If the value exists in DB, set a message and put the value in a list. If not, set an other message and do nothing.
/!\ For information: I've a barcode scanner, so I couldn't press a button or to display value in the list. So I chose to set a timer and every 800ms, it takes value and clears. With that, I can scan a value, display and clear it dynamically without touch my keyboard. /!\
addlist.php
<input type="text" id="IDAlim">
<div class="col-md-6">
<section>
<li id="demo"></li>
</section>
</div>
<script src="js\jquery.js"></script>
<script type="text/javascript">
var list = document.getElementById('demo');
$(document).ready(function()
{
putIn();
function putIn() {
var focused = $(':focus');
$("#IDAlim").focus();
focused.focus();
var IDAlim = document.getElementById('IDAlim').value;
var quantite = "1";
var entry = document.createElement('li');
if(IDAlim != "")
{
$.post('validation.php',{IDAlim: $('#IDAlim').val()}, function(data){
if(data.exists){
alert('Is in DB');
$("#demo").append('<li class="list-group-item">'+IDAlim+' '+quantite+'x'+'</li>');
}else{
alert('Re-Scan please');
}
}, 'JSON');
setTimeout(function(){ putIn() }, 800);
$("#IDAlim").val('');
}
else
{
entry.appendChild(document.createTextNode(IDAlim));
setTimeout(function(){ putIn() }, 800);
$("#IDAlim").val('');
}
}
})
</script>
validation.php
<?php
//set the headers to be a json string
header('content-type: text/json');
//no need to continue if there is no value in the POST IDAlim
if(!isset($_POST['IDAlim']))
echo json_encode(array('non' => 'POSTError'));
//Variable for db connection
$host="localhost";
$user="root";
$pass="";
$dbname="aliments";
try
{
$dbcon = new PDO("mysql:host={$host};dbname={$dbname}",$user,$pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$query = $dbcon->prepare('SELECT nom FROM tblaliments WHERE nom = :nomAlim');
$query->bindParam(':nomAlim', $_POST['IDAlim']);
$query->execute();
//return the json object containing the result of if the IDAlim exists or not. The $.post in my jquery will access it.
echo json_encode(array('exists' => $query->rowCount()));
}
catch (Exception $e)
{
echo json_encode(array('non' => 'PDOError'));
}
?>
I would update my quantity when I scan a same value, in my case, I put pending "1" for "quantite" (=quantity in french) to show you an example.
That's my problem
What I would like to have
Thank you in advance to help me and sorry for my bad english (I speak french)
In changename.php I have this DIV:
<div id="resultDiv"></div>
In the same file I have the PHP code:
<?php
include_once ('connect.php');
if(isset($_POST['name']))
{
$postedname = $_POST['name'];
$safename = mysqli_real_escape_string($con, $postedname);
$checkname = "SELECT * from accounts where name='$safename' LIMIT 1";
$query = mysqli_query($con, $checkname);
$row = mysqli_num_rows($query);
if($row) {
echo 'Name is already taken!';
} else {
$changename = "UPDATE accounts SET name='$safename' WHERE Name='$_SESSION[username]'";
$query = mysqli_query($con, $changename);
if($query)
{
echo 'Name is changed!';
$_SESSION['username'] = $safename;
}
}
}
?>
And this is my Jquery script (in a seperate file):
$(function(){
$("form").submit(function() {
event.preventDefault();
var name = $('#inputName').val();
$.post("changename.php",
{
name: name
},
function(data)
{
$("#resultDiv").text(data);
});
});
});
The code is just working fine, it successfully changes my name. If I want my name to be 'John', it successfully changes it in the DB.
The problem is, it's supposed to change the div with ID resultDiv to Name is already taken!. Instead of that, it takes the whole changename.php HTML code and puts it into that DIV. So instead of 1 line, I have 100+ lines of my page in there. So it looks like this:
https://gyazo.com/9320a5f15ed67a8ad9298d6172ab6909
Any idea why it's not just the message I want?
Ajax will fetch all data from file given as url for it.
If you want to avoid that, you have 2 options.
Write condition in changename.php in such a way that only update to db part will be executed.
On changename.php keep only required code to update to db.
I have a system set up that will display certain pages. I have the paignation set up already. In each page, I want to have 5 radio buttons, each named as "Definitely No", "No", "Second look", "Yes", "Definitely Yes". When the user clicks one of the radio button, php should insert one value (1-5) to a column called "viewed" and a row according to the current page variable ($currentpage). The paignation and each page's code is here:
<?php
// database connection info
require_once "connect_database_viewer.php";
$table = 'JOBARXXX20140709';
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM $table";
$result = $db_server->query($sql) or trigger_error("SQL", E_USER_ERROR);
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = $numrows;
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
$query = "SELECT * FROM $table";
$result = $db_server->query($query);
if (!$result) die ("Database access failed: " . $db_server->error);
$rows = $result->num_rows;
$result->data_seek($currentpage);
echo $currentpage;
$row = $result->fetch_array(MYSQLI_NUM);
$asin = $row[2];
echo $asin;
echo file_get_contents("http://www.amazon.com//dp/$asin/?ie=UTF8");
echo <<<_END
<html>
<head>
<meta charset="=utf-8">
</head>
<body>
<div>
<iframe src="http://camelcamelcamel.com/product/$asin" width="1200" height="2300" align="middle"></iframe>
</div>
<div>
<form action="insert.php">
<input type="radio" name="result" value="1">Definitely No<hr>
<input type="radio" name="result" value="2">No<hr>
<input type="radio" name="result" value="3">Second Look<hr>
<input type="radio" name="result" value="4">Yes<hr>
<input type="radio" name="result" value="5">Definitely Yes<hr>
</form>
</div>
</body>
</html>
_END;
echo $currentpage;
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
How should I write the insert.php? This is a little insert code I wrote but I don't think it is working out.
if(isset($_POST['result']) && !empty($_POST['result'])){
$radioContent= $_POST['result'];
$sql = "UPDATE $table SET viewed='1' WHERE name='$currentpage'";
}
else{
error_log($mysqli->error);
}
}
A few things:
If you want to use the $_POST array, make sure to set your form method to post. <form action="insert.php" method="post"> The form element defaults to using GET.
$table and $currentpage will not be set in insert.php. You will have to send this information with your post. This can be done by making hidden inputs. <input type="hidden" value="<?php echo $currentpage ?>" name="currentpage" />. Now these variables will be accessible in the $_POST array. ($_POST['currentpage'])
ALWAYS escape any data being used for SQL queries. Including the hidden values made in #2. http://php.net/manual/en/mysqli.real-escape-string.php
You need to actually send the query to the database. As it is, you're only setting up the query string.