Run a php update file from javascript - javascript

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);
});
}

Related

JavaScript to PHP variable value pass error (document.write command is not working)

After sending the country name "US" in JavaScript to PHP code, I will try to receive the results of PHP's work back to JavaScript and use them.
To do this I used the below code.
$ctryNm_php_temp = "document.write(ctryNm);";
As a result, it seemed that the value 'US' of the ctryNm variable was well transfered to php code.
The cryNm value and $SQL value printed on the screen contain 'US'.
However, the results of the SQL query were returned to an empty value, so we checked.
The IF statement shows that ctryNm and 'US' are different values.
(The output on the screen shows the same value and data type as string.)
I printed $result_obj and found no value.
echo and console.log command result for checking:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var ctryNm = "US";
</script>
<?php
$ctryNm_php_temp = "<script language='javascript'>document.write(ctryNm);</script>";
$ctryNm_php = $ctryNm_php_temp;
echo $ctryNm_php . "<br><br>";
echo "--------------" . "<br>";
echo gettype($ctryNm_php) . "<br>";
if ($ctryNm_php == 'US') {
echo "Same" . "<br>";
} elseif ($ctryNm_php != 'US') {
echo "Different" . "<br>";
}
$conn = new mysqli("...", "...", "...");
mysqli_select_db($conn, '...');
mysqli_query($conn, "set names utf8");
$sql = "SELECT * FROM acst_covid_who WHERE country_code = '$ctryNm_php'";
echo $sql . "<br>";
$result_obj = mysqli_query($conn, $sql);
echo "result_obj :" . $result_obj . "<br>";
$date_adjust = 0;
$latestDate_trend = '';
while ($row = mysqli_fetch_array($result_obj)) {
if ((int)$row['confirmed_new'] !== 0) {
$latestDate_trend = $row['date'];
$date_adjust = 1;
} elseif ((int)$row['confirmed_new'] === 0) {
$latestDate_yester_trend = strtotime($row['date'] . "-1 days");
$latestDate_trend = date("Y-m-d", $latestDate_yester_trend);
$date_adjust = 0;
};
};
$result_obj = mysqli_query($conn, $sql);
$total_rows_trend = mysqli_num_rows($result_obj) - $date_adjust;
$arr_trend = array();
while ($row = mysqli_fetch_array($result_obj)) {
array_push($arr_trend, $row);
}
echo $total_rows_trend;
echo json_encode($latestDate_trend);
?>
<script>
var latestDate_js_trend = <?php echo json_encode($latestDate_trend) ?>;
var arr_js_trend = <?php echo json_encode($arr_trend) ?>;
var arr_length_trend = <?php echo $total_rows_trend ?>;
console.log(latestDate_js_trend);
console.log(arr_js_trend);
console.log(arr_length_trend);
</script>
</body>
</html>
this sadly does not work like this.
PHP code is executed first on the server, so before the website is even shown in the browser. The order you write it does not matter.
The process is like this:
You type the address in the browser and it asks the server for the page.
The server literally runs an app called php, that reads what you wrote in the code, reads only what is between <?php and ?>, nothing else (technically the first one can be <?=)
When it is done, the server sends the page to browser
The browser reads html and fires JavaScript, long after PHP was already changed.
This is simplified but show why your code will not work.

how to send data from a php page to ajax page

i have this code, now i want to send this $_SESSION['roll_id'] variable to another page menu.php where ajax function is written. how i send this variable to another ajax page for set data.
this is login.php page.
if($row["Login_Id"]==$username and $row["Login_Pass"]==$password)
{
echo "<h2 align='center'>" ."Login Sucessfull welcome" ." " .$row["Login_Id"]
."</h2>" ;
$_SESSION['roll_id']=$row['Roll_Id'];
//echo "ID" .$_SESSION['roll_id']; (give roll id)
header("Location: menu.php");
}
else
{
echo "<h2 align='center'>" ."Login Failed" ."</h2>";
}
this is menu.php page where whole functionality is written. i want to send rollid from this page to submenu.php where i can use this roll id in sql query.
<?php
session_start();
$session = $_SESSION['roll_id'];
?>
<html>
<head>
<link href="menu_style.css" type="text/css" rel="stylesheet"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var rollid = '<?php json_encode($session); ?>';
$.ajax
({
type:'post',
url:'submenu.php',
data:{"roll_id":rollid},
success:function(response)
{
//console.log(response);
var menuArray= JSON.parse(response);
var html ="";
$.each( menuArray, function( key, value )
{
html += "<li><a href=''>" + value.Menu_Name + "</a>";
if(value.subMenu.length > 0)
{
console.log(JSON.stringify(value.subMenu));
html += "<ul>";
$.each( value.subMenu, function( key, subValue )
{
html += "<li><a href=''>" + subValue.text + "</a></li>";
});
html += "</ul>";
}
html += "</li>";
});
console.log(html);
if(response!="")
{
$("#main_menu").html(html);
}
}
});
});
this is submenu.php page
<?php
session_start();
include('config.php');
$roll_id = $_POST['roll_id'];
$q="select a.Roll_Id, a.Menu_Id, b.Menu_Name, b.Menu_URL,b.Menu_Level,
b.MainMenu_ID, b.Menu_Order, b.Account_id,b.is_deleted from roll_menu AS a
join menu AS b on a.Menu_Id=b.Menu_Id and a.Roll_Id=".$roll_id;
$menu = mysqli_query($conn, $q);
$mainMenu = array();
foreach($menu as $x=>$value)
{
if($value['MainMenu_ID']==0)
$mainMenu[]=$value;
}
$menuData= array();
foreach($mainMenu as $y=>$value1)
{
$subMenu= array();
$m=$mainMenu[$y]['Menu_Id'];
$q1="select a.Roll_Id, a.Menu_Id, b.Menu_Name, b.Menu_URL,
b.Menu_Level, b.MainMenu_ID, b.Menu_Order, b.Account_id,
b.is_deleted from roll_menu AS a join menu AS b on
a.Menu_Id=b.Menu_Id and a.Roll_Id=".$roll_id."and b.MainMenu_ID=$m";
$menu1 = mysqli_query($conn, $q1);
while($row=mysqli_fetch_array($menu1))
{
if($row["MainMenu_ID"]==$m)
{
$subMenu[]=array("text"=>$row["Menu_Name"]);
}
}
$value1["subMenu"] = $subMenu;
$menuData[] = $value1;
}
$menuDataJSON = json_encode($menuData);
echo $menuDataJSON;
now i attach the full code of submenu.php page.
Try like this may its helpful for you
<?php
session_start();
$session = $_SESSION['roll_id'];
?>
<html>
<head>
<link href="menu_style.css" type="text/css" rel="stylesheet"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var rollid = "<?php echo $session; ?>"; //change here
alert(rollid)
$.ajax
({
type:'post',
url:'submenu.php',
data:{roll_id:rollid}, // change alse here
/*success: function (data) {
alert(data);
}*/
You echoed the <h2 ... on successful login and then used the header function to redirect. This will cause a warning `Warning: Cannot modify header information - headers already sent by” and redirection might not work.
As for AJAX, you need to echo the roll_id like this:
var rollid = '<?php echo json_encode($session); ?>';
I woudl also like to point out that since rollid is a single value, you dont really need to json_encode it.
1st : You missed to echo the variable .
2nd : if it's not a array no need json_encode
3rd : Before header function you will not echo any browser out put like html or echoing something will cause Warning: Cannot modify header information - headers already sent so take care about that .
4th : Try to put exit(); function after header function
header(....);
exit();
Js :
var rollid = '<?php echo $session; ?>';
just start_session() at top of page and try like this
var rollid = "<?php echo $_SESSION['roll_id']; ?>";

Make a pagination using JQuery after getting data from api.php

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();
}
}
?>

Connecting to database via PHP and displaying contents on browser

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

2 dropdown lists dependent on each other in php include. Need to reload only the include file not the entire page

I have 2 simple drop down lists one dependent on the other in a php include.
When one is selected it refreshes the page and then populates the second with the correct data, (works great).
The problem is that it refreshes the whole page instead of just the include file.
Is there a way to do just refresh the include? I have looked at many other examples (Ajax, Javascript etc) on here and other sites and cannot seem to get it to work.
A huge thank you in advance to anyone who can point me in the right direction.
<form enctype="multipart/form-data" action="advanced_search2.php" method="POST">
<?php require 'config.php'; ?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<?
echo '<div id="publication">';
echo "<select name='cat'><option value=''>Select one</option>";
$quer2="SELECT DISTINCT id,publication FROM publication WHERE appear = 'Yes' and Search = 'Yes'";
foreach ($dbo->query($quer2) as $noticia2) {
echo "<option selected value='$noticia2[publication]'>$noticia2[publication]</option>"." <BR>";
}
echo "</select>";
echo '</div>';
?>
<?
echo '<div id="section">';
echo "<select name='subcat'><option value=''>Select one</option>";
$quer="SELECT DISTINCT section FROM sandbox WHERE publication = '$cat' AND appear = 'Yes'";
foreach ($dbo->query($quer) as $noticia) {
echo "<option value='$noticia[section]'>$noticia[section]</option>";
}
echo "</select>";
echo '</div>';
?>
<form>
<script>
$('#publication').change(function(){
var page = $( this ).attr('data-page');
$.ajax({
type:'POST',
url:page,
success: function(response){
$('#section').html(response);
}
});
})
</script>
wrap your second select box with a div
in you js function 'reload', call a ajax (another page) where you pass the catid and echo your second select box in that page
update your div html with the ajax response.
Your main page can look like this
<?php require 'config.php'; ?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<?
echo '<div id="publication">';
echo "<select name='cat'><option value=''>Select one</option>";
$quer2="SELECT DISTINCT id,publication FROM publication WHERE appear = 'Yes' and Search = 'Yes'";
foreach ($dbo->query($quer2) as $noticia2) {
echo "<option selected value='$noticia2[publication]'>$noticia2[publication]</option>"." <BR>";
}
echo "</select>";
echo '</div>';
?>
<div id="section"></div>
<script>
$('#publication').change(function(){
$('#section').load('subcat.php?cat='+$(this).val());
});
})
</script>
And another page for getting subcat (subcat.php)
<?php
require 'config.php';
$cat = $_GET['cat'];
echo "<select name='subcat'><option value=''>Select one</option>";
$quer="SELECT DISTINCT section FROM sandbox WHERE publication = '$cat' AND appear = 'Yes'";
foreach ($dbo->query($quer) as $noticia) {
echo "<option value='$noticia[section]'>$noticia[section]</option>";
}
echo "</select>";
?>

Categories

Resources