//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(){
});
Related
I'm trying to pass data via post with ajax to my sendjs.php.
jsonObj is not being passed in IE11 only (havent tested lower versions of IE but it works in Edge and all other browsers). FormData and captchaResponse are being passed though.
In 'Network' in IE 11 inspector the post data is:
cart: [null] and there are no errors displayed in console.
All other browsers it contains the data:
eg. cart: {name: "130 Litre Polypropylene Soakwells", price: "$39.95", quantity: "4", total: "$159.80"},…]
Live site here: www.diysoakwells.com.au (you can add an item and checkout to test).
Have spent ages trying to find the cause and now I'm not even sure where to go from here to be honest, so any information would be appreciated and I will update the post with any info as requested.
app.js
$(function() {
// Get the form.
var form = $("#ajax-contact");
// Get the messages div.
var formMessages = $("#form-messages");
var spinner = $("#spinner");
var submit = $("#submit");
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
//display the cog animation
$(spinner).removeClass("hidden");
//hide the submit button
$(submit).addClass("hidden");
var jsonObj=[];
for(i=1;i<$(".item-price").length;i++)
{
var items={};
var itemname = $(".item-name").get(i);
var itemprice = $(".item-price").get(i);
var itemquantity = $(".item-quantity").get(i);
var itemtotal = $(".item-total").get(i);
items["name"] = itemname.innerHTML;
items["price"] = itemprice.innerHTML;
items["quantity"] = itemquantity.innerHTML;
items["total"] = itemtotal.innerHTML;
jsonObj.push(items);
}
console.log(jsonObj );
var formdata = {};
formdata["textbox"] = $("#textbox").val();
formdata["name"] = $("#name").val();
formdata["phone"] = $("#phone").val();
formdata["email"] = $("#email").val();
formdata["address"] = $("#address").val();
formdata["grandtotal"] = simpleCart.grandTotal();
var x =
{
"cart" : jsonObj,
"formdata" : formdata,
"captchaResponse" : $("#g-recaptcha-response").val()
};
//jsonString = jsonObj+formdata;
var y = JSON.stringify(x);
console.log(y);
var result = jQuery.parseJSON(y);
console.log(result);
// Serialize the form data.
//var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: "post",
url: "sendjs.php" ,
//url: $(form).attr("action"),
data: y,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (response) {
if(response=="Thank You. Your order has been sent and a copy mailed to your inbox.")
{
//remove the button animation
$(spinner).addClass("hidden");
$(formMessages).removeClass("error");
$(formMessages).addClass("success");
$("#textbox").val("");
$("#name").val("");
$("#email").val("");
$("#message").val("");
$("#phone").val("");
$("#address").val("");
}
else
{
$(formMessages).removeClass("success");
$(formMessages).addClass("error");
$(spinner).addClass("hidden");
$(submit).removeClass("hidden");
}
$(formMessages).text(response);
}
});
});
});
sendjs.php
<?php
//Debugging
//ini_set( 'display_errors', 1 );
//error_reporting( E_ALL );
//replaces file_get_contents due to restrictions on server
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//turn url_fopen on due to restrictions on server
//ini_set('allow_url_fopen', true);
date_default_timezone_set('Australia/Perth');
$time = date ("h:i A");
$date = date ("l, F jS, Y");
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$captcha = $obj["captchaResponse"];
$captcha;
$secretKey = "scrubbed";
$ip = $_SERVER['REMOTE_ADDR'];
$response = get_data("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
//not used due to server restictions
//$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo "Please Click on the Captcha";
return false;
}
else
{
//echo $items;
$name = $obj["formdata"]["name"];
$phone = $obj["formdata"]["phone"];
$email = $obj["formdata"]["email"];
$textbox = $obj["formdata"]["textbox"];
$address = $obj["formdata"]["address"];
$grandtotal = $obj["formdata"]["grandtotal"];
$text = "<html style='font-family:arial'>
<body>
<h1 style='color:crimson;'>DIY Soakwells</h1>
<p>This order was submitted from www.diysoakwells.com.au on $date at $time</p>
<p>$name thank you for your order inquiry. Deliveries are normally every Friday, we will be in contact shortly to discuss your order and confirm a time.</p>
<p>An invoice will be issued after delivery for payment via bank transfer.</p>
<p>In the meantime if you haven't already seen it, you can take a look at www.soakwellcalculator.com.au to confirm the number of soakwells you ordered will be adequate.</p>
<br>
<h2 style='color:crimson;'>CUSTOMER DETAILS</h2>
<p><b>Email:</b>\n$email</p>
<p><b>Name:</b>\n$name</p>
<p><b>Phone:</b>\n$phone</p>
<p><b>Delivery Address:</b>\n$address</p>
<p><b>Message:</b>\n$textbox</p>
<br>
<h2 style='color:crimson;'>ORDER DETAILS</h2>";
$items_in_cart = count($obj["cart"]);
for($i=0; $i < $items_in_cart; $i++) {
$iname = $obj["cart"][$i]["name"];
$price = $obj["cart"][$i]["price"];
$quantity = $obj["cart"][$i]["quantity"];
$total = $obj["cart"][$i]["total"];
//display looped cart data
$items .= "<p>$iname x $quantity - $price <small>ea.</small> <b>Sub Total: </b> $total .</p>";
}
$final_total ="<br>
<p><b>Total: </b>$$grandtotal <small>inc. GST</small></p>
</body>
</html>";
//Email Content
$body = $text.$items.$final_total;
// Set the email subject.
$subject = "New order from $name";
// Build the email content.
$email_content = $body;
// Build the email headers.
$email_headers = 'MIME-Version: 1.0' . PHP_EOL;
$email_headers .= 'Content-Type: text/html; charset=ISO-8859-1' . PHP_EOL;
//$email_headers .= 'To:' . $name . '<' . $email . '>' . PHP_EOL;
$email_headers .= 'From: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'CC: orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'Reply-To: DIY Soakwells <orders#diysoakwells.com.au>' . PHP_EOL;
$email_headers .= 'Return-Path: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'X-Sender: DIY Soakwells <orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
//$email_headers .= 'X-Priority: 1' . PHP_EOL;
//validate Email
$email_check = filter_input(INPUT_POST, $email, FILTER_VALIDATE_EMAIL);
//Recipients
$to = $email;
if (mail($to, $subject, $email_content, $email_headers, '-forders#diysoakwells.com.au')) {
// Set a 200 (okay) response code.
//http_response_code(200);
echo "Thank You. Your order has been sent and a copy mailed to your inbox.";
} else {
// Set a 500 (internal server error) response code.
//http_response_code(500);
echo "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.";
}
}
?>
Hope someone can give me some tips.
Edit: Added cart modal html
<!-- cart modal panel -->
<section class="modal fade cartModal" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<!-- Modal Header-->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title cart_summary">
<b>Cart Summary</b>
</h3>
</div>
<!-- Cart Modal Body -->
<section class="modal-body">
<div class="checkout">
<!-- Cart Items -->
<div class="simpleCart_items"></div>
<!-- Cart Items Footer -->
<div class="panel-footer">
<div class="row">
<div class="col-xs-12 col-sm-4 cart_modal_btn">
<a class="btn btn-default btn-sm" onclick="simpleCart.empty();">Clear Cart</a>
</div>
<div class="col-xs-12 col-sm-8 cart_footer_text">
<span class="total">Current Total:
<b class="simpleCart_grandTotal"></b>
<small class=gst>Inc. GST</small>
</span>
</div>
</div>
</div>
</div>
<div>
<h3 class="cart_summary">
<b>Checkout</b>
</h3>
</div>
<!-- Customer Details Form -->
<section class="details_form">
<b class="invoice_info">Due to the custom nature of this service we do not take payment until your order is confirmed and the materials are delivered.</b>
<b class="invoice_info">You will be emailed an invoice with our account details. Payment terms are 5 days from the invoice date please.</b>
<p class="invoice_info">For payment we accept bank transfer and VISA / Master Card <small>(2.3% surcharge for credit cards).</small></p>
<form id="ajax-contact" class="contact_form" method="post">
<fieldset>
<h4 class="contact_form_title">Questions / Additional Information</h4>
<div class="textbox_container">
<textarea rows="5" style="overflow-y:hidden" class="textbox" name="textbox" id="textbox"></textarea>
</div>
<h4 class="contact_form_title">Customer Details</h4>
<table>
<tr>
<th><label for="name" class="cart_label">Enter Name</label></th>
<td><input type="text" name="name" placeholder="Name Required" class="input" id="name" required /></td>
</tr>
<tr>
<th><label for="phone" class="cart_label">Enter Phone Number</label></th>
<td><input type="tel" placeholder="Phone Number Required" name="phone" class="input" id="phone" required/></td>
</tr>
<tr>
<th><label for="emaile" class="cart_label">Enter Email</label></th>
<td><input type="email" placeholder="Email Required" name="emaile" class="input" id="emaile" required/></td>
</tr>
<tr>
<th><label for="address" class="cart_label">Enter Address</label></th>
<td><input type="text" name="address" placeholder="Address / Suburb" class="input" id="address" required/></td>
</tr>
</table>
</fieldset>
<!-- captcha -->
<div class="captcha_container">
<div class="g-recaptcha" data-sitekey="6LfPjyMTAAAAANe_qucSV5ZFAuDNO4Ud524-NGoa" data-size="compact"></div>
</div>
<section class="fb_container">
<div class="fb-like" data-href="http://www.facebook.com/DiySoakwells" data-layout="button_count" data-width="225" data-action="like" data-show-faces="false" data-share="true"></div>
</section>
<br/><!-- css this -->
<fieldset class="submit">
<div class="formMessages submit_field"></div>
<div id="spinner" class="hidden success submit_field"><i class="loader2"></i></div>
<input id="submit" type="submit" name="Submit" value="Send" style="cursor:pointer" class="success"/>
</fieldset>
</form>
</section>
</section>
<!-- Modal Footer-->
<section class="modal-footer">
<button type="button" class="btn btn-default close" aria-label="Close" data-dismiss="modal">Back to Shop</button>
</section>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</section><!-- /.main section -->
Simple Cart config
simpleCart({
//Setting the Cart Columns for the sidebar cart display.
cartColumns: [
//{ attr: "image", label: false, view: "image"},
//Name of the item
{ attr: "name" , label: "Item" },
//Quantity displayed as an input
{ attr: "quantity", label: "Qty", view: "input"},
//Price of item
//{ attr: "price", label: "Price", view: "currency"},
//Subtotal of that row (quantity of that item * the price)
{ attr: "total" , label: "SubTot", view: "currency" }
],
cartStyle: "table" ,
checkout: {
type: "SendForm" ,
url: "/php/sendjs.php" ,
method: "POST" ,
}
});
simpleCart.bind( 'beforeCheckout' , function( data ){
data.name = document.getElementById("name").value;
data.textbox = document.getElementById("textbox").value;
data.emaile = document.getElementById("emaile").value;
data.phone = document.getElementById("phone").value;
data.address = document.getElementById("address").value;
});
Codepen link to simplecart.js
Copy of simplecart.js
UPDATE 2
Your code here uses items, not item, and that works fine for me. I checked your live site, which uses item, and found that code does not work, it exhibits the problem you describe. I copied that live, broken code locally and was able to fix the problem as described below.
UPDATE
I stumbled on the solution (described below), without understanding it. After more research, I've now found the cause of the problem: item is defined as a native function in IE.
Related question 1
Related Question 2
Related Question 3
How I stumbled onto the answer
I copied your code locally and played around with it. I noticed jsonObj was created OK, though the contents looked strange. Likewise x was created OK, but after JSON.stringify your cart contents were lost.
console.dir(jsonObj) showed that it was an array of objects, but each object showed up as a function called item - in IE11 only:
In Chrome it is an array of plain objects.
The name of that function (item) seems strange, considering it is the name of the object you are storing your cart items in. And JSON.stringify on a function will return null - so that could explain it.
Checking your code again I notice you did not declare item anywhere. I tried just adding:
var item;
outside your for (i=1...) loop, and this solved it for me! Cart contents are not lost by JSON.stringify, and devtools shows the cart and your other data is POSTed successfully.
Maybe item declared somewhere else (in SimpleCart?) as a function, and that's getting in the way? UPDATE Yes this is exactly what is happening, though it is declared by the browser itself, not in any JS.
so I'm making a pagination which uses 3 different files. The page itself (index.php), the header which contains a JS Ajax scripts for changing page which is included in the index.php (header.php) and a pagination script contained in a separate PHP file which is called via the AJAX script (pagination.php).
In the index.php I have a variable which defines the category the user is currently in named $category, I would like this variable to be used in the pagination.php to select what results are shown (Only results where subcategory2 = $category).
Because pagination.php is called through an ajax script on document ready it can't see that variable. Is there any way for the two to communicate without the use of Session (which would mess up when changing to other categories) or include (which would end up calling the script twice).
Header.php:
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("/includes/pagination.php");
$(".pagination").bootpag({
total: <?php echo $pages; ?>,
page: 1,
maxVisible: 5
}).on("page", function(e, num){
e.preventDefault();
$("#results").prepend('<div class="loading-indication"><img src="/images/ajax-loader.gif" style="width: 2em; margin: 0 auto;" /><br />Loading...</div>');
$("#results").load("/includes/pagination.php", {'page':num});
});
});
</script>
Pagination.php
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
//sanitize post value
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
$page_number = 1;
}
echo $category;
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($mysqli, "SELECT ProductID, SupplierID, ProductName, ProductDesc, ProductURL, Image1URL, Image2URL, Image3URL, Image4URL, Image5URL, ProductCondition, Stock, AvailabilityDate, ProductGTIN, ProductMPN, ProductBrand, ProductGroupID, ProductColour, ProductGender, ProductAgeGroup, ProductMaterials, ProductSize, ProductPSize, Feature1, Feature2, Feature3, Feature4, Feature5, Feature6, Feature7, Feature8, Feature9, Feature10, CostPrice, Markup, Offer, Shipping, ShippingWeight, ShippingLabel FROM products ORDER BY productid ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '
<table id="productbox">
<tr>
<th class="producthead" colspan="3">'.$row["ProductName"].'</th>
</tr>
<tr>
<td class="productimgcell"><img src="'.$row["Image1URL"].'" class="productimg" /></td>
<td class="productinfo">'.$row["Feature1"].'<br />'.$row["Feature2"].'<br />'.$row["Feature3"].'</td>
<td class="productprice"><div class="pricebg">'; echo price_calc($mysqli, $row["ProductID"], $row["CostPrice"], $row["Markup"], $row["Offer"]); echo '<span class="priceinfo">inc. VAT</a></div><div style="clear:both;"></div><div class="addtocartbg">Add To Cart</div></td>
</tr>
<tr>
<td class="productfoot" colspan="3">5/5 Stars - Write A Review</td>
</tr>
</table><br />
';
}
echo '</ul>';
?>
Index.php
<?php
$category = 'AMD';
global $category;
$page_title = 'AMD Motherboards - Motherboards - PC Components';
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
$results = mysqli_query($mysqli,"SELECT COUNT(*) FROM products WHERE SubCategory2 = '$category'");
$get_total_rows = mysqli_fetch_array($results);
$pages = ceil($get_total_rows[0]/$item_per_page);
include_once($_SERVER['DOCUMENT_ROOT'].'/template/header.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/template/sidemenu.php');
?>
<div class="contentboxcontainer">
<div class="centercontentbox">
<div class="halfcontentboxcontainer">
<div class="halfcontentbox">
<div class="contenthead">Deals</div>
<div class="content">
<div class="contentcontainer">
Test
</div>
</div>
</div>
</div>
<div class="halfimgcontentboxl">
<img src="https://assets.vg247.com/current//2015/07/battlefront_leaked_alpha_tatooine_4.jpg" style="border-radius: 5px; width: 100%;" />
</div>
</div>
</div>
<div class="contentboxcontainer">
<div id="contentbox">
<div class="contenthead">Products</div>
<div class="content">
<div id="results"></div>
<div class="pageswrap"><div class="pagination"></div> <div style="clear:both;"></div></div>
</div>
</div>
</div>
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/template/footer.php');
?>
Send the category id as a post variable in the load command.
var cat = <?php echo $category; ?>
$("#results").load("/includes/pagination.php", {'page':num , 'category':cat});
For anyone else interested in an answer for this, I'm going to post my work around just in case anyone might find it useful.
In my pagination.php I added a check for the current page the user is on and compared that to a url I define. If the user is on said page then I define the category there.
pagination.php
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
if ($_SERVER['HTTP_REFERER'] == $domainurl.'/store/pc-components/motherboards/amd/') {
$category = 'AMD';
}
I had to use $_SERVER['HTTP_REFERER'] due to it being called from JS and $domainurl is defined in my config file (which is included in db_connect.php).
I can now call my variable in a mysql query on pagination.php
FROM products WHERE SubCategory2 = '".$category."'
Not the cleanest of work arounds but it saved me worrying about having to rethink the way I was doing it all.
I am developing a Messaging system.I need Scroll bar to be fixed down ,Because when new data arrives It should automatically go down.How to do that in HTML/CSS
Don't mine if this full code is in a unprofessional way..
Home.php
<?php
// Turn off all error reporting
error_reporting(0);
//shop not login users from entering
if(isset($_SESSION['id'])){
$user_id = $_SESSION['id'];
}else{
}
require_once("./inc/connect.inc.php");
?>
<header>
<link rel="stylesheet" href="home - Copy.css" />
<nav>
<h3><a class="h3" href="#">CP</a></h3>
<div><span>Logout</span></div>
<div>
<?php
//Start your session
session_start();
//Read your session (if it is set)
if (isset($_SESSION['user_login'])){
echo '<div id="ull">'.strtoupper($_SESSION['user_login']).'</div>';
}
?>
</div>
</nav>
<body>
<div class="shead">
<div class="a1"> <li >Frequent Member</li>
<div class="fm">
<ul>
<?php
//show all the users expect me
$user_id = $_SESSION['id'];
$q = mysql_query("SELECT * FROM `users` WHERE id!='$user_id'");
//display all the results
while($row = mysql_fetch_assoc($q)){
echo " <div class='usernames'>
<a id=\"usernames\" href='home.php?id={$row['id']}'>{$row['username']}</a>
</div>
";
}
?>
</ul>
</div>
</div>
<div class="a2"> <li >Site's Popular in Your College</li></div>
</div>
</header>
<div class="rss">
<?php
// include('rssclass.php');
//include('rss.php');
?>
</div>
<div class="message-right">
<!-- display message -->
<div class="display-message">
<?php
//check $_GET['id'] is set
if(isset($_GET['id'])){
$user_two = trim(mysql_real_escape_string( $_GET['id']));
//check $user_two is valid
$q = mysql_query( "SELECT `id` FROM `users` WHERE id='$user_two' AND id!='$user_id'");
//valid $user_two
if(mysql_num_rows($q) == 1){
//check $user_id and $user_two has conversation or not if no start one
$conver = mysql_query( "SELECT * FROM conversation WHERE (user_one='$user_id' AND user_two='$user_two') OR (user_one='$user_two' AND user_two='$user_id')");
//they have a conversation
if(mysql_num_rows($conver) == 1){
//fetch the converstaion id
$fetch = mysql_fetch_assoc($conver);
$conversation_id = $fetch['id'];
}else{ //they do not have a conversation
//start a new converstaion and fetch its id
$q = mysql_query( "INSERT INTO `conversation` VALUES ('','$user_id',$user_two)");
$conversation_id = mysql_insert_id($con);
}
}else{
die("Invalid $_GET ID.");
}
}else {
die("Click On the Person to start Chating.");
}
?>
</div>
<script type="text/javascript">
var objDiv = document.getElementById("display-message");
objDiv.scrollTop = objDiv.scrollHeight;
</script>
<div class="send-message">
<!-- store conversation_id, user_from, user_to so that we can send send this values to post_message_ajax.php -->
<input type="hidden" id="conversation_id" value="<?php echo base64_encode($conversation_id); ?>">
<input type="hidden" id="user_form" value="<?php echo base64_encode($user_id); ?>">
<input type="hidden" id="user_to" value="<?php echo base64_encode($user_two); ?>">
<div class="textbox">
<input class="t_box" type="text" id="message" placeholder="Enter Your Message"/>
<button class="t_btn" id="reply">Reply</button>
<span id="error"></span>
</div>
</div>
</div>
<!--
<div class="textbox">
<form action="#" method="post">
<input type="text" name="msg_body" class="t_box" id="t_box" >
<input type="submit" class="t_btn" id="t_btn" name="submit" value="Send">
</form>
</div>-->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
Getmsg.php
<?php
require_once("./inc/connect.inc.php");
if(isset($_GET['c_id'])){
//get the conversation id and
$conversation_id = base64_decode($_GET['c_id']);
//fetch all the messages of $user_id(loggedin user) and $user_two from their conversation
$q = mysql_query( "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'");
//check their are any messages
if(mysql_num_rows($q) > 0){
while ($m = mysql_fetch_assoc($q)) {
//format the message and display it to the user
$user_form = $m['user_from'];
$user_to = $m['user_to'];
$message = $m['message'];
//get name and image of $user_form from `user` table
$user = mysql_query( "SELECT username FROM `users` WHERE id='$user_form'");
$user_fetch = mysql_fetch_assoc($user);
$user_form_username = $user_fetch['username'];
//display the message
echo "
<div class='message'>
<div class='text-con'>
<a href='#''>{$user_form_username}:</a>
<p> {$message}<p>
</div>
</div>
<hr>";
}
}else{
echo "No Messages";
}
}
?>
You didn't mention if you are using jQuery. If yes, you can do something like this:
$('#your_div_id').scrollTop($('#your_div_id')[0].scrollHeight);
Alternatively, only with Javascript you can find solution here:
Scroll to bottom of div?
You always need to pass the height of the div to the scroll option so it is sticked to the bottom. This means that you need to bind this to the event which detects when the new message is received and rendered.
Your solution si based on scrollHeight, these two ling of code can help you
var objDiv = document.getElementById("toScrollBottom");
objDiv.scrollTop = objDiv.scrollHeight;
You can see this snippet for example, just click on the blue div to add messages
var count = 0;
var objDiv = document.getElementById("toScrollBottom");
objDiv.scrollTop = objDiv.scrollHeight;
$("body").on("click","#toScrollBottom",function(){
$("#messages").append('<p>Message Line' + count + '<br/>Message line</p>');
var objDiv = document.getElementById("toScrollBottom");
objDiv.scrollTop = objDiv.scrollHeight;
count++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toScrollBottom" style="height: 150px; overflow-y: scroll; margin: 50px; border: solid 2px blue;">
<div id="messages">
<p>Message Line FIRST<br/>Message Line</p>
</div>
</div>
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']
The program below contains various error messages to be displayed under certain conditions. These conditions are found through PHP code, after which the necessary JQuery script is echoed in PHP to make the messages appear.
At first, all messages in the .warning class are hidden. Then, if a certain condition is met, particular ids of this class are shown. Below is the relevant code.
<?php require_once 'connection.php'; ?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Create Account</title>
<link rel="stylesheet" type="text/css" href="Styles2.css">
<script src="JQuery.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$('.warning').hide();
});
</script>
<div class="unloggedheadingbar">
</div>
<br>
<div class="createaccount">
<center><h1>Create Account</h1></center>
<center><table>
<form action="create_account.php" method="post">
<tr><td><font class="createaccountfont">Email</font></td><td><input type="text" name="Email" placeholder="someone#somewhere.com" value="<?php if(isset($_POST['Create'])){ echo $_POST['Email']; } ?>" class="createaccounttext"></td></tr>
<tr><td colspan="2"><br></td></tr>
<tr><td><font class="createaccountfont">Password</font></td><td><input type="password" name="Password" class="createaccounttext"></td></tr>
<tr><td colspan="2"><br></td></tr>
<tr><td><font class="createaccountfont">Confirm Password </font></td><td><input type="password" name="ConfirmPassword" class="createaccounttext"></td></tr>
</table></center>
<br>
<center><input type="submit" name="Create" value="Create Account" class="createButton" id="Create"></center>
</form>
<br>
<div class="warning" id="passwordMatchError">
<center><font class="warningText">Your password confirmation must match with your original password!</font></center>
</div>
<div class="warning" id="emailFormatError">
<center><font class="warningText">Your email must match the someone#something.com format.</font></center>
</div>
<div class="warning" id="emailDuplicateError">
<center><font class="warningText">An account under this email already exists.</font></center>
</div>
</div>
<?php
if(isset($_POST['Create'])){
$email = $_POST['Email'];
$password = md5($_POST['Password']);
if(strpos($email, '#') !== TRUE){
echo '<script>
$(".warning").hide();
$("#emailFormatError").show();
</script>';
}elseif($_POST['Password'] != $_POST['ConfirmPassword']){
echo '<script>
$(".warning").hide();
$("#passwordMatchError").show();
</script>';
}else{
$query = "SELECT * FROM user_table WHERE Email = '" . $email . "';";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0){
$query = "INSERT INTO user_table VALUES ('" . $email . "', '" . $password . "');";
mysqli_query($con, $query);
}else{
echo '<script>
$(".warning").hide();
$("#emailDuplicateError").show();
</script>';
}
}
}
?>
</body>
However, the objects with particular IDs are not actually shown. Does anyone know why this may be? Thank you.
jQuery actions should be placed in $( document ).ready( function () {} );, i.e.:
echo '<script>$( document ).ready( function () {
$(".warning").hide();
$("#emailFormatError").show();
} );</script>';