I am updating my site content with AJAX by using this method i have found here: https://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html
This works very well but according to this tutorial i have to echo the values i want to show as an updated value in the background running "record_count.php". Later all values are shown up in my frontend file "index.php" within the specific <div id="xxx">. my problem is now that in my background "record_count.php" i have several values i echo but in need them in separate HTML <div id="1, 2, ...> In my example it is $name and $city. How can i connect the values to a specific HTML <div id="1, 2, ...> ? (Please ignore the old query method i have copy/paste here. In my code i am using prepared statements with PDO)
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php?q=<?php echo $id; ?>').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
<body>
<div id="load_tweets"> </div>
</body>
</script>
record_count.php
<?php
include("db.php");
$search_word=$_GET['q'];
$sql = mysqli_query($db,"Select name, city FROM users where id = $id");
$record_count=mysqli_num_rows($sql);
//Display count.........
echo $city;
echo $name
?>
Related
I have an index.php, a navbar.php landingpage.php, and a landingpage.js
The navbar.php file is where I retrieve user information upon successful login on index.php As shown below, I use if-else to select which navigation items to display per user. In this case, we have Settings navigation item.
navbar.php
<?php
require_once 'core/init.php';
require_once 'dbutil/dbconnection.php';
require_once 'functions/sanitize.php';
require_once 'functions/redirect.php';
$user = new User();
$user->setId($_SESSION['userId']);
$user->setUsername($_SESSION['username']);
$user->setPassword($_SESSION['password']);
$user->setLastname($_SESSION['lastname']);
$user->setFirstname($_SESSION['firstname']);
$user->setMiddleinitial($_SESSION['middlename']);
$role = new Role();
$role->setRoleId($_SESSION['roleId']);
$role->setRolename($_SESSION['rolename']);
?>
<?php if ($role->getRolename() === 'Administrator') : ?>
<a class="nav_tab" id="admin_settings" href="#">
Settings
</a>
<?php endif; ?> ....
landingpage.php has the navbar.php attached to it.
<?php
require_once 'navbar.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin | Dashboard</title>
<link rel="stylesheet" href="css/dashboard_admin.css">
</head>
<body>
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<!-- this div gets filled with different content/page depending on what was clicked on the navbar. -->
<!-- end of container-->
</div>
<script src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
var user = '<?php echo json_encode($user);?>';
var role = '<?php echo json_encode($role); ?>';
</script>
<script src="js/landingpage.js"></script>
</body>
</html>
GOAL: I had to pass the php $user variable and $role to landingpage.js (in other words, make their values visible within the landingpage.js)
PROBLEM: The way I have it setup to make $user and $role variables' values visible in landingpage.js, exposes $user and $role properties when you view the page source code. I can't think of another way or setup to pass php objects $user and $role values to my external javascript file without exposing its properties.
The reason I am passing the json_encode($user) and json_encode($role) to landingpage.js is so that I can show or hide parts of the landing page depending on the role of user who is logged in.
landingpage.js
var userObj = JSON.parse(user);
var roleObj = JSON.parse(role);
$(document).ready(function(){
loadDashboard();
});
function loadDashboard() {
var url_admin_dashboard = 'view/admin_dashboard.php';
var url_teacher_dashboard = 'view/teacher_dashboard.php';
var url_student_dashboard = 'view/student_dashboard.php';
div_content_container.html('');
if (roleObj.rolename === 'Administrator') {
div_content_container.load(url_admin_dashboard);
} else if (roleObj.rolename === 'Teacher') {
div_content_container.load(url_teacher_dashboard);
} else if (roleObj.rolename === 'Student') {
div_content_container.load(url_student_dashboard);
}
}
Sorry for the long description. I'm fairly new with integration of PHP AJAX and JQuery and still trying to really understand how to properly setup the pages to avoid repetition of codes.
I'd appreciate any suggestion. I just thought that it's really wrong to expose the php object values during json_encode()
Thank you.
I have php inside javascript, and I made a query inside php, but the query cannot be fetched even in php area itself, why?
I have tried that query in PHPmyAdmin manually and it works fine. The "ca" field value is 1 not 0, but after i apply on code the result of "ca" is 0. What is wrong exactly? And there's no error message shows in console log.
image:
simple code:
<?php
include('ckcon.php');
include('logincheckmember.php');
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
<script>
function kampret(){
var ssloginmember = document.getElementById('id1').textContent;
var ambilun = document.getElementById('id2').textContent;
<?php
$ssloginmember=ssloginmember;
$ambilun=ambilun;
$q=mysql_query("SELECT COUNT(ai) AS ca,unnum FROM t_follow WHERE username='$ssloginmember' AND username2='$ambilun'");
$f=mysql_fetch_object($q);
$unnum2=$f->unnum;
$ca=$f->ca;
if($ca==0){
$status='follow';
$unnum=0;
}else{
$status='unfollow';
$unnum=$unnum2;
}
?>
var status='status = '+<?php echo json_encode($status);?>;
var unnum='unnum = '+<?php echo json_encode($unnum);?>;
var output1='output1 = '+<?php echo $ssloginmember;?>;
var output2='output2 = '+<?php echo $ambilun;?>;
document.getElementById('status').innerHTML = status;
document.getElementById('unnum').innerHTML = unnum;
document.getElementById('output1').innerHTML = output1;
document.getElementById('output2').innerHTML = output2;
}
</script>
</head>
<body>
<div id="status">status</div>
<div id="unnum">unnum</div>
<div id="output1">output1</div>
<div id="output2">output2</div>
<br>
<button onClick="kampret()" >button</button><br>
<br>
<div id="id1">melisavirgi</div>
<div id="id2">ririnputrian</div>
<br>
<?php
echo "ssloginmember=$_SESSION[ssloginmember]";
?>
</body>
</html>
result:
The problem seems to be that you are trying to get a javascript value in the PHP, ie $ssloginmember=ssloginmember;.
The PHP code is run before the page is loaded in the browser and generates parts of your javascript code. Your script seems to be acting as if it is run every time the javascript function is called, and as if both languages are the same.
AJAX is probably going to be your best solution - post the data to a PHP script that returns the values you need.
I suspect you may need to brush up on the difference between client side and server side code, too.
The purpose of my code is to randomly display four icons and depending on which one the user clicks on, a small amount of text will be appended to a text file. My problem is that, after an icon is clicked on, all four of the functions are called which writes to the txt file four times. How can I get it so that only the correctly corresponding function is called.
<div style="text-align:center" "padding-left: 60px">
<form action="(im hiding the URL)construct/index.html" id="formid" onclick= function() {myFunction()}>
<form>
</form>
</form>
</div>
<script>
document.getElementById("icon_1.png").onclick = function writeTo1(){
<?php
$file = fopen("icon_select.txt","a");
echo fwrite($file,"-Icon 1-");
fclose($file);
?>
}
document.getElementById("icon_2.png").onclick = function writeTo2(){
<?php
$file = fopen("icon_select.txt","a");
echo fwrite($file,"-Icon 2-");
fclose($file);
?>
}
document.getElementById("icon_3.png").onclick = function writeTo3(){
<?php
$file = fopen("icon_select.txt","a");
echo fwrite($file,"-Icon 3-");
fclose($file);
?>
}
document.getElementById("icon_4.png").onclick = function writeTo4(){
<?php
$file = fopen("icon_select.txt","a");
echo fwrite($file,"-Icon 4-");
fclose($file);
?>
}
</script>
Looks to me like the 4 bits of PHP are running when the page is requested, and therefore adding to the text file at that time. Then the functions are empty when the JavaScript runs so it has no effect. Check the page source in the browser to see what the functions look like to the browser and after page load but before clicking on an icon check to see if the text has been added to the file.
Can I trigger the execution of a php file from another php file when performing an action? More specific, I have an anchor generated with echo, that has href to a pdf file. In addition of downloading the pdf I want to insert some information into a table. Here's my code, that doesn't work:
require('./database_connection.php');
$query = "select author,title,link,book_id from book where category='".$_REQUEST['categorie']."'";
$result = mysql_query($query);
$result2 = mysql_query("select user_id from user where username='".$_REQUEST["username"]."'");
$row2 = mysql_fetch_row($result2);
while($row= mysql_fetch_row($result))
{
echo '<h4>'.$row[0].' - '.$row[1].'</h4>';
if(isset($_SESSION["username"]) && !empty($_SESSION["username"]))
{
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo ' <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function insert_download() {
$.ajax({
type: "GET",
url: "insert_download.php" ,
success : function() {
location.reload();
}
});
}
</script>
<a onclick="insert_download()" href="'.$row[2].'" download> download </a>';
}
And here's the insert_download.php:
<?php
require('./database_connection.php');
$query = "insert into download(user_id,book_id,date)values(".
$_REQUEST["id_carte"].",".
$_REQUEST["id_user"].",".
date("Y-m-d h:i:s").")";
mysql_query($query,$con);
mysql_close($con);
?>
Can anyone help me with this? Thanks!
As I understand correctly, you want to display a link, and when the user clicks that link,
some data is inserted into a database or something;
the user sees a download dialog, allowing him to download a file?
If this is correct, you can use this code:
On your webpage:
download
result.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "";
?>
<!DOCTYPE html>
<html>
<head>
<title>Downloading...</title>
<script type="text/javascript">
function redirect(url) {
//window.location.replace(url);
window.location.href = url;
}
</script>
</head>
<body>
Download is starting...
<script type="text/javascript">
redirect("http://example.com/download.php?file=dummy.pdf");
</script>
</body>
</html>
download.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "nullfile";
$file_url = "download_dir_or_something/".$file;
// Put some line in a log file...
file_put_contents("logfile.txt", "successful on ".date("Y-m-d H:i:s")."\n", FILE_APPEND);
// ...or anything else to execute, for example, inserting data into a database.
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".basename($file_url)."\"");
readfile($file_url);
?>
Why not use a redirection instead of "complicated" AJAX?
<!-- in your first document -->
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo 'download';
and in download_pdf.php
<?php
require('./database_connection.php');
...
mysql_close($con);
header("location: " . $_GET['redirect']);
You're lacking basic skill of debugging. If I was you, I should:
Use a browser which supporting, ex: Chrome with "Network" inspecting tab ready
Try click on the link <a onclick="insert_download()" ... and see if the ajax request is performed properly (via Network inspecting tab from your chrome). If not, re-check the generated js, otherwise, something wrong with the download_pdf.php, follow next step
Inspecting download_pdf.php: turn on error reporting on the beginning (put error_reporting(E_ALL); and ini_set('display_errors', 1); on top of your file) try echoing something before and/or after any line you suspect that lead to bugs. Then you can see those ajax response from your Network inspecting tab... By doing so, you're going to narrow down which line/scope of code is causing the problem.
Note that the "echoing" trick can be avoid if you have a solid IDE which is supporting debugger.
Hope it can help
I am trying to make a select have some pre-loaded options.
I have a php script that queries for these options, and I want to load them into the select on an html page.
My attempt right now..
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$("#usersList").html(data.value);
});
});
});
</script>
</head>
<body>
<form>
Find Users in: <select id="usersList" name="usersList">
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
PHP
<html>
<head>
</head>
<body>
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$ary[] =$info['State'];
}
mysql_close();
?>
</body>
</html>
My PHP works fine, but I am not sure how to get that information into my select.
All help appreciated!
First:
The html select-tag needs to get closed like this:
<select></select>
Next:
Your $ary isnt defined anywhere and it isnt returned anywhere
Use json_decode(); to return json
(and dont use any html head/body in your php file which outputs json)
Your json.php:
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
$ary = Array();
while($info = mysql_fetch_array( $data ))
{
array_push($ary,$info["state"]);
}
mysql_close();
echo json_encode($ary);
?>
Next:
You need to append option tags to your select with jquery like this:
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$.each(data,function(key,indata){
$("#usersList").append($("<option>",{
html : indata
}));
})});
});
});
Seems you have jquery library is missing. Please add it after the <head> tag and try:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
In the php, after mysql_close(). Add
print json_encode($ary);