Ajax + mysql reload page - php

i try to work on something but it's not realy working as i want, so first we have the index page with the ajax code :
function redirect(){
$(".redirect").load("redirect.php");
}
setInterval(function(){
redirect()
}, 3000);
</pre>
Of course in the body we have this :
<div class="redirect"></div>
In the redirect.php code, we have this :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['clientvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
//header('location: '.$_SESSION['redirect_url']);
}
}
}
Okay so, to start, when my client is on the index.php, the row redirect is on 0.
And on my web panel, i can set up the value to 1, if the value is on 1, i want the client to be redirected of the index page to my $_SESSION['redirect_url'].
But the problem is, of course, it redirect only in the class="redirect" div.
But i want him to be redirected from the index page, so i tried in the redirect.php code this :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['clientvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
$ok = 1;
}
}
}
And on the index.php page i added this below the class redirect div :
<?php
if($ok == 1) {
header('location: url');
}
?>
But it doesn't detect the $ok from the redirect.php.
Any idea how i could fix this problem ?
Thank !

Okay i resolved the problem, i don't know if it's the proper way to do it, but it's working as i want ! i did that :
redirect.php :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['ccvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
echo '<div id="content"><div id="activity">1</div></div>';
}
else {
echo '<div id="content"><div id="activity">0</div></div>';
}
}
}
And the AJAX in index.php :
<script>
$(document).ready(function() {
function redirect(){
$.ajax({
url:'redirect.php',
type:'GET',
success: function(data){
var active = $(data).find('#activity').html();
if(active == 1) {
<?php echo 'window.location.replace("'.$_SESSION['redirect_payment'].'");'; ?>
}
}
});
}
setInterval(function(){
redirect()
}, 3000);
});
</script>
Hope it will help, thank #CBroe

Related

PHP - Make a submit button send info to database

Hello I am new at coding and I have a question I hope some of you guys with some experience can help me with.
I have a page with some text and a button "Confirm". When this button is clicked by me, I first want to redirect to "loading.php" and in the mysql database I want to recieve "confirmed" or "ok" anything like that. Then in my dashboard I want to manually press "Next" on the unique-userid to redirect to "page3.php"
I would need some help with this and a simple "template" on how the button would be programmed in my php.
Script in my PHP where I have the button.
$(document).ready(function() {
var allInputs = $(":input");
$('#SubmitConfirm').submit(function(e) {
e.preventDefault();
var confirm = $('#confirm').val();
if (confirm == null) {
return false;
} else {
}
$.ajax({
type: 'POST',
url: 'files/action.php?type=confirm',
data: $('#confirm').serialize(),
success: function(data) {
console.log(data);
var parsed_data = JSON.parse(data);
if (parsed_data.status == 'ok') {
//console.log(parsed_data);
location.href = "Loading.php"
} else {
return false;
}
//console.log(parsed_data.status);
}
})
});
});
And here is "confirm" in action.php
if($_GET['type'] == 'confirm'){
if($_POST['confirm'] == true){
$submit = $_POST['confirm'];
$uniqueid = $_POST['userid']; // unique userid
$query = mysqli_query($conn, "UPDATE customers SET confirm='$confirm', status=1, buzzed=0 WHERE uniqueid=$uniqueid");
if($query){
echo json_encode(array(
'status' => 'ok'
));
}else{
echo json_encode(array(
'status' => 'notok'
));
}
}
}
}
I have tried but I only got 404 error when I pressed the button
from dashboard.
$query = mysqli_query($conn, "SELECT * from customers");
if($query){
if(mysqli_num_rows($query) >= 1){
$array = mysqli_fetch_all($query,MYSQLI_ASSOC);
//print_r($array);
}
}
foreach($array as $value){
$user = $value['user'];
$confirm = $value['submit'];
$info = "
uniqueID : $user
Confirm: $confirm
echo "

How to use a div id as a php var

I have the following function that pass to the div with id = "window", the value dbdata from the database.
$(document).ready(function() {
setInterval(function () {
$('#window').load('crt.php');
)};
)};
How can I get the id value and use it in the php code below?
without refresh the page?
if ($id = $row["dbdata"]) { do something }
I added the rest of the code:
index.html
`<div id = "window"></div>`
`if ($id = $row["dbdata"]) {do something}`
`<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#window').load('crt.php')
}, 3000);
});
</script>`
crt.php
`<?php
$conn = new mysqli('localhost', 'root', '', 'user');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT id FROM data");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['dbdata'] . '<br>';
}
}
?>`
Thank you in advance.
You can pass values in URL parameters.:
$('#window').load('crt.php?id=window')
Then in your php code you can retrieve the parameter using:
$id = $_GET["id"];
a simple way could be assign the GET param in your jquery load url and use it in your php code
$(document).ready(function() {
setInterval(function () {
$('#window').load('crt.php?id=window')
.
if ($_GET['id'] = $row["dbdata"]) { do something }
or you instead of load could use ajax get eg :
$.get( "crt.php?id=window", function( data ) {
alert( "Data Loaded: " + data );
});
in your crt.php
if ($_GET['id'] = $row["dbdata"]) {
return "hello!";
}

Passing values from a php page to a modal from other page

I'm trying to edit a post using this snippiet of from my query.php page:
echo '<button type="submit" onclick="openModal(this)" id="btn-edit"
name="edit" value='.$postID.'></button>';
function openModal(id)
{
var editpost = id.value;
$.ajax({
url:"query.php",
method:"POST",
data:{ editpost : editpost },
success:function(data)
{ //
},
error: function () {//
}
});
$('#edit').modal('show');
}
The function to get the data from the post selected is on the same php page. This is the code:
if(isset($_POST['editpost']))
{
session_start();
$editpostid = $_POST['editpost'];
if($editpostid != "")
{
$sql = "SELECT * FROM post WHERE PostId = '" . $editpostid . "'";
}
if($sql != "")
{
$qry = mysqli_query($connection, $sql);
if (mysqli_num_rows($qry) > 0)
{
foreach($qry as $row)
{
$_SESSION['editpostdesc'] = $row['PostDesc'];
$_SESSION['editpostfile'] = $row['PostFile'];
$_SESSION['editpostid'] = $row['PostId'];
}
}
}
}
But the modal is on the other page (main page). I want to get the data of the post and display it on the modal, so I tried using $_SESSION. Yes, I got the data and was able to display it on the modal, but the problem is when I try to edit another post, the first value assigned to the session cannot be replaced. Is there is any other way that I can pass the values without using session? I'm really running out of ideas, I'm just starting my first web project.
if you get multiple row means this methods will worked...
if(isset($_POST['editpost']))
{
session_start();
$editpostid = $_POST['editpost'];
if($editpostid != "")
{
$sql = "SELECT * FROM post WHERE PostId = '" . $editpostid . "'";
}
if($sql != "")
{
$qry = mysqli_query($connection, $sql);
if (mysqli_num_rows($qry) > 0)
{
foreach($qry as $row)
{
$res[] = array(
'editpostdesc' => $row['PostDesc'],
'editpostfile' => $row['PostFile'],
'editpostid' => $row['PostId']
);
}
}
}
}

Timeout Session When There's No Activity From the User

how can I timeout a session when there is no activity from the user?
Here is my code which has the name session.php:
<?php
require_once('conn.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($conn, "select * from employee where Username = '$user_check'");
$row = mysqli_fetch_array($ses_sql, MYSQLI_ASSOC);
$login_session = $row['EmployeeName'];
if (!isset($_SESSION['login_user'])) {
header("location:index.php");
}
?>
Include this code into the profile page you want to redirect to after logged in. First calculate the time like this.
<script>
var sec = 0;
var min = 0;
var hrs = 0;
function time () {
if (sec<=59) {
sec++;
if (sec<10) {
sec="0"+sec;
}
if (sec>59) {
sec=0;
min++;
if (min>59) {
min=0;
hrs++;
if (hrs>24) {
hrs=0;
};
};
};
};
document.getElementById("time").innerHTML=hrs+":"+min+":"+sec;
}
function tick () {
if (min<10) {
min="0"+min;
}
if (hrs<10) {
hrs="0"+hrs;
}
}
window.onload=function () {
tick();
setInterval(time,1000);
}
</script>
This will give you a time. After that do this. Let's assume you want to time it out in 30 seconds. Here login.php is any common page which redirects after logout.
<script>
if(sec == 30){
</script>
<?php
$_SESSION["login_user"] = NULL;
redirect_to("login.php");
?>
<script>
}
</script>
I hope this would work.

How to get a single mysql value and output it to an ajax call?

I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.

Categories