Here is my codes-
client.php
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style>
#show{
background:red;
}
</style>
</head>
<body>
<?php
<div id="show"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('api.php')
});
});
</script>
</body>
</html>
api.php
<?php
$conn = new mysqli('localhost', 'root', '', 'ajax01');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT name FROM variables");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['name'] . '<br>';
}
}
?>
These codes are giving me the results like-
Result of above codes
I am getting the values from database and it is fetching all the data. Therefore, I need a pagination with these value. Need help.
Based on your comments,
I want a pagination that will show only one value and next page will show another...second result will show after click on next>
There are few things you need to consider here,
Instead of setInterval() and load() functions, simply use an AJAX request to implement your pagination functionality
Use prepared statements because that will help you in preventing SQL injection. Also, read about how you can prevent SQL injection in PHP.
Based on these above points and your below comments, the solution would be like this:
client.php:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style>
#show{
background:red;
}
</style>
</head>
<body>
<div id="show">
<?php
$conn = new mysqli('localhost', 'root', '', 'ajax01');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
// prepare query statement
if($stmt = $conn->prepare("SELECT name FROM variables LIMIT 0, 1")){
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($name);
// fetch values
$stmt->fetch();
// display name and pagination link
if(isset($name) && !empty($name)){
echo $name . '<br />';
?>
<div id='link-div' style='background-color:#ffffff'>
<a href='' class='showmore' id='1'>Next »</a>
</div>
<?php
}
// close statement
$stmt->close();
}
?>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click','.showmore',function(event){
event.preventDefault();
var offset = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'api.php',
cache: 'false',
data: {offset: offset},
beforeSend: function(){
$('#link-div').html('<span>Loading...</span>');
},
success: function(data){
$('#link-div').remove();
$('#show').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
// error
}
});
});
});
</script>
</body>
</html>
api.php:
<?php
if(isset($_POST['offset'])){
$offset = $_POST['offset'];
$prev = $offset - 1; // Previous link in the pagination series
$next = $offset + 1; // Next link in the pagination series
$conn = new mysqli('localhost', 'root', '', 'ajax01');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
// prepare query statement
if($stmt = $conn->prepare("SELECT COUNT(name) FROM variables")){
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($total_rows);
// fetch values
$stmt->fetch();
// close statement
$stmt->close();
}
// prepare query statement
if($stmt = $conn->prepare("SELECT name FROM variables LIMIT ?, 1")){
// bind parameter
$stmt->bind_param('i', $offset);
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($name);
// fetch values
$stmt->fetch();
// display name and pagination link
if(isset($name) && !empty($name)){
echo $name . '<br />';
?>
<div id='link-div' style='background-color:#ffffff'>
<?php
if($offset > 0){
?>
<a href='' class='showmore' id='<?php echo $prev; ?>'>«Prev </a>
<?php
}
if($offset < $total_rows - 1){
?>
<a href='' class='showmore' id='<?php echo $next; ?>'>Next »</a>
<?php
}
?>
</div>
<?php
}
// close statement
$stmt->close();
}
}
?>
Related
I'm developing a website using php. I have some problems. I want to know know how to get modified table values while running the php page without refreshing the page.
<html>
<?php
function fun_get_user_name() {
$host_name = "localhost";
$db_user_name = "root";
$password = "";
$database_name = "database_name";
$connect = mysqli_connect($host_name, $db_user_name, $password, $database_name);
$query = "SELECT * FROM `users` ";
$result = mysqli_query($connect, $query);
$output = "";
while ($row = mysqli_fetch_array($result)) {
$output = $output."<br/>"..$row[0];
}
}
?>
<script>
function js_function() {
result = "<?php echo fun_get_user_name; ?>";
document.getElementById('div_body_users').innerHTML = result;
}
window.setInterval(function() {
js_function();
}, 1000);
</script>
<body>
<div id="div_body_users">
</div>
</body>
</html>
when I made a change in phpmyadmin table the change didn't affect the page. But I expected the updated table.
So move the fun_get_user_name to another file and then in a setInterval do a n ajax call to that file.
$.get( "users.php", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
For more info on ajax request look at this link
https://api.jquery.com/jquery.get/
On user.php you just need to add fun_get_user_name
You can do it with using ajax, here changed with your ajax url and database connection details.
<html>
<?php
function fun_get_user_name()
{
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
}
if($_GET['ajax']==1){
$data=fun_get_user_name();
echo $data;
exit(0);
}
?>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function(){
setInterval(js_function,1000);
function js_function()
{
$.ajax({
url: "http://localhost/test2/test.php?ajax=1",
data: '',
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (result) {
document.getElementById('div_body_users').innerHTML=result;
}
});
}
});
</script>
<body>
<div id="div_body_users">
</div>
</body>
</html>
You for update page without page refresh you have to use AJAX along with setInterval function.
Please check below link
https://www.w3schools.com/asp/asp_ajax_intro.asp
I want to send data from php to php and in same time I also want to send data from js to php. I have one index.php which contains php and js part. In enrolled.php I want to collect my data. SQL injection or other security problems are not important. I do not get any error but it does not save to database.
Small part of index.php
<!DOCTYPE html>
<html lang="en">
<head>
//smt....Not important
</head>
<body>
//smt....Not important
<div id="dom-target" style="display: none;">
<?php
include_once "connection.php";
session_start();
$username = $_SESSION['username'];//coming from previous page.
echo htmlspecialchars($username); //for sending variable from php to js.
?>
</div>
<script type = "text/javascript">
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
var div = document.getElementById("dom-target");
var username = div.textContent;//these lines help to gett data from php
document.getElementById("usernamee").innerHTML = username;//for checking
$.ajax({
type: "POST",
url: "addenrolled.php",
data: {
// Send the username (js, not php)
username: username,
subject: subjectone,
course: courseone,
grade: gradeone
}, success: function(data) {
alert("sucess");
}
});
});
</script>
</body>
</html>
enrolled.php
<?php
include_once "connection.php";
$nick = $_POST['username'];
$subject=$_POST['subject'];
$course=$_POST['course'];
$grade=$_POST['grade'];
echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $con->prepare("INSERT INTO enrolledtable ('nickname', 'subject', 'course', 'grade') VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
header('Location: index.php');
exit();
}
?>
Change your jQuery to this
<script>
$(document).ready(function(){
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
$.post('enrolled.php', {subjectone: subjectone, courseone: courseone, gradeone: gradeone, addmore: "yes"}, function(response){
console.log(response);
})
});
});
</script>
Then in your PHP modify the prepare statement to the following
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
enrolled.php
<?php
session_start();
include_once "connection.php";
if (isset($_POST['addmore'])) {
$nick = $_SESSION['username'];
$subject=$_POST['subjectone'];
$course=$_POST['courseone'];
$grade=$_POST['gradeone'];
// //echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
// header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
//header('Location: index.php');
exit();
}
}
?>
I am trying to run a update to mysql when a link in a table is clicked.
For this I have made 3 files:
movies.php
<html>
<head>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<script src="video.js" type="text/javascript"></script>
</head>
<?php
include 'combo_new.php';
include 'config.php';
include 'opendb.php';
$ndate = $_POST['ndate'];
$result = mysql_query("SELECT *
FROM DayMovie
WHERE FileDate LIKE '$ndate%' ORDER BY FileDate DESC")
or die(mysql_error());
echo "<table border='0'>";
echo "<tr> <th>Dato</th><th>Visninger</th><th>Handling</th></tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo date('d.m.Y', strtotime($row['FileDate']));
echo "</td><td>";
echo $row['Counter'];
echo "</td><td>";
echo "<a href='alldaymovies/{$row['FileName']}' onclick='playVideo(this.href, {$row['FileName']});' onkeypress='playVideo(this.href, {$row['FileName']});'>Se film</a>";
echo "</td></tr>";
}
echo "</table>";
include 'closedb.php';
?>
</html>
video.js
function playVideo(filename)
{
$.post( "update.php" {"filename":filename},
function( data ) {
alert( "Data Loaded: " + data );
});
}
update.php
<?php
include 'config.php';
include 'opendb.php';
$filename = $_POST['filename'];
$result = mysql_query("UPDATE DayMovie SET Counter=Counter+1 WHERE FileName='$filename'")
or die(mysql_error());
include 'closedb.php';
?>
However theres something not correct here... Can anyone see where I am going wrong?
The problem is probably that your user is already redirect to the other page before the call to update.php got finished. Keep in mind that if you redirect the browser to another page that request that are busy get cancelled.
To test if this is really the problem try to replace the href of the "a" element with "#".
And change your playVideo function to look like this:
function playVideo(filename)
{
$.post( "update.php" {"filename":filename},
function( data ) {
alert( "Data Loaded: " + data );
setTimeout(function(){ document.location.href="alldaymovies/" + filename;}, 300);
});
}
I am connecting to an SQL server via PHP script and displaying the contents retrieved on the browser.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
href="http://cdn.sencha.com/ext/trial/5.0.0/build/packages/ext-theme-neptune/build/resources/ext-
theme-neptune-all.css">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/php" src="connection.php"></script>
</head>
<body>
</body>
</html>
app.js
document.addEventListener('DOMContentLoaded', function() {
d3.json("connection.php", function (data) {
document.write(data);
});
});
connection.php
<?php
// Server Name
$myServer = "10.112.1.2";
// Database
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=>"logs", "CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect($myServer, $connectionInfo);
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
}
$sql = "SELECT * FROM dbo.logsData";
$data = sqlsrv_query( $conn, $sql );
if( $data === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$result = array();
do {
while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while ( sqlsrv_next_result($data) );
echo json_encode($result);
sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>
All 3 files are in the same folder.
The browser just displays a null and I don't hit any of the logging information from the .php file. Is my method right? Am I using the right javascript event?
Change your connection.php in this way:
if (!$conn) {
$message = "Connection failed";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
header('Content-Type: application/json');
}
You need to change mime type of your response. Moreover you cannot print out anything else than json data. That's way I removed from your code these lines:
$message = "Connected";
echo "<script type='text/javascript'>alert('$message');</script>";
Try using a relative pathname for connection.php here: d3.json("connection.php"
Something like "/dirname/connection.php".
You can test connection.php alone using a full pathname, like http://www.yourserver.xxx/dirname1/dirname2/...connection.php
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()