Display content dynamically with Dropdown (with connection to DB) - javascript

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): ?>

Related

Unable to get Select2 to get data from my mysql database

I've been trying a few different methods of getting Select2 to use information from my MySQL database. Currently, it seems something has been lost in translation and it's just showing the literal name of the array(".$title"). The database is called vettigevrijdag and the table is called article.
My PHP snippet that is to be included in the navbar:
<head>
<link href="select2.css" rel="stylesheet"/>
<script src="select2.js"></script>
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
</script>
<select class="js-example-basic-single">
<?php
include('db.php');
$stmt=$db_con->prepare("SELECT * FROM article");
$stmt->execute();
if($stmt->rowCount() > 0){
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$id = $row['if'];
$title = $row['title'];
echo '<option value="'.$id.'">'.$title.'</option>';
}
}
?>
</select>
</head>
My db.php file:
<?php
$dbhost = "localhost"; /* Host name */
$dbname = "vettigevrijdag"; /* Database name */
$dbuser = "localhost"; /* User */
$dbpassword = "123456"; /* Password */
try {
$db_con = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpassword);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $ex) {
die($ex->getMessage());
//throw $th;
}
?>
<select class="js-example-basic-single">
<?php
include('db.php');
$stmt=$db_con->query("SELECT * FROM article")->fetchall(PDO::FETCH_ASSOC));
foreach($stmt as $key=>$row){
echo "<option value=\"".$row['if']."\">".$row['title']."</option>";
}
?>
</select>

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

ajax jquery form fetching mysql data

I have troubles with JQuery and Ajax forms. I'm new in Ajax and Jquery. I'm creating a webapp with a search form. The data I'm fetching from MYSQL Database. So I have a request page with a form, then the mysql processing file, a javascript to return the requested data and a html file, where the results are displayed. So, my problem is, that I can't display the results under index.html. Therefore I tried to action directly to landmarks.php and there I can see the reuslts in array like this
([{"id":"1","name":"Big Ben","latitude":"51.500600000000","longitude":"-0.124610000000"}]);
The request.html file
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<form method="post" action="landmarks.php">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<label for="l_name"><b>Name</b></label>
<input type="text" name="l_name" id="l_name" value="" />
<input class="submit" type="submit" value="Submit" />
</fieldset>
</div>
</form>
</body>
Then this file for mysql
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "test";
$password = "test132";
$database = "landmarks";
$l_name = $_POST["l_name"];
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude FROM landmarks WHERE l_name like '".$l_name."' ORDER BY l_name";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
my json callback looks like this
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'landmarks.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.latitude+'<br>'
+ item.longitude+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.')
}
});
});
and finally my final page, where the results should be displayed
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/load-json.js"></script>
</head>
<body>
<div id="output"></div>
</body>
</html>

Run a php update file from 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);
});
}

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

Categories

Resources