Someone pls help me. I have search form and displaying data from database and im using jquery twbsPagination. So my problem is the space in url if the user search two or more words.I used encodeURIComponent(); its work perfectly fine its display data. but when i click on page 2. its display no data and when i go back to the first page the datas is not showing anymore. help me pls. im debugging for 12 hrs sorry for my english.
this is my form
<div class="input-group input-group-lg">
<input id="searchBar" type="text" class="form-control" placeholder="Search job">
<span class="input-group-btn">
<button id="searchBtn" type="button" class="btn btn-info btn-flat">Go!</button>
</span>
</div>
and this is my script
<script>
function Pagination(){
<?php
$limit=5;
$sql="SELECT COUNT(id_jobpost) AS id from job_post";
$result=$conn->query($sql);
if($result->num_rows > 0)
{
$row = $result->fetch_assoc();
$total_records = $row['id'];
$total_pages = ceil($total_records / $limit);
} else {
$total_pages = 1;
}
?>
$('#pagination').twbsPagination({
totalPages: <?php echo $total_pages;?>,
visible: 5,
onPageClick: function(e, page){
e.preventDefault();
$(".target-content").html("Loading....");
$(".target-content").load("job-pagination.php?page="+page);
}
});
}
</script>
<script>
$(function(){
Pagination();
});
</script>
<script>
$("#searchBtn").on("click", function(e){
e.preventDefault();
var searchResult = $("#searchBar").val();
var filter = "searchBar";
if (searchResult != "") {
$('#pagination').twbsPagination('destroy');
Search(searchResult,filter);
}else{
$('#pagination').twbsPagination('destroy');
Pagination();
}
});
<script>
function Search(val,filter){
$('#pagination').twbsPagination({
totalPages: <?php echo $total_pages; ?>,
visible: 5,
onPageClick: function(e, page){
e.preventDefault();
val = encodeURIComponent(val);
$(".target-content").html("Loading....");
$(".target-content").load("search.php?page="+page+"&search="+val+"&filter="+filter);
}
});
}
</script>
and this is my search.php
<?php
session_start();
require_once("db.php");
$limit = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $limit;
$search = $_GET['search'];
$sql = "SELECT * FROM job_post WHERE jobtitle LIKE '%$search%' ORDER BY id_jobpost DESC LIMIT $start_from, $limit";
$result=$conn->query($sql);
if ($result->num_rows>0) {
while ($row=$result->fetch_assoc()) {
$sql1 = "SELECT * FROM company WHERE id_company='$row[id_companyname]'";
$result1 = $conn->query($sql1);
if($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc())
{
?>
<div class="attachment-block clearfix">
<img class="attachment-img" src="uploads/logo/<?php echo $row1['logo']; ?>" alt="Attachment Image">
<div class="attachment-pushed">
<h4 class="attachment-heading"><?php echo $row['jobtitle']; ?> <span class="attachment-heading pull-right">₱<?php echo $row['maximumsalary']; ?>/Month</span></h4>
<div class="attachment-text">
<div><strong><?php echo $row1['companyname']; ?> | <?php echo $row1['province'].",".$row1['city']; ?> | Experience Required(in years): <?php echo $row['experience']; ?></strong></div>
</div>
</div>
</div>
<?php
}
}
}
}else{
echo "<center><strong>No Job Matched!</strong></center>";
}
$conn->close();
?>
I think the error is in your search.php page code. You need to change your ending limit.
$limit = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $limit;
$search = $_GET['search'];
$sql = "SELECT * FROM job_post WHERE jobtitle LIKE '%$search%' ORDER BY id_jobpost DESC LIMIT $start_from, $limit";
When you are on the first page, you are doing: LIMIT 0, 5. When you are on the second page, you are doing: LIMIT 5, 5.
I suggest:
$limit = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $limit;
$end_at = $page * $limit;
$search = $_GET['search'];
$sql = "SELECT * FROM job_post WHERE jobtitle LIKE '%$search%' ORDER BY id_jobpost DESC LIMIT $start_from, $end_at";
However I also noticed that in your search page you are doing a query inside of a query, I think a better way to do this is with a join so you only hit the database once. I don't know the structure of your database but the below code is an example of a better way to go about it so that you only hit the database once:
<?php
session_start();
require_once("db.php");
$page_size = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $page_size;
$end_at = $page * $page_size;
$search = $_GET['search'];
$sql = "
SELECT
j_p.*,
c.*
FROM
job_post j_p,
company c
WHERE
jobtitle LIKE '%$search%'
and c.id_company = j_p.id_companyname
ORDER BY
id_jobpost DESC
LIMIT
$start_from,
$end_at
";
$result=$conn->query($sql);
if ($result->num_rows>0) {
while($row1 = $result1->fetch_assoc()) {
?>
<div class="attachment-block clearfix">
<img class="attachment-img" src="uploads/logo/<?php echo $row1['logo']; ?>" alt="Attachment Image">
<div class="attachment-pushed">
<h4 class="attachment-heading"><?php echo $row1['jobtitle']; ?> <span class="attachment-heading pull-right">₱<?php echo $row1['maximumsalary']; ?>/Month</span></h4>
<div class="attachment-text">
<div><strong><?php echo $row1['companyname']; ?> | <?php echo $row1['province'].",".$row1['city']; ?> | Experience Required(in years): <?php echo $row1['experience']; ?></strong></div>
</div>
</div>
</div>
<?php
}
}else{
echo "<center><strong>No Job Matched!</strong></center>";
}
$conn->close();
?>
Related
I am still learning web development and I am working on a project in order to learn how to develop a complete website with all functionalities. I am currently trying to implement the product refine filter by categories, condition, region and price. I started doing the filter according to categories and regions only, to see how I could go about but my attempt to do it failed. Whenever I check a box, itfetches the categoryId in the url but gives me an error about sql syntax.
The error message received:
I have 4 tables
ads table with adId, title, catId, regionId, price, condition, description
category table with catId, catName
region table with regionId, regionName
images table with imageId,adId,path, preview
Can anyone help me to find a solution to my problem?
Here is my class file
public function getAllCat(){
$query = "SELECT * FROM category ORDER BY catId";
$result = $this->db->select($query);
return $result;
}
public function getAllRegion(){
$query = "SELECT * FROM region ORDER BY regionId";
$result = $this->db->select($query);
return $result;
}
public function getAllAds(){
$query = "SELECT * FROM ads ORDER BY adId DESC";
$result = $this->db->select($query);
return $result;
}
public function getPreviewImage($id){
$query = "SELECT * FROM images WHERE adId = $id AND preview = '1' ";
$image = $this->db->select($query);
return $image;
}
Here is my allads.php file
<?php
//declaration array varible
$filtercategory = array();
$filterregion = array();
//finding query string value
if(isset($_REQUEST['filtercategory'])){
//query string value to array and removing empty index of array
$filtercategory = array_filter(explode("-",$_REQUEST['filtercategory']));
}
if(isset($_REQUEST['filterregion'])){
$filterregion = array_filter(explode("-",$_REQUEST['filterregion']));
}
?>
<main class="cd-main-content">
<div class="Ads-Container">
<?php
//Pagination start
$query = "SELECT COUNT(adId) FROM ads";
$result = $db->select($query);
$row = mysqli_fetch_row($result);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 20;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
?>
<?php
$query = "SELECT * FROM ads ORDER BY adId DESC $limit";
//filter query start
if(!empty($filtercategory)){
$categorydata =implode("','",$filtercategory);
$query .= " and catId in('$categorydata')";
}
if(!empty($filterregion)){
$regiondata =implode("','",$filterregion);
$query .= " and regionId in('$regiondata')";
}
//filter query end
$post = $db->select($query);
if($post){
while($result = $post->fetch_assoc()){
?>
<div class="ads-column_2">
<div class="ads-column-thumbnail">
<?php
$preview = $ad->getPreviewImage($result["adId"]);
if($preview){
while($rresult = $preview->fetch_assoc()){
?>
<img src="/afro-circle/<?php echo $rresult['path']?>" alt="" class="image-responsive">
<?php } } ?>
<div class="ads-preview-details">
<center>
<h4><?php echo $result['title']; ?></h4>
<h4 class="">FCFA <?php echo number_format($result['price']); ?></h4>
</center>
</div>
<div class="space-ten"></div>
<div class="btn-ground text-center">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#product_view">Quick View</button>
</div>
<div class="space-ten"></div>
</div>
</div>
<?php } } ?>
</div>
<!-- /.row -->
<div class="row" style="text-align: center;">
<?php
// This shows the user what page they are on, and the total number of pages
$textline1 = "Testimonials (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need a link to
the previous page or the first page so we do nothing. If we aren't then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'First Page ';
$paginationCtrls .= 'Previous ';
// Render clickable number links that should appear on the left of the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= '<span>'.$pagenum.'</span> ';
// Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
$paginationCtrls .= ' Last Page ';
}
}
?>
<div class="pagination">
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</div>
<!-- /.row -->
<div class="cd-filter filter-is-visible">
<form>
<div class="cd-filter-block">
<h4>Categories <span class="spanbrandcls" style="float:right; visibility:hidden;"><img src="refine/images/reset.png" alt="reset" title="reset"></span></h4>
<ul class="cd-filter-content cd-filters list">
<?php
$getCategory = $category->getAllCat();
if($getCategory){
while($result = $getCategory->fetch_assoc()){
?>
<li>
<input type="checkbox" class="filter filtercategory" value="<?php echo $result['catId']; ?>" <?php if(in_array($result['catName'],$filtercategory)){ echo"checked"; } ?> >
<label class="checkbox-label" id="Category" ><?php echo $result['catName']; ?></label>
</li>
<?php } } ?>
</ul> <!-- cd-filter-content -->
</div> <!-- cd-filter-block -->
<div class="cd-filter-block">
<h4>Size <span class="spansizecls" style="float:right; visibility:hidden;"><img src="refine/images/reset.png" alt="reset" title="reset"></span></h4>
<div class="cd-filter-content">
<div class="cd-select cd-filters">
<select class="filter scheck" name="subcatId">
<option data-type="sizes" value="">Item Condition</option>
<option data-type="sizes" value="1">New</option>
<option data-type="sizes" value="2">Used</option>
</select>
</div> <!-- cd-select -->
</div> <!-- cd-filter-content -->
</div> <!-- cd-filter-block -->
<div class="cd-filter-block">
<h4>Region <span class="spancolorcls" style="float:right; visibility:hidden;"><img src="refine/images/reset.png" alt="reset" title="reset"></span></h4>
<ul class="cd-filter-content cd-filters list">
<?php
$getRegion = $region->getAllRegion();
if($getRegion){
while($result = $getRegion->fetch_assoc()){
?>
<li>
<input type="radio" class="filter filterregion" value="<?php echo $result['regionId']; ?>" <?php if(in_array($result['regionName'],$filterregion)){ echo"checked"; } ?>>
<label class="radio-label" for="radio1"><?php echo $result['regionName']; ?></label>
</li>
<?php } } ?>
</ul> <!-- cd-filter-content -->
</div> <!-- cd-filter-block -->
</form>
<i class="fa fa-close"></i> Close
</div>
<i class="fa fa-filter"></i> Search by:
<div class="clear"></div>
Here is my JS
<script>
$(function(){
$('.filter').click(function(){
var filtercategory = multiple_values('filtercategory');
var filterregion = multiple_values('filterregion');
var url ="allads.php?filtercategory="+filtercategory+"&filterregion="+filterregion;
window.location=url;
});
});
function multiple_values(inputclass){
var val = new Array();
$("."+inputclass+":checked").each(function() {
val.push($(this).val());
});
return val.join('-');
}
The problem lies in the following section of the code:
$query = "SELECT * FROM ads ORDER BY adId DESC $limit";
//filter query start
if(!empty($filtercategory)){
$categorydata =implode("','",$filtercategory);
$query .= " and catId in('$categorydata')";
}
if(!empty($filterregion)){
$regiondata =implode("','",$filterregion);
$query .= " and regionId in('$regiondata')";
}
The code insert the filter criteria at the en of the sql statement, which means after the limit. So, the actual sql statement looks something like as follows:
SELECT * FROM ads ORDER BY adId DESC LIMIT 10, 10 and catId in('4')
The correct sql code would look something like:
SELECT * FROM ads WHERE catId in('4') ORDER BY adId DESC LIMIT 10, 10
You must modify your php code to generate valid sql code. While debugging, add code that prints out the full sql statement to see the full sql ststement before it is executed.
Also, your code is wide open to sql injection attacks. Pls use prepared statements or other techniques to prevent such attacks.
I've been trying to make this work for some time now. I have a <select tag for displaying number of results on a page. Apparently, the query works on displaying all rows, but when I go to the second page, it doesn't work anymore. I've checked out a thread about using $_REQUEST variable but to no avail.
FORM
<form method="POST" action="test.php" class="navbar-form navbar-left">
<div class="form-group">
<select class="form-control" id="adNum" name="showAdsOptions" aria-describedby="categoryHelp">
<option value="10">Show 10 ads per page</option>
<option value="15">Show 15 ads per page</option>
<option value="20">Show 20 ads per page</option>
</select>
<input type="submit" name="filterAds" class="form-control" value="Go" />
</div>
</form>
TABLE
<table class="table table-bordered">
<?php
include 'admin/script/connection.php';
$limit = 5;
$counter = 1;
$me = $_SESSION['user'];
$selectSQL = "SELECT * FROM user_pending_ads WHERE User_Name='$me'";
$result = $conn->query($selectSQL);
$total = $result->num_rows;
if (isset($_GET['p']) == null) {
$p = 0;
} else {
$p = $_GET['p'];
if($p == 1) {
$p = $p-1;
} else {
$p = ($p-1) * $limit;
}
}
if ($limit > $total) {
$nop = 1;
} else {
$nop = $total/$limit;
}
$nop = ceil($nop);
$display = "SELECT * FROM user_pending_ads WHERE User_Name='$me' LIMIT $p, $limit";
// SEARCH QUERY
if (isset($_GET['searchAds'])) {
if (isset($_GET['q']) == null) {
$display = "SELECT * FROM user_pending_ads WHERE User_Name='$me' LIMIT $p, $limit";
} else {
$search = $_GET['q'];
if ($search == "") {
$display = "SELECT * FROM user_pending_ads WHERE User_Name='$me' LIMIT $p, $limit";
} else {
$display = "SELECT * FROM user_pending_ads WHERE User_Name='$me' AND Ad_Title LIKE '%$search%' LIMIT $p, $limit";
}
}
}
// IF SHOW # ADS PER PAGE IS SET AND GO IS CLICKED
if (isset($_POST['filterAds']) == true) {
$opt = $_REQUEST['showAdsOptions'];
$display = "SELECT * FROM user_pending_ads WHERE User_Name='$me' LIMIT $p, $opt";
}
$getdisplay = $conn->query($display);
while ($col = $getdisplay->fetch_assoc()) {
...
}
?>
</table>
PAGINATION
<ul class="pagination">
<?php
if ($total >= 1) {
?>
<li>First</li>
<?php
for ($i = 1; $i <= $nop; $i++) {
?>
<li><?php echo $i ?></li>
<?php
}
?>
<li>Last</li>
<?php
}
?>
</ul>
I'm trying learn how to make a simple pagination.. for the first launch (index.php) it's success,
then i click the button CATEGORIES to show the products by category, it's still success..
But when i click the next page, let say page number 5, it's actually jump to the page number 5
but not in the CATEGORIES, it's back to the main page. I know it's because of this echo a href='index.php',
but i'm a beginner here, just start with php and javascript about a week ago,
so i need you "JUST CORRECT MY CODE", please don't give me a bunch of code like javascript that i'm just start to learning.
<!--index.php-->
<!doctype html>
<?php include ("functions/functions.php"); ?>
<html>
<head>
<link rel="stylesheet" href="styles/style.css" type="text/css" media="all" />
</head>
<body>
<!--NAV BUTTON-BY CATEGORY-->
<ul id="cats">
<?php getCats(); ?>
</ul>
<!--SHOWING PRODUCTS-->
<div id="wrapper">
<?php getPro(); ?> <!--FIRST LAUNCH (index.php)-->
<?php getCatPro(); ?> <!--GETTING THE PRODUCTS BY CATEGORIES-->
</div>
</body>
</html>
//functions.php
<?php
$con = mysqli_connect("localhost","root","","justLearning");
if (mysqli_connect_errno())
{
echo "The connection was not established: " . mysqli_connect_error();
}
//GETTING THE CATEGORIES (
function getCats(){
global $con;
$get_cats = "select * from categories";
$run_cats = mysqli_query($con, $get_cats);
while ($row_cats=mysqli_fetch_array($run_cats)){
$cat_id = $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<li><button><a href='index.php?cat=$cat_id'>$cat_title</a></button></li>";
}
}
//FIRST LAUNCH (index.php)
function getPro(){
if(!isset($_GET['cat'])){
if(!isset($_GET['brand'])){
global $con;
$per_page=9;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
$query = "SELECT * FROM products ORDER BY product_id DESC LIMIT $start_from, $per_page";
$result = mysqli_query ($con, $query);
while ($row = mysqli_fetch_array($result)){
$pro_title = $row['product_title'];
$pro_image = $row['product_image'];
echo "<div id='product'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='135' height='145'/>
</div>";
}
$query = "select * from products";
$result = mysqli_query($con, $query);
$total_records = mysqli_num_rows($result);
$total_pages = ceil($total_records / $per_page);
echo "<a href='index.php?page=1'>".'First Page'."</a> ";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."'>".$i."</a> ";
};
echo "<a href='index.php?page=$total_pages'>".'Last Page'."</a>";
}
}
}
//GETTING THE PRODUCTS BY CATEGORIES
function getCatPro(){
if(isset($_GET['cat'])){
$cat_id = $_GET['cat'];
global $con;
$per_page=9;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
$query = "SELECT * FROM products where product_cat='$cat_id' order by product_id DESC LIMIT $start_from, $per_page";
$result = mysqli_query ($con, $query);
while ($row_cat_pro=mysqli_fetch_array($result)){
$pro_title = $row_cat_pro['product_title'];
$pro_image = $row_cat_pro['product_image'];
echo "<div id='product'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='135' height='145'/>
</div>";
}
$query = "select * from products where product_cat='$cat_id'";
$result = mysqli_query($con, $query);
$total_records = mysqli_num_rows($result);
$total_pages = ceil($total_records / $per_page);
echo "<a href='index.php?page=1'>".'First Page'."</a> ";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='index.php?page=".$i."'>".$i."</a> ";
};
echo "<a href='index.php?page=$total_pages'>".'Last Page'."</a>";
}
}
?>
You have to modify getCatPro() and concatenate the cat parameter to the links. For example:
echo "<a href='index.php?page=".$i."&cat=".$cat_id."'>".$i."</a> ";
Hope it helps.
My code is below.
Since my items are many in numbers i showed on 12 items at a time but it is starting from item number 3 and skipping item 1, 2
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$sql = "SELECT * FROM item_table LIMIT $start_from, $num_rec_per_page";
$rs_result = mysql_query($sql) or die("Unable to get results"); //run the query
$row=mysql_fetch_assoc($rs_result) or die("Unable to get rows");
<?php
while($row=mysql_fetch_assoc($rs_result))
{
?>
<form>
<div class="col-xs-6 col-sm-3">
<div class="thumbnail" style="height:350px; background-color:black;transparent">
</img>
<h3 style="color:white;" ><?php echo $row['title']?></h3>
<p><?php// echo $row['s_des']?></p>
</div>
</div>
</form>
<div align="center">
<?php
} //end of loop ?>
?>
<?php
require 'connect.inc.php';
$query = "SELECT `item`, `up`, `down` FROM mytable ORDER BY RAND() LIMIT 1";
$query_run = mysql_query($query);
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$item = $query_row['item'];
$up = $query_row['up'];
$down = $query_row['down'];
?>
<div id="one">
<div id="votes">
<?php
echo "$up votes";
?>
</div>
</div>
<div id="or">
<div id="item">
<?php echo $item ?>
</div>
</div>
<div id="two">
<div id="votes">
<?php
echo "$down votes";
?>
</div>
</div>
<?php }
} else {
echo mysql_error();
}
?>
This is my code. I need to make it so when a user clicks the div id="one" or id="two" execute this sql query (if div one was clicked (same thing for two))
UPDATE mytable SET up=$up+1 WHERE id="1(can be any id)"
Also, can I do that math in an sql query?
Thanks
Alright so this consist of 3 parts:
1.html.
2.JS/ajax.
3.php.
1.) HTML.
<div data-action="up" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$up votes";
?>
</div>
</div>
<div id="or">
<div id="item">
<?php echo $item ?>
</div>
</div>
<div data-action="down" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$down votes";
?>
</div>
</div>
2.) JS/Ajax.
<script type='text/javascript' >
$('.clicker').click(function (){
doAjaxCall($(this).attr('id'), $(this).attr('data-action'));
});
function doAjaxCall(varID, vote){
var pageUrl = document.URL;
ar post = '{"ajax":"yes", "varID":' + varID + ', "vote":' + vote + '}';// Incase you want to pass dynamic ID
$.post(pageUrl,post,function(data){
var response = $.parseJSON( data )
if(response.success){
//do whatever you like.
alert('baaaam');
}
});
}
</script>
3.) php.
if($_POST['ajax'] == 'yes'){
$field = $_POST['vote'];
$query = "UPDATE mytable SET `$field` = `$field` +1 WHERE id=".$_POST['var_id'];
$query_run = mysql_query($query);
$return = array();
$return['success'] = false;
if($query_run){
$return['success'] = true;
}
echo json_encode($return);
die()
}
Update whole Page
if($_POST['ajax'] == 'yes'){
$field = $_POST['vote'];
$query = "UPDATE mytable SET `$field` = `$field` +1 WHERE id=".$_POST['var_id'];
$query_run = mysql_query($query);
$return = array();
$return['success'] = false;
if($query_run){
$return['success'] = true;
}
echo json_encode($return);
die()
}
$query = "SELECT `item`, `up`, `down` FROM mytable ORDER BY RAND() LIMIT 1";
$query_run = mysql_query($query);
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$item = $query_row['item'];
$up = $query_row['up'];
$down = $query_row['down'];
?>
<div data-action="up" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$up votes";
?>
</div>
</div>
<div id="or">
<div id="item">
<?php echo $item ?>
</div>
</div>
<div data-action="down" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$down votes";
?>
</div>
</div>
<script type='text/javascript' >
$('.clicker').click(function (){
doAjaxCall($(this).attr('id'), $(this).attr('data-action'));
});
function doAjaxCall(varID, vote){
var pageUrl = document.URL;
var post = '{"ajax":"yes", "varID":' + varID + ', "vote":' + vote + '}';// Incase you want to pass dynamic ID
$.post(pageUrl,post,function(data){
var response = $.parseJSON( data )
if(response.success){
//do whatever you like.
alert('baaaam');
}
});
}
</script>
<?php }
} else {
echo mysql_error();
}
?>
Basically this is the whole thing. if you want i can also put the pieces together for you.
You can add and onClick() event in javascript/jquery. Then, do a POST like this
$("#div1").onClick(function(){
var info = $(this).val();
$.post("fileWithQuery.php",{toUpdate: info},function(data){ // (fileName to post, variables to send via POST, callBack function)
// Show a message
});
});
You just need to create that php file.