I would like to create a web page so I can assign access zones to people by dragging the people into the zones and update the zone in the database.
I manage to use Drag and drop javascript and retrieve the list of people in the database.
But I would like to find the most optimal way to sort people in the right boxes when the page loads and then I would like to be able to change the zone number in the Mysql database when a person is dropped in a zone .
See Image
Here is my current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>📌 Drag and Drop</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<main class="board">
<div class="column column-zone1" ondrop="drop(event)" ondragover="allowDrop(event)">
<h2>Zone 1</h2>
<div class="container">
<table>
<div class="column column-ip" ondrop="drop(event)" ondragover="allowDrop(event)">
<?php include('EmployesDrag.php')
?>
</div>
</table>
</div>
</div>
<div class="column column-zone2" ondrop="drop(event)" ondragover="allowDrop(event)">
<h2>Zone 2</h2>
</div>
<div class="column column-zone3" ondrop="drop(event)" ondragover="allowDrop(event)">
<h2>Zone 3</h2>
</div>
</main>
<script src="js/DragDrop.js"></script>
</body>
</html>
<?php
//connexion à la base de donnée
include_once "connexion.php";
//requête pour afficher les infos d'un employé
$sql="SELECT prenom , nom FROM personnel";
$result=mysqli_query($con,$sql);
if ($result)
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
}
if($rowcount == 0){
//s'il n'existe pas d'employé dans la base de donné , alors on affiche ce message :
echo "Il n'y a pas encore d'employé ajouter !" ;
}else {
//si non , affichons la liste de tous les employés
while($row=$result->fetch_assoc()){
?>
<tr>
<article class="card" draggable="true" ondragstart="drag(event)" data-id="1"><?=$row['nom']?></td>
</tr>
<?php
}
// Free result set
mysqli_free_result($result);
}
?>
const dragStart = target => {
target.classList.add('dragging');
};
const dragEnd = target => {
target.classList.remove('dragging');
};
const dragEnter = event => {
event.currentTarget.classList.add('drop');
};
const dragLeave = event => {
event.currentTarget.classList.remove('drop');
};
const drag = event => {
event.dataTransfer.setData('text/html', event.currentTarget.outerHTML);
event.dataTransfer.setData('text/plain', event.currentTarget.dataset.id);
};
const drop = event => {
document.querySelectorAll('.column').forEach(column => column.classList.remove('drop'));
document.querySelector(`[data-id="${event.dataTransfer.getData('text/plain')}"]`).remove();
event.preventDefault();
event.currentTarget.innerHTML = event.currentTarget.innerHTML + event.dataTransfer.getData('text/html');
};
const allowDrop = event => {
event.preventDefault();
};
document.querySelectorAll('.column').forEach(column => {
column.addEventListener('dragenter', dragEnter);
column.addEventListener('dragleave', dragLeave);
});
document.addEventListener('dragstart', e => {
if (e.target.className.includes('card')) {
dragStart(e.target);
}
});
document.addEventListener('dragend', e => {
if (e.target.className.includes('card')) {
dragEnd(e.target);
}
});
To display people in the right column, I can do it by making 3 different php pages and executing the query $sql="SELECT firstname, lastname FROM personal where zoneAccess = 1";
then $sql="SELECT firstname, lastname FROM personal where zoneAccess = 2";
and then $sql="SELECT firstname, lastname FROM personal where zoneAccess = 3";
But I know that's not the right way to do it. Can you help me improve this?
And how can I do to write the number of the selected zone, in the zoneAccess field of the database?
Thanks,
Kevin.
I found a way to make everything work, but my code is not optimized:
For each area from/to which I want to drag and drop, I execute one MYSQL Request to retrieve the names associated with each zone:
require_once('connexion.php');
$sqlZone1 = "SELECT id, nom, zoneAcces FROM personnel where zoneAcces = '1' ORDER
BY id desc";
$zone1Result = mysqli_query($con, $sqlZone1);
//Fetch all zone1 list items
$zone1Items = mysqli_fetch_all($zone1Result,MYSQLI_ASSOC);
//Get Zone2 items
$sqlZone2 = "SELECT id, nom, zoneAcces FROM personnel where zoneAcces = '2' ORDER
BY id desc";
$zone2Result = mysqli_query($con, $sqlZone2);
//Fetch all Zone2 items
$zone2Items = mysqli_fetch_all($zone2Result, MYSQLI_ASSOC);
...
then I create the DIV for the area to DRAG/DROP
<div id="droppable1" class="ui-widget-header">
<?php foreach ($zone1Items as $key => $item) { ?>
<div class="personnel1" data-itemid=<?php echo $item['id'] ?> >
<p><strong><?php echo $item['nom'] ?></strong></p>
<hr />
</div>
<?php } ?>
</div>
<div id="droppable2" class="ui-widget-header">
<?php foreach ($zone2Items as $key => $bitem) { ?>
<div class="personnel2" data-itemid=<?php echo $bitem['id'] ?>>
<p><strong><?php echo $bitem['nom'] ?></strong></p>
<hr />
</div>
<?php } ?>
</div>
...
Then For each zone I create the javascript to allow drag drop and with a link to a php file for each update
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( ".personnel1" ).draggable();
$( "#droppable1" ).droppable({
drop: function( event, ui ) {
$(this).addClass( "ui-state-highlight" );
var itemid = ui.draggable.attr('data-itemid')
$.ajax({
method: "POST",
url: "updatePHP/update_item_status1.php",
data:{'itemid': itemid},
}).done(function( data ) {
var result = $.parseJSON(data);
});
}
});
});
$( function() {
$( ".personnel2" ).draggable();
$( "#droppable2" ).droppable({
drop: function( event, ui ) {
$(this).addClass( "ui-state-highlight" );
var itemid = ui.draggable.attr('data-itemid')
$.ajax({
method: "POST",
url: "updatePHP/update_item_status2.php",
data:{'itemid': itemid},
}).done(function( data ) {
var result = $.parseJSON(data);
});
}
});
});
And so for each Update I've a different php file with only zoneAcces = '1' or zoneAcces = '2' or ... wich is different
<?php
require_once('../connexion.php');
$itemid = intval($_POST['itemid']);
//SQL query to get results from database
$sql = "update personnel set zoneAcces = '1' where id = $itemid";
$con->query($sql);
$con->close();
//send a JSON encded array to client
echo json_encode(array('success'=>1));
Related
First, I will summary my demo for you: I have a form for me to type an api link and type of the chart I want to draw from my api link. After that, I will click the button to create chart and insert my input to MySQL database to show it on screen. Each chart have a button for me to delete it if I want.
Everything worked fine except delete funtion to delete my input from database. When I press delete button, it's only delete in html, not delete in my database. Can you help me? Thank you!
Here is my code:
My input form:
<!--HTML Form input-->
<div class = "login-block">
<form id="form1" style="display: block" method="POST" action="chart_test.php">
<!--Input link api-->
<b>Link: </b><input type="text" id="link" name="apilink"><br>
<br>
<!--Chart Type-->
<b>Chart Type:</b>
<label class="custom-select">
<select id="chartType" name="chartType">
<option value="">Select</option>
<option value="pie">Pie Chart</option>
<option value="column">Column Chart</option>
<option value="bar">Bar Chart</option>
</select>
</label>
<br><br>
<!--Button create chart-->
<div class ="wrapper">
<button type="submit" name="create" onClick="drawChart()">Create</button>
<br><br>
</div>
</form>
</div>
Insert input to database and show to screen:
<!--insert form data to mysql-->
<?php
$con = mysql_connect("localhost","root","123456");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
mysql_select_db("activiti_report");
//check data when first load page to not showing notice error
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$apilink = $_POST["apilink"];
$chartType = $_POST["chartType"];
}
if(isset($_POST['create'])) {
$sql = "INSERT INTO chartinfo (link, typeChart) VALUES ('$apilink', '$chartType')";
$result = mysql_query($sql);
header("Location:chart_test.php");
exit;
}
?>
Query database to show chart on screen and the button with script to delete:
<?php //query data from database
$result = mysql_query("SELECT * FROM chartinfo");
?>
<?php //while loop to read data from query result
while($db_field = mysql_fetch_assoc($result)):
?>
<?php //unique chartId for not the same to show more chart
$idChart = 'chartContainer_' . uniqid();
?>
<!--Show chart from database-->
<br>
<div class = "chart-block">
<?php // 2 lines about chart infomation
echo ("<b>API Link:</b> "); print $db_field['link'] . "<BR>";
echo ("<b>Chart Type:</b> "); print $db_field['typeChart'] . "<BR>";
?>
<!-- The <div> and <script> to show the chart -->
<div id="<?=$idChart?>" style="height: 360px; width: 70%;"></div>
<script>
$(document).ready(function() {
var dataPointsA = []
var text = document.getElementById('chartType')
var strChart = text.options[text.selectedIndex].value
$.ajax({
type: 'GET',
url: "<?php echo $db_field['link']?>", //assign URL from query result field
dataType: 'json',
success: function(field) {
for (var i = 0; i < field.length; i++) {
dataPointsA.push({
label: field[i].name,
y: field[i].value
});
}
var chart = new CanvasJS.Chart("<?=$idChart?>", {
title: {
text: "Activiti Report"
},
data: [{
type: "<?php echo $db_field['typeChart']?>", //assign type of chart from query result field
name: "chart",
dataPoints: dataPointsA
}]
});
chart.render();
}
});
});
</script>
<br>
<!--Button to delete the chart and row in database-->
<button type="submit" name="delete" onClick="removeParent(this.parentNode)">Delete</button>
<!--Script remove <div> contain the chart-->
<script>
function removeParent(parent) {
parent.remove();
}
</script>
<!--Script delete form data from mysql-->
<?php
if(isset($_POST['delete'])) {
$sql = "DELETE FROM chartinfo (link, typeChart) WHERE link ='" .$db_field['link']. "' AND typeChart = '" .$db_field['link']. "'";
$result = mysql_query($sql);
header("Location:chart_test.php");
exit;
}
?>
I know I should use mysqli_* instead mysql_* but this is just a demo for me to understand PHP, I learned it only a few days. Sorry for a lot of code but I think I should show to you to understand what I am doing.
Thank you very much!
Your delete button trigger its action from the js code not the php code. It only remove from the view but will appear on reload. You can use ajax in your remove function or use a delete link instead of button
<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php",
data: {id:id},
success: function(resp) {
btn_this.parentNode.remove();
}
});
});
<?php
if(isset($_GET['id'])) {
$sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
$result = mysql_query($sql);
}
?>
<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
<script>
$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php?id="+id,
success: function(resp) {
btn_this.parentNode.remove();
}
});
});
</script>
<?php
if(isset($_GET['id'])) {
$sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
$result = mysql_query($sql);
}
?>
Hello I'm a beginner in Ajax and PHP so sorry if my question is useless or stupid. But I am trying to do a live search with ajax and I have looked over and over internet but nothing could help me... so here I am! :-) I have 4 files one for the html, one to connect to the database, one for jQuery and the last one for the script in php. I have looked on the console with chrome and I can see that the ajax works but there is no output and I have no idea why... I'll leave you the code below and an early thank you! Also there might be some French in the code but it's just the variables and I will secure my connection to the database later. Thank you again.
Html :
<html>
<head>
<meta charset="utf-8" />
<title>live search test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche">
</div>
<br>
<div class="resultat" id="resultat">
</div>
</body>
</html>
PHP to connect to the database:
<?php
$host="localhost";
$user="root";
$password="";
$db="smartphone";
$conn=mysqli_connect($host,$user,$password,$db);
?>
jQuery:
$(document).ready(function(){
$("#recherche").keyup(function(){
var recherche = $(this).val();
var data = 'motclef = ' + recherche;
if (recherche.length > 1) {
$.ajax({
type : "GET",
url : "fetch.php",
data : data,
success : function(server_response){
$("#resultat").html(server_response).show();
}
});
}
});
});
And the script in PHP:
include'connect.php';
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn ->prepare($sql);
$req -> execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req -> fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result ->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
?>
Remove whitespace from 'motclef = '
var data = 'motclef= ' + recherche;
Other wise put underscore $_GET['motclef_'] in your PHP code(if you don't remove space then)
if (isset($_GET['motclef_'])) {
$motclef = $_GET['motclef_'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn->prepare($sql);
$req->execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req->fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
i am working on a project and come across a module.
page1
user have to search from search bar which will take him to page 2.
page2
On page 2 all fetched results will get displayed to user in div's. Each result has a checkbox associated with it.
when i click on add to compare check box ,ajax call is executed and fetched selected result should appear in hidden div.
my problem is it is only shows first result in hidden div and not working with another result.
My code of page 2
<script type="text/javascript">
$(document).ready(function()
{
var check = $('#compare').val();
$("#compare").change(function() {
if(this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').html(data);
}
});
$("#compare_box").show();
}
else
{
$("#compare_box").hide();
}
});
});
</script>
</head>
<body>
<?php
$query = $_GET['search_bar'];
$query = "call fetch_data('$query')"or die(mysqli_error($conn));
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result))
{
$id = $row['course_id'];
$title = $row['course_title'];
$description = $row['course_description'];
$course_url = $row['course_url'];
$video_url = $row['course_video_url'];
$fee = $row['course_fee'];
$duration = $row['course_duration'];
$start_date = $row['course_start_date'];
$university = $row['university_name'];
$course_provider = $row['course_provider_name'];
$instructor = $row['instructor_name'];
$_SESSION['result'][$id] = Array('id'=> $id,'course_title' => $title,'course_description'=> $description,'course_url' => $course_url,'video_url' => $video_url,'fee' => $fee,'course_duration'=>$duration,'start_date'=>$start_date,'university' => $university,'course_provider'=>$course_provider,'instructor'=>$instructor);
?>
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
<?php
}
?>
page3 compare.php
<?php
session_start();
include 'includes/dbconfig.php';
$check = $_POST['value'];
$sql = "SELECT * from course_info_table where course_id = '$check' " or die(mysqli_error($conn));
$result = mysqli_query($conn,$sql);
$index = 0;
while($row = mysqli_fetch_array($result))
{
$title = $row['course_title'];
?>
<?php
}
echo json_encode($title);
?>
You can change
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">
to
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">
^you can only have one unique 'id' value in your html doc, which means your first id="compare" will work fine and others with id="compare" will be ignored by the DOM tree
Reference:
http://www.w3schools.com/tags/att_global_id.asp
Summary:
I have a list of posts, each post also containing a list of comments within it. I have the option to add a comment directly on the post (much like twitter). I submit those posts via ajax.
Problem:
When submitting a new comment, is updates all the "comments lists" of each and all posts, and not only the one I have submitted from.
Any ideas? (code below)
JS:
$(document).ready(function () {
var options = {
//clearForm: true,
//resetForm: true,
//beforeSubmit: ShowRequest,
success: function (html) {
$('.post_comment_list').prepend(html);
$('.footer-post').hide();
$('.comments-feed').hide();
$('.small-textarea-main-feed').removeClass('set-large');
resetForm($('.footer-comment'));
},
error: function () {
alert('ERROR: unable to upload files');
},
complete: function () {
},
};
$(".footer-comment").ajaxForm(options);
function ShowRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
return true;
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
});
PHP
<?php
if (empty($_POST) === false && empty($errors) === true) {
//register user
$post_comment = array(
'comment' => $_POST['comment'],
'id' => $_POST['id'],
);
$user_id = $_SESSION['user_id'];
post_comment_db($user_id, $post_comment);
//print_r($post_question['tags']);
load_comment($user_id,$post_comment);
} else{
echo output_errors($errors);
}
?>
PHP/HTML: Li (the comment to be added)
function load_comment($user_id,$post_comment){
$username = mysql_result(mysql_query("SELECT `username` FROM `users` WHERE `user_id` = $user_id"), 0, 'username');
$timestamp = mysql_result(mysql_query("SELECT `timestamp` FROM `comments` WHERE `user_id` = $user_id"), 0, 'timestamp');
$r = format_time($timestamp);
$question_id = $post_comment['id'];
$q = "SELECT `comment_id` FROM `question_has_comments` WHERE `question_id` = $question_id ORDER BY `timestamp` DESC LIMIT 1" ;
$q = "SELECT `comment_id` FROM `comments` WHERE `question_id` = $question_id ORDER BY `timestamp` DESC LIMIT 1" ;
echo
'
<li id="" class="post_comment">
<!-- wrapper da imagem -->
<div id="" class="give-margin">
<div id="" class="profile-page-avatar-wrapper">
<img id="" class="profile-page-avatar-image" src="./images/test/chemistry.jpg" alt=""><!-- A imagem -->
</div>
<!-- o botao e o texto-->
<div id="" class="profile-page-uploader-tools">
<!-- o botao -->
<div id="" class="profile-image-btn">
<div id="" class="profile-page-btn-wrapper">
<div id="" class="header-id">
<span id="user-name">' . $username . '</span>
</div>
<div id="" class="question-page-feed-answer-header-timer">
<a id="feed-answer-header-timer" href="#"><span class="timer" data-time="">' . $r . '</span></a>
</div>
</div> <!-- fecha Div wrapper do botao-->
</div>
<!-- fecha botao
http://www.w3.org/TR/html-markup/Overview.html#toc-->
<p>' . $post_comment['comment'] . '</p>
</div>
</div>
</li>';
}
Your last comment response identified the problem:
the class "post_coment_list" is an "ol" present in all posts, where the comments to a post reside
From the api:
.prepend(): Description: Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
In your code, the ajax success function prepends the returned HTML as follows:
$('.post_comment_list').prepend(html);
Since $('.post_comment_list') is a set of all elements with class .post_comment_list, and since every post has that class, your HTML will be prepended to each and every post.
To solve this, assign each post a unique ID and, in the success function, prepend the HTML only to that one ID.
To get that ID, you can grab it at the time the ajax call is made and either:
assign the ID to a global var and grab it again in the success fn, or
send the ID along with the other ajax data, and then send it back to the success fn along with the HTML. For example:
PHP side:
$post_id = $_POST['postid'];
$send_back = $post_id . '|' . '<li id="" class="post_comment">
<!-- wrapper da imagem -->
<div id="" class="give-margin">
etc
';
echo $send_back
jQuery/javascript: (inside success: function)
var arrHTML = html.split('|');
var postId = arrHTML[0];
var html_code = arrHTML[1];
$('#'+postId).prepend(html_code);
Note that, above, I did not demonstrate sending the post ID over to the PHP side. I'm sure you are alright with that. Just showed enough to explain what I was suggesting.
Hi i have voting system,
The problem is when i hit vote up/down its count the vote. But when i refresh/reload the page its back to default vote amount. Run the test on local machine only so far, with wamp.
This is the code from index.php
<?php
include('config.php');
# connect mysql db
dbConnect();
$query = mysql_query(
'SELECT id, first_name, last_name, film_info, vote
FROM voting
LIMIT 0 , 15');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>jQUery Voting System</title>
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<div class="wrap">
<h1>Voting System</h1>
<?php while($row = mysql_fetch_array($query)): ?>
<div class="item" data-postid="<?php echo $row['id'] ?>" data-score="<?php echo $row['vote'] ?>">
<div class="vote-span"><!-- voting-->
<div class="vote" data-action="up" title="Vote up">
<i class="icon-chevron-up"></i>
</div><!--vote up-->
<div class="vote-score"><?php echo $row['vote'] ?></div>
<div class="vote" data-action="down" title="Vote down">
<i class="icon-chevron-down"></i>
</div><!--vote down-->
</div>
<div class="post"><!-- post data -->
<h2><?php echo $row['first_name'].' '.$row['last_name']?></h2>
<p><?php echo $row['film_info'] ?></p>
</div>
</div><!--item-->
<?php endwhile?>
<p style="text-align:center; margin-top: 20px">© w3bees.com 2013</p>
</div>
<?php dbConnect(false); ?>
</body>
</html>
This is the config.php
<?php
# db configuration
define('DB_HOST', 'locahost');
define('DB_USER', 'hendra');
define('DB_PASS', '123456');
define('DB_NAME', 'voter');
# db connect
function dbConnect($close=true){
global $link;
if (!$close) {
mysql_close($link);
return true;
}
$link = mysql_connect("localhost", "hendra", "123456") or die('Could not connect to MySQL DB ') . mysql_error();
if (!mysql_select_db("voter", $link))
return false;
}
?>
This is the ajaxvote.php
<?php
include('config.php');
# start new session
session_start();
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) AND isset($_POST['action'])) {
$postId = (int) mysql_real_escape_string($_POST['postid']);
# check if already voted, if found voted then return
if (isset($_SESSION['vote'][$postId])) return;
# connect mysql db
dbConnect();
# query into db table to know current voting score
$query = mysql_query("
SELECT vote
from voting
WHERE id = '{$postId}'
LIMIT 1" );
# increase or dicrease voting score
if ($data = mysql_fetch_array($query)) {
if ($_POST['action'] === 'up'){
$vote = ++$data['vote'];
} else {
$vote = --$data['vote'];
}
# update new voting score
mysql_query("
UPDATE voting
SET vote = '{$vote}'
WHERE id = '{$postId}' ");
# set session with post id as true
$_SESSION['vote'][$postId] = true;
# close db connection
dbConnect(false);
}
}
}
?>
and this is the jQuery code
$(document).ready(function(){
// ajax setup
$.ajaxSetup({
url: 'ajaxvote.php',
type: 'POST',
cache: 'false'
});
// any voting button (up/down) clicked event
$('.vote').click(function(){
var self = $(this); // cache $this
var action = self.data('action'); // grab action data up/down
var parent = self.parent().parent(); // grab grand parent .item
var postid = parent.data('postid'); // grab post id from data-postid
var score = parent.data('score'); // grab score form data-score
// only works where is no disabled class
if (!parent.hasClass('.disabled')) {
// vote up action
if (action == 'up') {
// increase vote score and color to orange
parent.find('.vote-score').html(++score).css({'color':'orange'});
// change vote up button color to orange
self.css({'color':'orange'});
// send ajax request with post id & action
$.ajax({data: {'postid' : postid, 'action' : 'up'}});
}
// voting down action
else if (action == 'down'){
// decrease vote score and color to red
parent.find('.vote-score').html(--score).css({'color':'red'});
// change vote up button color to red
self.css({'color':'red'});
// send ajax request
$.ajax({data: {'postid' : postid, 'action' : 'down'}});
};
// add disabled class with .item
parent.addClass('.disabled');
};
});
});
Troubleshoot your code in ajaxvote.php
There may be issue because of you are calling mysql_real_escape_string before database connection.
Change
define('DB_HOST', 'locahost');
to:
define('DB_HOST', 'localhost');