how do I display different content from database on one php file? - javascript

I am trying to use one php file php.project and depending on the name of 1 variable I get all the data from the database that is needed and display it on the site. Right now I have one problem.
I have one php file that is this:
<?php
$pName = $_POST['name'];
$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="libs/ppo.js"></script>
<link rel="stylesheet" href="libs/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>
</body>
</html>
depending on the variable $pName the content of the site changes, because it gets its content from a database and $pName stands for "project name".
$pName is determenent by the name of the picture you click on the index page which is this:
<?php
$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="libs/ppo.js"></script>
<link rel="stylesheet" href="libs/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("<img id=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>");
}
?>
<div class="tile" id="tileM"><h2>Meer</h2></div>
</div>
<form action="project.php" method="post" id="formF">
<label><input id="inputF" type="hidden" name="name"></label><br>
<input type="submit">
</form>
</body>
</html>
by clicking the image I put the name of it in a form and submit it to project.php. in project. php it is stored in the variable $pName . The problem is that once I refresh the page the $pName becomes Null and you see none of the database's data on the page. my question is: how can change this code in a way that $pName doesn't become Null when I refresh the page? and are there any suggestions on how to improve this code?
this is my javascript:
var check = null;
var form = $('#myForm');
$(document).ready(function(){
$('img').click(function(){
$('#inputF').val(this.id);
$("input[type=submit]").trigger("click");
});
});

Add Sessions to you code (as requested by #aleation).
Also, using parameters directly to query your database is very dangerous (as #jeroen mentioned).
Read up on the topic of SQL Injections and try to evaluate $pName before using it in a query.
<?php
session_start();
if(!is_null($_POST['name']))
{
$pName = $_POST['name'];
$_SESSION['pName'] = $pName;
}
elseif (array_key_exists('pName',$_SESSION)) {
$pName = $_SESSION['pName'];
}
else {
$pName = ''; // Maybe set a default here?
}
$pName = $_POST['name'];
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
...
Tiny glimpse into the Problem SQL Injections bring: In your example, imagine someone send's a POST request where name is ';Delete FROM project where id <>.
This would result in you loosing all your entries in the project table.
And that Query injection wouldn't even be that hard to guess.
With analyzing your website, someone could get hold of userdata, manipulate userdata, insert userdata ... you see? It is a mess.

Why are you using a $_POST variable for selecting the right content? If you make your images hyperlinks with the project name in the address, you can refresh the page without losing the variable content.
change:
echo nl2br("<img id=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>");
into
echo nl2br("<img id=\"$project\" width='100px' alt='Project name' height='100px' class='tile' src=".$row['image']."/>");
and then get $pname = $_GET['name'] instead of $pname = $_POST['name']

Related

Locate the reasoning for NULL values between HTML and PHP

I am trying to figure out why the resulting values are...
NULL NULL string(4) "PEAR"
..on the page they are displayed on.
Originally I do not want them to be displayed but I want the php code to run, using local storage data, when the page loads, then possibly return a boolean value or something in that direction. With a set goal in mind, I am looking for the mistake I have made that creates the NULL values. I have the following code:
validateSession.php , php functionality that will validate values from localstorage and database
<?php
include("config.php");
include("refc/refcvalidation.php");
$sesuserid = $_POST[$valuserid];
$sessionid = $_POST[$valsesid];
var_dump($sesuserid, $sessionid);
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
$stmt = $conn->prepare("SELECT * FROM sessiontable WHERE sesowner=? AND sescode=?");
$stmt->bind_param("is", $sesuserid, $sessionid);
$stmt->execute();
$result = $stmt->get_result();
$conn->close();
if ($result->num_rows > 0) {
var_dump("APPLES");
}else{
var_dump("PEAR");
}
?>
refcvalidation.php , reference coordination, ensuring same value on both pages
<?php
$valuserid = "VALSES1";
$valsesid = "VALSES2";
?>
homepage.php , basic page with contents
<?php
include("services/refc/refcvalidation.php");
include('services/validateSession.php');
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="general/styling.css">
<script src="general/launch.js"></script>
</head>
<body>
<div id="topBox">
</div>
<div class="box">
<form id="logForm" action="validateSession.php" method="post">
<input type="hidden" required="required" name="<?php echo $valuserid ?>" id="userfield">
<input type="hidden" required="required" name="<?php echo $valsesid ?>" id="sesidfield">
</form>
</div>
</body>
<style>
</style>
</html>
<script>
document.getElementById("userfield").value = localStorage.getItem("userid");
document.getElementById("sesidfield").value = localStorage.getItem("sessionid");
</script>
The values within HTML are set and have a value in the script section, they are null within the PHP $_POST[$valuserid]; and $_POST[$valsesid]; . Any ideas?
Have'nt tested this, but it might give you some ideas to a solution.
Maybe we could impolement some Ajax into this?
What is Ajax?
AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Ajax can give data as response.
refcvalidation.php
This should be removed
validateSession.php
<?php
include("config.php");
//include("refc/refcvalidation.php"); //REMOVED
$sesuserid = $_POST['valuserid'];
$sessionid = $_POST['valsesid'];
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
$stmt = $conn->prepare("SELECT * FROM sessiontable WHERE sesowner=? AND sescode=?");
$stmt->bind_param("is", $sesuserid, $sessionid);
$stmt->execute();
$result = $stmt->get_result();
$conn->close();
if ($result->num_rows > 0) {
$myObj->sesuserid = $sesuserid;
$myObj->sessionid = $sessionid;
$myJSON = json_encode($myObj);
echo $myJSON;
return true; //CONTAINS SOMETHING
}else{
return false; //CONTAINS NOTHING
}
?>
homepage.php
<?php
include("services/refc/refcvalidation.php");
include('services/validateSession.php');
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="general/styling.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="general/launch.js"></script>
</head>
<body>
<div id="topBox">
</div>
<div class="box">
<form id="logForm" action="validateSession.php" method="post">
<input type="hidden" required="required" name="<?php echo $valuserid ?>" id="userfield">
<input type="hidden" required="required" name="<?php echo $valsesid ?>" id="sesidfield">
</form>
</div>
</body>
<style>
</style>
</html>
<script>
$.ajax({
url: 'validateSession.php',
method: 'POST',
data: { valuserid: '<?php echo $valsesid ?>', valsesid: '<?php echo $valsesid ?>'},
success: function(data) {
var data_json= JSON.parse(data);
console.log(data_sjon);
localStorage.userid = data_json[0];
localStorage.sesidfield = data_json[1];
document.getElementById("userfield").value = localStorage.getItem("userid");
document.getElementById("sesidfield").value = localStorage.getItem("sessionid");
}
})
</script>

How to change Login to Logout button on wordpress using $_SESSION?

So I have a custom Login page on Wordpress that connects to my users database and checks if all the information is correct. This is the login.php:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['email'])){
// removes backslashes
$email = stripslashes($_REQUEST['email']);
//escapes special characters in a string
$email = mysqli_real_escape_string($conn,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($conn,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE email='$email'
and password='".md5($password)."'";
$result = mysqli_query($conn,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $email;
// Redirect user to index.php
header("Location: index.php");
}else{
echo "<div class='form'>
<h3>Email/password is incorrect.</h3>
<br/>Click here to <a href='../login/'>Login</a></div>";
}
}else{
?>
<div class="form">
<!-- <h1>Log In</h1> -->
<form action="" method="post" name="login">
<input type="text" name="email" placeholder="Email" required />
<input type="password" name="password" placeholder="Password" required />
<br>
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='../register/'>Register Here</a></p>
</div>
<?php } ?>
</body>
</html>
What I want to do is change the LOGIN button on my Wordpress header to LOGOUT (and showing the user information if it's possible) after the user is logged, and I suppose that I can do that using the $_SESSION['email'] = $email;variable.
How can I do that?
Thanks a lot!
You can use the built-in WordPress function is_user_logged_in() or is your login using also a custom table in the database and not the WordPress user table wp_user?
<?php
if ( is_user_logged_in() ) {
echo 'Login out';
} else {
echo 'Login';
}
?>
If your login system is independent of WordPress, you need to check your login function and see what session variables it creates, you might also need to start the session your self then if it is not in the function something like this then
session_start();
if (isset($_SESSION['email'])) {
/// your login button code here
} else {
/// your logout button code here
}
A function that would add it to your wordpress menu you need to style it:
add_filter('wp_nav_menu_items', 'button_login_logout', 10, 2);
function button_login_logout() {
ob_start();
if (isset($_SESSION['email'])) :
?>
<a role="button" href="logoutlink">Log Out</a>.
<?php
else :
?>
<a role="button" href="loginlink">Log In</a>
<?php
endif;
return ob_get_clean();
}

I'm trying to create a live search bar on my webpage but can't seem to make it work. It just doesn't display any data

The template.php file contains all the coding related to the script.
<?php
include 'dbh.php';
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $title; ?></title>
<link rel ='Stylesheet' type ='text/css' href ='Styles/StyleSheet.css'/>
</head>
<body>
<div id="banner">
</div>
<form action="">
<input type ="text" id="search">
</form>
<div id="result">
</div>
<div id="content_area">
<?php echo $content; ?>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#search').keyup(function()
{
var search = $('#search').val();
if($.trim(search.length)==0)
{
$('#result').html('Please enter correct data');
}
else
{
$.ajax({
type:'POST',
url:'Search.php',
data:{'search':search},
success:function(data)
{
$('#result').html(data);
}
});
}
})
})
</script>
</body>
</html>
The Search.php file contains the code related to query of data. My database has only one table named CINFO and has only one column named Title.
<?php
include 'dbh.php';
if(isset($_POST['search']))
{
$search = $_POST['search'];
$query = $db->prepare("SELECT * from CINFO where TITLE LIKE ?");
$query->execute(["%$search%"]);
$count = $query->rowCount();
if($count==0)
{
echo "Sorry No result found";
}
else
{
while($r = $query->fetch(PDO::FETCH_OBJ))
{
$name = $r->Title;
echo "$name";
}
}
}
?>
dbh.php has code related to the connection of the database-
<?php
$server = "localhost";
$username = "root";
$password = "root";
$dbname = "ComicDB";
$conn = mysqli_connect($server, $username, $password,$dbname);
?>
Whenever I enter any data in the search box, all it doesn't display any data but when I press backspace and delete what I've entered it does display 'Please enter correct data' which means the if block in template.php is getting executed but not the else block. Thats what I've understood out of the code. Can't seem to figure out what I've done wrong.

Updating database value with button

<?php
include ('session.php');
$connection = mysqli_connect("localhost", "root", "" , "log_database");
$question_id = rand(1,2);
$query = "SELECT * FROM questions WHERE id='$question_id' ";
$query_run = mysqli_query($connection,$query);
$query_row = mysqli_num_rows($query_run);
if ($query_row==1) {
foreach ($query_run as $row ) {
$option1 = $row['option1'];
$option2 = $row['option2'];
$money = $row['money'];
$option1_clicked = $row['option1_clicked'];
$option2_clicked = $row['option1_clicked'];
$id_question = $row['id'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Game</title>
<link rel="stylesheet" type="text/css" href="game.css"> </head>
<body>
<div id="content_div">
<img id="title_img" src="wealthypinguin.png">
</div>
<div id="question_div">
<span id="question">
<?php echo $username; ?>, <br> for <span id="money">€ <?php echo $money; ?></span>,
<br>would you rather...</span>
</div>
<div id="buttons_div">
<button onclick="addOption1()" id="button1">
<?php echo $option1; ?>
</button>
<br>
<button onclick="addOption2()" id="button2">
<?php echo $option2; ?>
</button>
<br>
<button id="button3">
Keep your money
</button>
</div>
</body>
<script>
function addOption1() {
<?php
$option1_clicked = $option1_clicked + 1;
$queryOption1 = "UPDATE `questions` SET `option1_clicked` = '$option1_clicked' WHERE id='$question_id'";
$query_run_option1 = mysqli_query($connection,$queryOption1);
?>
}
function addOption2() {
<?php
$option2_clicked = $option2_clicked + 1;
$queryOption2 = "UPDATE `questions` SET `option2_clicked` = '$option2_clicked' WHERE id='$question_id'";
$query_run_option2 = mysqli_query($connection,$queryOption2);
?>
}
</script>
</html>
What I want to achieve that when my button1 is clicked, my php variable $option1_clicked is raised by one and the new value is updated in my database.
When I click button2 the same result.
The problem is when I click one of them, the value is updated but it automatically updates both values($option1_clicked, $option2_clicked) to the same value.
So when option1_clicked goes from 6 to 7, option2_clicked gets also the value 7.
Ajax is the best way to do that.
Have a look to that:
https://www.w3schools.com/xml/ajax_intro.asp
You will be able to send a POST or GET query to a file (often a PHP file) without leave the current web page.
It's very useful, very plaisant for the users (You can create good and fluid User Interfaces), and quite simple.

Ajax Pagination Script Send Variable to php Script

//index.php
<?php
include("config.inc.php");
if(!empty($_GET['email'])){
$dude = $_GET['email']; // user email address to be gotten by javascript variable
// dude and sent to fetch_pages.php
echo '<input type="text" style="display:none" id="hide" value="'. $dude .'" />';
}
$results = mysqli_query($connecDB,"SELECT COUNT(*) FROM user_registration_details");
$get_total_rows = mysqli_fetch_array($results); //total records
$item_per_page = 5;
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i< $pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?>
<?php
/*
* Ajax form submit
*/
# request sent using HTTP_X_REQUESTED_WITH
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['name']) AND isset($_POST['email']) AND isset($_POST['subject']) AND isset($_POST['message'])) {
$to = 'your#mail.id';
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$sent = email($to, $email, $name, $subject, $message);
if ($sent) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
/**
* email function
*
* #return bool | void
**/
function email($to, $from_mail, $from_name, $subject, $message){
$header = array();
$header[] = "MIME-Version: 1.0";
$header[] = "From: {$from_name}<{$from_mail}>";
/* Set message content type HTML*/
$header[] = "Content-type:text/html; charset=iso-8859-1";
$header[] = "Content-Transfer-Encoding: 7bit";
if( mail($to, $subject, $message, implode("\r\n", $header)) ) return true;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Pagination</title>
<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var dude = document.getElementById("hide").value;//variable to be sent to fetch_pages //to present user email
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="profiler.js"></script>
<style type="text/css">
#import url("style2.css");
</style>
<link href="style5.css" rel="stylesheet" type="text/css">
</head>
<body onload="profiler();">
<div id="firstdiv">
<p></p>
<img id="image1" src="2347033609685.jpg" alt="Profile Pic" height="170" width="180" />
<table id="pname"><tr height="49"><td id="name">Richard Berry</td></tr>
<tr id="num"><td>08023818955</td><td width="400">Agent with homes and good event centres</td></tr>
<tr height="20"><td width="200">Specialties: Event Centres / Venue</td>
</tr></table>
<table id="like"><tr><td width="6"></td><td width="31"><img src="2347033609685.jpg" height="27" width="27" /></td>
<td width="71"><img src="yahoo2.PNG" height="27" width="27" /></td></tr>
</table>
<table id="pdetails"><tr><td width="200"><p id="over" onclick="profilerr('pover');" ><button id="o">Overview</button></p></td>
<td width="220"><p id="list" onclick="profile('plist');"><button id="l">Listings()</button></p></td>
<td width="221"><p id="about" onclick="profiles('pabout');"><button id="a">About</button></p></td>
</tr></table>
<div id="pabout" style="display:none">
<table>
<tr><td id="name">About Richard Berry</td></tr>
<tr><td>Firstly, there are two sets of people who come to this hall. The first set are those who just come to watch and/or charge gadgets and the second set are those who come to train.
To the first set of people, we plead that you kindly stay in the waiting area when you visit the hall and far from tables especially when people are playing because most times it serves as a means of distraction and also playing on table is prohibited.
Secondly, to the second set of people who are registered members of the team we are pleading that you should always be in complete sport outfit whenever you come for training and should avoid littering of the hall with nylons, papers, bottles e.t.c
Most especially the new training timetable for the semester is below:</td></tr>
</table></div>
<div id="pover" style="display:none">
<table>
<tr><td id="name">About Richard Berry</td></tr>
<tr><td>Firstly, there are two sets of people who come to this hall. The first set are those who just come to watch and/or charge gadgets and the second set are those who come to train.
To the first set of people, we plead that you kindly stay in the waiting area when you visit the hall and far from tables especially when people are playing because most times it serves as a means of distraction and also playing on table is prohibited.
Secondly, to the second set of people who are registered members of the team we are pleading that you should always be in complete sport outfit whenever you come for training and should avoid littering of the hall with nylons, papers, bottles e.t.c
Most especially the new training timetable for the semester is below:</td></tr>
<tr><td id="listl">Listings (2401) by Richard Berry</td></tr>
</table></div>
<div id="plist" style="display:none">
<table>
<tr><td id="listl">Listings(2401) by Richard Berry</td></tr>
<tr></tr></table>
<div id="results"></div>
<?php echo $pagination; ?>
</div>
</div>
<div id="wrap">
<p id="compdiv">Contact Supplier</p>
<div class="alert">Hello</div>
<form id="form" action="" method="post">
<div>
<label>
<span id="spandisp">Name: * </span>
<input placeholder="Name" type="text" id="input" name="name" required>
</label>
</div>
<div>
<label>
<span id="spandisp">Email: * </span>
<input placeholder="Email address" id="input" type="email" name="email" required>
</label>
</div>
<div>
<label>
<span id="spandisp">Subject: * </span>
<input placeholder="Subject" id="input" type="text" name="subject" required>
</label>
</div>
<div>
<label>
<span id="spandisp">Message: *</span>
<textarea id="input2" placeholder="Type your message here...." name="message" required></textarea>
</label>
</div>
<div>
<button name="submit" type="submit" id="submit">Send Message</button>
</div>
</form>
<p>Note: * Fields are required</p>
</div>
</div>
</body>
</html>
//config.inc.php
<?php
$db_username = 'root';
$db_password = '****';
$db_name = '****';
$db_host = 'localhost';
$item_per_page = 5;
$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name) or
die('could not connect to database');
?>
//fetch_pages
<?php
include("config.inc.php"); //include config file
$item_per_page = 5;
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!empty($_POST['email'])){
$email = $_POST['email'];
echo "gotcha";
}
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($connecDB,"SELECT * FROM user_registration_details WHERE email = '$email' ORDER BY id ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '<li id="item_'.$row["id"].'">'.$row["id"].'. <span class="page_name">'.$row["contact_name"].'</span><span class="page_message">'.$row["email"].'</span><span class="view"> View Details</span></li>';
}
echo '</ul>';
?>
Please the code above is getting the user email from the URL and also successfully inputting it into the JavaScript variable dude. Also all the AJAX pagination script is working perfectly as I want it just that I can't send the user email to fetch_pages.php to be able to restrict the search based a particular user email. please how can I send the user email details to fetch_pages without refreshing the page and not still disturbing the pagination script. please all help will be needed as I need the script for a major project.
i came to understand that the only problem was to add dude to the javascript code as below.
the same webpage cannot send two ajax request to the same php at the same time.
$("#results").load("fetch_pages.php", {'page':0, 'email':(dude)}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1),'email':(dude)}, function(){
});

Categories