Syntax Highlighting PHP SQL - javascript

I have a page that searches a database. I am looking to get the data that the user enters in the search box to be highlighted in the search results.
The data from the user is stored in the variable '$criteria', and all contents of that variable I am aiming to highlight.
My PHP looks as follows:
<?php
session_start();
if ($_SESSION['loggedin'] != 1) {
header("Location: ../");
}
include("../php_includes/connection.php");
$queryErrorMessage = "";
?>
<html>
<head>
<title>Search Tasks</title>
<link rel="stylesheet" href="../css/bootstrap.min.css">
<script src="../js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<?php include("header.php"); ?>
<?php include("sidebar.php"); ?>
<div class="row">
<div class="col-md-9">
<div class="well well-lg">
<h3>Search Tasks</h3>
<hr>
<form method="post" action="">
<div class="input-group">
<input name="criteria" type="text" class="form-control" placeholder="What would you like to search for?...">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
Submit
</button>
</div>
</div>
</form>
<?php
//Run section of code if the POST criteria is provided for "criteria"
if(isset($_POST['criteria'])){
$criteria = mysqli_real_escape_string($db,$_POST['criteria']);
//If the user does not provide criteria to search, an error will be displayed.
if($criteria == ""){
$queryErrorMessage = "You did not provide any criteria";
GoTO errorMsg;
}
//Prepare sql statement checking each column with the criteria that is provided.
$sql = "SELECT * FROM taskinfo WHERE clientCompany LIKE '%".$criteria."%' OR clientName LIKE '%".$criteria."%' OR email LIKE '%".$criteria."%' OR contactNo LIKE '%".$criteria."%' OR details LIKE '%".$criteria."%'";
//Run sql query storing the records in $result
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result)>0){
//Get each row and put it into the array $row
echo '<h4>Displaying results for search criteria: <b>'.$criteria.'</b></h4>';
while($row = mysqli_fetch_array($result)){
$queryErrorMessage = "";
//Display the query results
?>
<div class="panel panel-default">
<div class="panel-body">
<h6><b>Task Details:</b></h6>
<?php echo $row['details'];?>
<h6><b>Task Information</b></h6>
<ul>
<li>Client Name: <?php echo $row['clientName'];?></li>
<li>Email: <?php echo $row['email'];?></li>
<li>Phone: <?php echo $row['contactNo'];?></li>
<li>Posted by <b><?php echo $row['postedBy'];?></b></li>
<li>Posted On: <b><?php echo $row['timeAdded']; ?></b></li>
</ul>
</div>
</div>
<?php
}
} else {
$queryErrorMessage = "No records found with your criteria.";
}
} else {
$queryErrorMessage = "Failed to perform query.";
}
}
//Check if there is an error message
//If true, echo the error to the user.
//
//Section of code is called errorMsg to
//Allow it to be called in the code above.
errorMsg:
if($queryErrorMessage != ""){
echo 'An Error Occurred: ';
echo $queryErrorMessage;
}
?>
</div>
</div>
</div>
</body>
</html>
If anyone can help, it'd be much appreciated.

this might help
<?php echo preg_replace_callback('/'.$criteria.'/i', function($matches){
return '<strong>' . $matches[0] . '</strong>';
}, $row['clientName']); ?>
it would make the search keyword in the content bold

Related

Deleting a picture with Ajax and php

I have a system where I can upload pictures from different users. Each user can then access a tab where he can see all the pictures that he uploaded by himself. From this tab the user should also be able to click on a button and delete each one induvidually.
I am struggling to make this work so I hope that somebody can help me out.
This is what my database looks like:
table: pictures, rows:
descPicture
id
imageFullNamePicture
titlePicture
userid
table: users, rows:
user_email
user_id
user_name
user_password
user_phone
user_zip
This is my code:
DBH.INC.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chhoe17";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(PDOException $e) {
echo $e->getMessage();
}
UPLOAD.PHP
<?php
include_once 'header.php';
include_once "includes/dbh.inc.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<section class="main-container">
<div class="main-wrapper">
<h2>Manage your pictures</h2>
<?php
//display a message and images if logged in!
if (isset($_SESSION['u_id'])) {
echo "Upload your pictures";
echo '<div class="picture-upload">
<h2>Upload</h2>
<br>
<br>
<br>
<form action="upload.inc.php" id="upload" method="POST" enctype="multipart/form-data">
<input type="text" name="filetitle" placeholder="Image title">
<input type="text" name="filedesc" placeholder="Image description">
<input type="file" id="file" name="file">
<button type="submit" name="submit">Upload</button>
</form>
</div>';
}
if (isset($_SESSION['u_id'])) {
echo ' <section class="picture-links">
<div class="wrapper">
<h2>Pictures</h2> ';
?>
<div id="pictures">
<?php
$sql = "SELECT * FROM pictures WHERE userid = '{$_SESSION['u_id']}'";
//$sql = "SELECT * FROM pictures ORDER BY userid DESC LIMIT 20;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$pictures = $stmt->fetchAll();
// if ($pictures !== null) {
foreach ($pictures as $pic) {
?>
<li>
<figure id="<?php echo $pic['id']; ?>">
<b>
<figcaption><?php echo $pic["titlePicture"] ?>
<img src=<?php echo $pic["imageFullNamePicture"] ?>>
<?php echo $pic["descPicture"] ?> <br>
</figure>
</li>
<span><input type="submit" id="del_btn" value="Delete Image" /></span>
<script type="text/javascript">
$(document).ready(function() {
$("input#del_btn").click(function() {
$.ajax({
type: "POST",
url: "delete.php", //
data: {
id: <?php echo $delid; ?>
},
success: function(msg) {
alert("Your picture has been deleted");
},
error: function() {
alert("failure");
}
});
});
});
</script>
<?php
}
}
?>
</div>
</div>
</section>
</body>
</html>
<?php
include_once 'footer.php';
?>
DELETE.PHP
<?php
include_once "includes/dbh.inc.php";
if (isset($_POST['id'])) {
$picID = $_POST['id'];
$sql = "DELETE FROM pictures WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($picID));
}
?>
As it is right now, nothing happens when I click the delete buttons that are attached to the pictures, and I dont get any alerts either. Any help that somebody could provide to make this work, would be very appreciated.
You're re-using id values, so when your jQuery selector executes which element should it find? Additionally, you're repeating the client-side click handler over and over in your loop. This can all be simplified.
Use a class to identify your "delete" button, and put the relevant id in a data attribute:
<button type="button" class="del_btn" data-id="<?php echo $delid; ?>">Delete Image</button>
Then later, outside the loop, create a single event handler which will listen on all the buttons and use the button's data-id to make the AJAX request:
$('input.del_btn').on('click', function() {
let id = $(this).data('id');
$.post('delete.php', { id: id })
.done(function () {
alert('Your picture has been deleted');
})
.fail(function () {
alert('failure');
});
});

get selected value from select and post to MySQL Table

I am fairly new at PHP HTML and found some help on this site but cannot get the code to work as part of my script
On clicking the SUBMIT button a record is posted to the database table (Transactions) but the FIELD (Code) is empty, it should contain a 3 letter uppercase string e.g. ABC
The ALERT shows that the value is stored in the variable $code but an empty string is posted to the table
Your help is greatly appreciated by this novice
<?php
// Include config file
require_once 'config.php';
// Define variables and initialize with empty values
$code = "";
$code_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Validate Code
$code = strtoupper($code);
// Check input errors before inserting in database
if(empty($code_err)){
// Prepare an insert statement
$sql = "INSERT INTO Transactions (Code)
VALUES (?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_code);
// Set parameters
$param_code = $code;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records created successfully. Redirect to landing page
$url = 'http://localhost:8888/portfolio/index.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<link href="style1.css" rel="stylesheet" type="text/css"/>
<style type="text/css">
.wrapper{
width: 450px;
margin: 0 auto;
}
</style>
<script>
function getValue(obj){
alert(obj.value);
$code=(obj.value);
**alert($code);**
}
</script>
<!--Display heading at top center of screen-->
<div>
<center><h3>Peter's Portfolio - Shares</h3></center>
</div> <!-- end of Div -->
</head>
<body style="background-color:#fcf8d9">
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<div class="page-header">
<h2>Create Transaction Record</h2>
</div>
<form class="form-horizontal" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<!-- ASX CODE -->
<div class="form-group">
<label for="name" class="control-label col-xs-6">ASX Code:</label>
<div class="col-xs-6">
<?php
$conn = new mysqli('localhost', 'root', 'root', 'Portfolio') or die ('Cannot connect to db');
$result = $conn->query("SELECT Code, Coy_Nm from Companies ORDER BY Code");
echo "<html>";
echo "<body>";
echo "<select Name='Code' ID='Code'onchange='getValue(this)'>";
while ($row = $result->fetch_assoc()) {
unset($Code, $Coy_Nm);
$Code = $row['Code'];
$Coy_Nm = $row['Coy_Nm'];
echo '<option value="'.$Code.'">'.$Coy_Nm.'</option>';
}
echo "</select>";
echo "<input type='hidden' value='submit'>";
//$code=$_POST['Code'];
//echo $code;
?>
</div>
</div>
<!--Submit and Cancel Buttons-->
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Javascript and PHP cannot simply communicate to each other live.
try this
function getValue(obj){
alert(obj);// check if obj has something in it before proceeding to "value"
alert(obj.value);
}
After require_once 'config.php',
Focus on the following line :
$code = "";
When you submit form and form action is self, this means that your post data will be sent to the same file and when the code is read from your file it makes $code empty every time. of course, an empty value will be sent to DB. move this line inside if condition or change this logic.

How to pass Variable One page to another in php

I have created dynamic button and i need to pass the button ID to another page when my button is clicked. I have pass it but it didn't work
Please give any solution
Here is my code for dash.php:
<?php
session_start();
function dash () {
include 'config.php';
$sql = "SELECT RoomNumber FROM roommaster ";
if ($result = mysqli_query($db, $sql)) {
$str = '';
while ($row = mysqli_fetch_array($result)) {
// generate array from comma delimited list.
$rooms = explode(',', $row['RoomNumber']);
//create the dynamic button and set the value.
foreach ($rooms as $v) {
$str .= "<a href = 'booking.php'?btn='btn'><input type='button' name='b1' id='btn' value='" . $v . "' /></a>";
}
}
return $str;
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
}
Here is my booking.php page:
<?php
if (isset($_POST['btn'])) {
$btn = $_POST['btn'];
echo $btn;
}
$sql = "SELECT RoomNumber FROM roommaster where RoomId=' " . $_GET['btn'] . " '";
if ($result = mysqli_query($db, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$RoomNumber = $row['RoomNumber'];
// $RoomType=$row['RoomType'];
// $Location=$row['Location'];
// $ChargesPerDay=$row['ChargesPerDay'];
}
// Free result set
mysqli_free_result($result);
} else {
echo "No records matching your query were found.";
}
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
?>
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Customer book Form</title>
<!-- Bootstrap -->
<link href="css/bootstrap1.min.css" rel="stylesheet">
<link href="css/book.css" rel="stylesheet">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</style>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-1.12.4.js"></script>
<script src="js/book1.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="head" id="link">
<div class="panel panel-primary" style="margin:20px;">
<div class="panel-heading">
<center><h3 class="panel-title"> Customer booking Form</h3></center>
</div>
<div class="panel-body">
<form method="post" action="">
<div class="col-md-12">
<div class="form-group col-md-12 ">
<label for="roomno">Room Number* </label>
<input type="text" class="form-control input-sm" name="RoomNumber" value="<?=$_GET['btn'];?>"required>
</div>
<div class="form-group col-md-6">
<label for="type">Room Type*</label>
<input type="text" class="form-control input-sm" name="RoomType" required >
</div>
<div class="form-group col-md-6">
<label for="location">Location*</label>
<input type="text" class="form-control input-sm" name="Location" required>
</div>
<div class="form-group col-md-12">
<label for="charges">Facilities*</label>
<input type="text" class="form-control input-sm" name="Facilities" required>
</div>
<div class="form-group col-md-12">
<label for="charges">ChargesPerDay*</label>
<input type="text" class="form-control input-sm" name="ChargesPerDay" required>
</div>
<div class="form-group col-md-4">
<label for="customer name">First Name*</label>
<input type="text" class="form-control input-sm" name="FirstName" required>
</div>
</div>
</form>
</div>
</body>
</html>
Try to use $_GET instead of $_POST
if (isset($_GET['btn'])) {
$btn = $_GET['btn'];
echo $btn;
}
Try linking using a form. BUTTONID should be the value to pass. $str should be:
<form action='booking.php' method='POST'>
<input type='hidden' value='BUTTONID' name='bttn'>
<input type='submit' value='".$v."'>
</form>
And then get the value of the hidden field as you already did...
$if (isset($_POST['bttn'])) {
$btn = $_POST['bttn'];
echo $btn;
}
i have modified script of dash.php and booking.php files. Please copy and paste this script.
dash.php file
<?php
session_start();
function dash(){
include 'config.php';
$sql = "SELECT RoomNumber FROM roommaster ";
if($result = mysqli_query($db, $sql))
{
$str = '';
while($row = mysqli_fetch_array($result))
{
// generate array from comma delimited list
$rooms = explode(',', $row['RoomNumber']);
//create the dynamic button and set the value
foreach ( $rooms as $v )
{
$str .= "<input type='button' name='b1' id='btn' value='".$v."' />";
}
}
return $str;
}
else {
echo "ERROR: Could not able to execute $sql. " .mysqli_error($db);
}
mysqli_close($db);
booking.php file
$sql = "SELECT RoomNumber FROM roommaster where RoomId=' " .$_GET['btn']." '";
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$RoomNumber=$row['RoomNumber'];
//$RoomType=$row['RoomType'];
// $Location=$row['Location'];
// $ChargesPerDay=$row['ChargesPerDay'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
To pass little data from one page to another page use parameters in the URL as below is parameter with the value you want to pass to next page as:
Click Button
Then on the anotherpage.php use $_GET to get the value passed by the URL as:
$val = isset($_GET['parameter']) ? $_GET['parameter'] : NULL;
Then use the $val for other processing. I think this may can help you to understand how to pass data from one page to another page simply.
Try to use $_REQUEST by that you can get both GET and POST values.In booking.php print the array like below:
print_r($_REQUEST);
if (isset($_REQUEST['btn'])) {
$btn = $_REQUEST['btn'];
echo $btn;
}

AJAX improvement for validation

SO i have this piece of AJAX that work as it should be but i want to add some validation to it.I dont want it to send empty information.The AJAX is done for a comment system.It takes the value from the form and then with php it inserts it to the databse. The Problem i am haveing is that it just insert empty comment to the database
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<script type="text/javascript">
function validateForm()
{
var comment = document.getElementsByName('comment').value;
if (comment == "" )
{
alert("Please fill in all the fields");
return false;
}
else
{
return true;
}
}
</script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" onsubmit="return validateForm();">
<label>New Comment</label>
<textarea name="comment" class="comment"> </textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
My AJAX code.I have tried to do some validation but it doesnt work properly and i dont know what is wrong with it.I am quite new to AJAX so not rlealy able to debug it myself.
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('.comment');
if (!comment.val()){
alert('You need to write a comment!');
}
else{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
});
});
My php code to insert into the database.
<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
session_start();
include('connection.php');
$connection = connectToMySQL();
$userId = $_SESSION['userID'];
$username = $_SESSION['username'];
$postId = $_POST['postid'];
$comment = $_POST['comment'];
$date_format = " Y-m-d g : i : s";
$time = date ($date_format);
$insertCommentQuery = "INSERT INTO `tblcomments`
(`Content`,`UserID`,`PostID`,`Timestamp`)
VALUES (
'$comment','$userId','$postId',
CURRENT_TIMESTAMP)";
$result = mysqli_query($connection,$insertCommentQuery);
$obj = array();
$obj['id'] = $postId;
$obj['html'] = '<div class="commentcontainer">
<div class="commentusername"><h1> Username :'.$username.'</h1></div>
<div class="commentcontent">'.$comment.'</div>
<div class="commenttimestamp">'.$time.'</div>
</div>';
echo json_encode($obj);
connectToMySQL(0);
endif?>
You never call the function validateForm()
And this part
if (!comment.val()){
alert('You need to write a comment!');
}
will always pass if there is a input field with the class comment, even if it's empty. You could do something like:
//send ajax request
if(validateForm()===false){
alert('You need to write a comment!');
return false;
}
else{
....
You could try to change the comment.val() to comment.text() since you are using a textarea and see if that solves your problem. The change is to be modified in your js code

can I get text from html and put it into variable in php without submitting a form?

I have a form in html:
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
and I want to get the value of this input in php without submitting it in a form.
this is my javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
pName= $(this).attr("name");
console.log(pName);
});
});
My php:
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
what I want is. you click on the picture,
1.the value of the name attribute of the picture is going to be saved into the variable pName (javascript),
2.it then goes into the form and changes the value of the form to the variable pName (javascript),
3.php picks up the value of the form (which should now be equal to pName),
4.then stores it into a variable $pName (php).
5.I also want $pName (php) to be globally used throughout all the pages of the website.
edit
this is my index page:
<?php
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
$query="SELECT * FROM project limit 5 ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="bgNav">
<div id="login">
Register
Log in
</div>
<nav id="nav">
Home
</nav>
</div>
<h2 class="titlePage">Home</h2>
<div id="bgTile">
<?php
while($row = mysqli_fetch_array($results))
{
$project = $row["name"];
echo nl2br("<a href='project.php'>" ."<img name=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>". "</a>");
}
?>
<div class="tile" id="tileM"><h2>Meer</h2></div>
</div>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
what I want: click on the image then you get sent to the project page where (php) $pName is equal to the value of (javascript) pName
project page:
<?php
$newRecord = null;
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
//insert into database
if(isset($_POST['insertComments'])){
include('connect-mysql.php');
$username = $_POST['username'];
$comment = $_POST['comment'];
$sqlinsert = "INSERT INTO user_comments (username, comment, project) VALUES ('$username', '$comment', '$pName')";
if (!mysqli_query($db_connection, $sqlinsert)){
die('error inserting new record');
}
else{
$newRecord = "1 record added";
}//end nested statement
}
//text from database
$query="SELECT * FROM user_comments where project = '$pName' ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
$query2="SELECT * FROM project where name = '$pName' ";
$results2 = mysqli_query($db_connection,$query2);
$intro2=mysqli_fetch_assoc($results2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="intro">
</div>
<div id="bgNav">
<nav id="nav">
Home
<a class="rightNav" href="register.php">Register</a>
<a class="rightNav" href="login.php">Log in</a>
</nav>
</div>
<div id="projectTile">
<span id="statusCheck"><?php print_r($intro2["status"]); ?></span>
<h2 id="prTitle"><?php print_r($intro2["name"]); ?></h2>
<div id="prPic"><img width="300" height="200" src="<?php print_r($intro2["image"]); ?>"></div>
<div id="prDescription"><?php print_r($intro2["description"]); ?></div>
</div>
<div id="comments">
<?php
while($row = mysqli_fetch_array($results))
{
echo nl2br("<div class='profile_comments'>" . $row['username'] . "</div>");
echo nl2br("<div class='comment_comments'>" . $row['comment'] . "</div>");
}
?>
</div>
<div id="uploadComments">
<form method="post" action="project.php">
<label for="name"><input type="hidden" name="insertComments" value="true"></label>
<fieldset>
<legend>comment</legend>
<label>Name:<input type="text" id="name" name="username" value=""></label><br/>
<label>Comments: <textarea name="comment" id="comment"></textarea></label>
<input type="submit" value="Submit" id="submitComment">
</fieldset>
</form>
</div>
<?php
echo $newRecord;
?>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
HTML:
do you have more then 1 image on page? its better if you add ID in image. No need for form and hidden fields for what you want done.
make sure your img has ID like <img id="imageID"...
JavaScript:
var pName= null;
$(document).ready(function(){
$('#imageID').click(function(){
pName= $(this).attr("name");
$.post("project.php", { pNameChange: pName },
function(data) {
// do something here.
});
});
});
above code should work as expected. Now in project.php > $_POST['pNameChange'] should receive the value of pName (image's name attr).
I don't understand what you want when you said $pName available globally on all pages. Please elaborate further, may be look into storing it as cookie/session?
EDIT:
Consider using session to pName value... by simple starting/resuming session in start of file:
<?PHP
session_start();
and then...
to set/update value:
if(isset($_POST["pNameChange"]))
$_SESSION["pName"] = $_POST["pNameChange"];
and then use $_SESSION["pName"] instead of $pName on all pages.
Try Ajax method in jQuery , hope it solves your problem
https://api.jquery.com/jQuery.ajax/
or
https://api.jquery.com/jQuery.post/
Actually, you do not need AJAX for this, all your index.php does it passes the image's name to project.php so try:
In index.php:
<form name='form1' method="post" action='project.php'> <!-- form attributes given -->
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
Javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
//onclick of image, we will save the image name into the hidden input
//and submit the form so that it goes to project.php
$('input[name="pNameChange"]').val($(this).attr("name"));
$('form1').submit()
});
});
And in your project.php:
//now project.php can get the posted value of 'pNameChange'
//There is no input field with `name`->`value`, so $_POST['value'] is invalid.
$pName = isset($_POST['pNameChange']) ? $_POST['pNameChange'] : '';
And if you need this value across multiple pages, global will not work, use sessions.
ok this "additional" answer is to focus on session only. use the codes for client-end from my previous answer and try this on server-end.
index.php Page:
<?php
session_start();
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : '';
project.php Page:
<?php
session_start();
$newRecord = null;
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : null;
if(is_null($pName) && isset($_POST['pNameChange'])) {
$_SESSION['pNameChange'] = $_POST['pNameChange'];
$pName = $_POST['pNameChange'];
}
hope it helps

Categories

Resources