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
Related
I know this is frequently asked question however I have tried using :
script language='javascript'
placed header in else after alert
script type='text/javascript'
Still I don't get alert box, while else parts executes perfectly.
Here's my code:
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data=mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
}
else{
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
?>
What am I missing here.
Thanks
You have your js files mixed up.
Include jquery and then your script, inside separate tags:
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>';
echo '<script type="text/javascript">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
By the way, you do NOT need jquery for a simple alert, as it is plain javascript. Try to avoid including external library if not needed, you will end up with a bloated code.
And printing js with php it's a bit of a hack. Why not just print it into your html or js file?
Javascript inside a script tag that has an src attribute does not get executed, you have to create a second script tag after the jquery one.
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data = mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo '</script>';
echo "<script>alert('PF No. Does not exist. Please Contact Admin!!!');</script>";
} else {
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
}
?>
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();
}
}
?>
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();
}
}
?>
im pretty new into this stuff and I just tried to do an AJAX request with Javascript and PDO and PHP to create a dropdown function that reacts dynamically in order to display new content.. Since my knowledge is quite limited here I created it by combining snippets of code I got from various pages and videos. The error is:
Parse error: syntax error, unexpected 'endforeach' (T_ENDFOREACH) in /var/www/xxx/html/listing.php on line 22
This is my listing.php page where the dropdown and the new content should be displayed:
<!DOCTYPE html>
<html>
<head>
<title>listing</title>
<meta charset="UTF-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="keywords" content="">
<link href=".css" type="text/css" rel="stylesheet">
<link href="favicon.ico" type="image/x-icon" rel="shortcut icon">
</head>
<body>
<select name="user" id="user-select">
<option value="">Choose a user</option>
<?php foreach ($subjects->fetchAll() as $user); ?>
<option value="<?php echo $user['subject_id']; ?>"><?php echo $user['subject']; ?></option>
<?php endforeach; ?>
</select>
<div id="user-profile"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="js/global.js"></script>
This is the global.js file:
$('#user-select').on('change', function() {
var self = $(this);
$.ajax({
url: 'https://www.xxx.de/partials/user.php',
type: 'GET',
data: { user: self.val() },
success: function(data){
$('#user-profile').html(data);
}
});
});
And the partials/user.php, which contains the connection to the database:
<?php
$dsn = "xxx";
$user = "xxx";
$pw = "xxx";
try {
$pdo = new PDO($dsn, $user, $pw);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if (isset($_GET['user'])) {
$userQuery = "
SELECT
subjects.subject_id,
subjects.subject,
FROM subjects
WHERE subjects.subject_id = :subject_id
";
$user = $pdo->prepare($userQuery);
$user->execute(['subject_id' => $_GET['user']]);
$selectedUser = $user->fetch(PDO::FETCH_ASSOC);
print_r($selectedUser);
}
?>
Any help is appreciated and I am thankful for any tips !
Stupid mistake.. I simply forgot to include the connection on the listing.php page to fill the foreach loop.
->
On listing.php before the !DOCTYPE html begins:
<?php
$dsn = "xxx";
$user = "xxx";
$pw = "xxx";
try {
$pdo = new PDO($dsn, $user, $pw);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$usersQuery = "SELECT fach_id, fach FROM faecher";
$users = $pdo->query($usersQuery);
?>
Try replacing ; with : in php foreach statement
<?php foreach ($subjects->fetchAll() as $user): ?>
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);
});
}