I want to load posts by click, I have two files
index.php with ajax
handler.php.
I'm studying AJAX. I understand this technology so by clicking on the button an Ajax request should occur, then the handler returns the data to the Ajax request, and the Ajax query outputs this data. But I can not do it, why? How to fix the error? My error is that the posts are not loaded. The console is empty. I set the echo to the top of the handler, but it did not work. I guess the problem with ajax
index.php with ajax
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
</head>
<body>
<main>
<!-- <article class="news">
<div class="picture"><img src="1news.jpg" width="300" height="300"></div>
<div class="aboutpost">
<h2 class="aboutpost-title">Пожар в торговом центре в Кемерово</h2>
<p class="aboutpost-description">Холдинг, куда входило ЧОП "Зимней вишни", прекратил работу после трагедии</p>
</div>
</article> -->
<?php
require 'infofordb.php';
$link = mysqli_connect($host, $user, $password, $database) or die("Ошибка " . mysqli_error($link));
$query ="SELECT * FROM news ORDER BY id DESC LIMIT 5";
$result = mysqli_query($link, $query) or die("Ошибка " . mysqli_error($link));
$articles = array();
while($row = mysqli_fetch_assoc($result)) {$articles[] = $row;}
foreach($articles as $article) {echo '
<article class="news">
<div class="picture">
<img src="/image/'.$article[path].'">
</div>
<div class="aboutpost">
<h2 class="aboutpost-title">'.$article[title].'</h2>
<p class="aboutpost-description">'.$article[description].'</p>
</div>
</article>';}
?>
<center><button id="load">Загрузить ещё</button></center>
<script>
$(document).ready(function(){
var inProgress = false;
var start = 5;
$('#load').click(function() {
$.ajax({
url: 'handler.php',
method: 'POST',
data: {"start" : start},
dataType: 'json',
beforeSend: function() {inProgress = true;}
}).done(function(data){
data = jQuery.parseJSON(data);
alert('nen');
if (data.length > 0) {
//надо вывести
$.each(data, function(index, data){
$('main').append(
'<article class="news"><div class="picture"><img src="/image/' + data.path +
+ '"></div><div class="aboutpost"><h2 class="aboutpost-title">' + data.title +
+ '</h2><p class="aboutpost-description">' + data.description +
+ '</p></div></article>');
});
inProgress = false;
start += 5;
}
});
});
});
</script>
</main>
</body>
</html>
handler.php
<?php
include(infofordb.php);
$start = $_POST['start'];
$link = mysqli_connect($host, $user, $password, $database) or die("Ошибка " . mysqli_error($link));
$query ="SELECT * FROM news ORDER BY id DESC LIMIT {$start}, 5";
$result = mysqli_query($link, $query) or die("Ошибка " . mysqli_error($link));
$articles = array();
while($row = mysqli_fetch_assoc($result)) {$articles[] = $row;}
echo json_encode($articles);
?>
dataType: 'json', tells jQuery to parse the returned JSON data. In your code, you call JSON.parse which attempts to parse it again, remove that line(this line I mean data = jQuery.parseJSON(data);).
You need to check your mysql Query in handler.php
$query ="SELECT * FROM news ORDER BY id DESC LIMIT {$start}, 5";
The curly braces does not work in query. May be this solve your problem.
Related
I'm a complete beginner and have built a basic To-Do List application using PHP/jQuery. The application allows the user to add and remove tasks from a list (stored in a MySQL database).
I'm having issues with the delete function. When the delete button is clicked, it removes the task from the list but it must be remaining in the database, as it reappears once the page is refreshed.
I have no idea where I'm going wrong! Any help appreciated. See below code:
index.php :
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<link rel="stylesheet" type="text/css" href="/style.css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="main">
<div class="list">
<ul>
<?php
require("db_connect.php");
$query = mysql_query("SELECT * FROM tasks ORDER BY date ASC, time ASC");
$numrows = mysql_num_rows($query);
if($numrows>0) {
while ( $row = mysql_fetch_assoc( $query ) ){
$task_id = $row['task_id'];
$task_desc = $row['task_desc'];
echo '<li><span>'.$task_desc.'</span><img id="'.$task_id.'" class="delete" width="10px" src="images/delete.png" /></li>';
}
}
?>
</ul>
</div>
<form class="new" autocomplete="off">
<input type="text" name="new-task" placeholder="Add a new task..." />
</form>
</div>
</body>
<script>
add_task();
delete_task();
function add_task() {
$('.new').submit(function() {
var new_task = $('.new input[name=new-task]').val();
if(new_task !== '') {
$.post('add_task.php', { task: new_task }, function ( data ) {
$('.new input[name=new-task]').val('');
$(data).appendTo('.list ul').hide().fadeIn();
delete_task();
});
}
return false;
});
}
function delete_task() {
$('.delete').click(function() {
var current_element = $(this);
var task_id = $(this).attr('task_id');
$.post('delete_task.php', { task_id: task_id }, function() {
current_element.parent().hide().fadeOut("fast", function() {
$(this).remove();
});
});
});
}
</script>
delete_task.php :
<?php
$task_id = strip_tags( $_POST['task_id'] );
require("db_connect.php");
mysql_query("DELETE FROM tasks WHERE task_id='$task_id'");
?>
You have an error in your delete_task function. There is no such attr as 'task_id'. Try to replace
var task_id = $(this).attr('task_id');
With
var task_id = $(this).attr('id');
Besides #IvanGajic answer is correct, also write your delete query like this:
mysql_query('DELETE FROM tasks WHERE task_id="' . $task_id . '"');
I realized a code for a rate system but when I select a vote, nothing change, when I reselect again a vote, it's ok ! BUT when I see my DB on phpmyadmin, the counter of vote has 1 clic in more than the counter of vote that I "echoed" on my page... why this difference of 1?
my note.js
$(function(){
$('.star').on('mouseover', function(){
var indice = $('.star').index(this);
$('.star').removeClass('full');
for(var i = 0; i<= indice; i++){
$('.star:eq('+i+')').addClass('full');
}
});
$('.star').on('mouseout', function(){
$('.star').removeClass('full');
});
var average = $('.average').attr('data-average');
function avaliacao(average){
average = (Number(average)*20);
$('.barra .bg').css('width', 0);
$('.barra .bg').animate({width: average+'%'}, 500);
}
avaliacao(average);
$('.star').on('click', function(){
var artigoId = $('.artigoDados').attr('data-id');
var ponto = $(this).attr('id');
location.reload();
$.post('sys/votar.php',{votar: 'sim', artigo: artigoId, ponto: ponto}, function(retorno){
avaliacao(retorno.average);
$('p.votos span').html(retorno.votos);
}, 'jSON');
});
});
My html code:
<?php
$bdd = new PDO('mysql:host=localhost;dbname=notation', 'root', 'root');
?>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/note.js"></script>
</head>
<body>
<?php
$artigoId = (int)$_GET['artigo'];
$artigos = $bdd->prepare('SELECT * FROM sys_note WHERE id_recette = ?');
$artigos->execute(array($artigoId));
while($row = $artigos->fetchObject()){
echo '<h1>'.$row->titre_recette.'</h1>';
$calculo = ($row->pontos == 0) ? 0 : round(($row->pontos/$row->votos), 1);
echo '<span class="average" data-average="'.$calculo.'"></span>';
echo '<span class="artigoDados" data-id="'.$row->id_recette.'"></span>';
?>
<div class="barra">
<span class="bg"></span>
<div class="estrelas">
<?php for($i=1; $i<=5; $i++): ?>
<span class ="star" id="<?php echo $i;?>">
<span class="starAbsolute"></span>
</span>
<?php endfor;?>
</div>
</div>
<p class="votos"><span><?php echo $row->votos;?></span>votes</p>
<?php }?>
</body>
</html>
votar.php
<?php
$bdd = new PDO('mysql:host=localhost;dbname=notation', 'root', 'root');
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$artigo = (int)$_POST['artigo'];
$pontos = $_POST['ponto'];
$pegaArtigo = $bdd->prepare('SELECT * FROM sys_note WHERE id_recette = ?');
$pegaArtigo->execute(array($artigo));
while($row = $pegaArtigo->fetchObject()){
$votosUpd = $row->votos+1;
$pontosUpd = $row->pontos+$pontos;
$average = round(($pontosUpd/$votosUpd), 1);
$update = $bdd->prepare('UPDATE sys_note SET votos = ?, pontos = ? WHERE id_recette = ?');
if($update->execute(array($votosUpd, $pontosUpd, $artigo))){
die(json_encode(array('average' => $average, 'votos' => $votosUpd)));
}
}
}
?>
You need to do location.reload(); after you the post, not before.
$.post('sys/votar.php',{votar: 'sim', artigo: artigoId, ponto: ponto}, function(retorno){
location.reload();
}, 'jSON');
There is no point to do the extra work inside the callback since you are reloading the page anyway.
Although, I would recommend you change the elements on the page via ajax instead of the crude location.reload();
I am making a product displaying page of an ecommerce website. The products are to be filtered by brands on the basis of brands that are checked by the customer. For this I have used an ajax request everytime a brand is checked. The problem is that the page cannot receive the get variables that i am sending to the same page. The ajax request is not giving any errors and also the chrome debugger side is also not showing any error at all. This is the page:
snapshot of the products page
And this is the code of the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<?php
session_start();
include('includes/pdo_connect.php');
include('includes/pdo_functions.php');
$logged_in;
$user_first_name;
if(isset($_SESSION['user'])){ //Determining if the user is logged in or not.
if($_SESSION['user']=='user'){
$user_id = $_SESSION['user_id'];
global $logged_in;
$logged_in = true;
global $user_first_name;
$user_first_name = $_SESSION['user_first_name'];
}
} else {
$_SESSION['user'] = 'guest';
$user_id = $_SERVER['REMOTE_ADDR'];
}
$cat;
if(isset($_GET['cat'])){
global $cat;
$cat = $_GET['cat'];
}
include('includes/logged_in.php');
if(isset($_GET['brand_list'])){
$brand_list = $_GET['brand_list'];
} else {
echo "<script>alert('value not received');</script>";
}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="styles/list_style.css?<?php echo time(); ?>">
<link rel="stylesheet" type="text/css" href="styles/thickbox.css" media="screen">
<script type="text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="js/thickbox.js"></script>
<?php
$where = array();
if(!empty($brand_list)){
echo "ajax working";
if(strpos($brand_list, ',')!==false){
$brand_choices = explode(',', $brand_list);
$barray = array();
foreach($brand_choices as $value) {
$barray[] = "brand_id = $value";
}
$where[] = '('.implode(' OR ', $barray).')';
} else {
$where[] = '(brand_id= '.$brand_list.')';
}
} else {
//echo "ajax not working ";
}
$w = implode(' AND ', $where);
$w = "where product_cat=$cat ".$w;
$filter_query = "select * from products $w ";
echo "filter query: ".$filter_query;
$first_load = 'filter';
function show_filtered(){
//echo "<script>alert('filter query working');</script>";
global $filter_query;
global $con;
global $brand_name;
try{
$stmt = $con->prepare($filter_query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $data) {
$product_id = $data['product_id'];
$product_cat = $data['product_cat'];
$product_brand = $data['product_brand'];
$product_title = $data['product_title'];
$product_price = $data['product_price'];
$product_desc = $data['product_desc'];
$product_image = $data['product_image'];
echo "
<div class='product_container $brand_name'>
<a href='details.php?pid=".$product_id."' alt='".$product_title."'>
<div class='img_div'>
<img src='admin/product_images/".$product_image."?".time()."' alt='".$product_title."'/>
</div>
<div class='index_product_desc'>".$product_title."</div>
<div class='index_product_price'>₹".$product_price."</div>
</a>
</div>
";
}
} catch(PDOException $e){
echo "Error in show_list(): ".$e->getMessage();
}
}
function show_brands(){
global $con;
global $cat;
global $brand_name;
try{
$query = "select * from cat_brand where cat_id = $cat";
$stmt = $con->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
//$brand = array();
foreach ($result as $data) {
$brand_id = $data['brand_id'];
//echo "<script>alert('$brand_id');</script>";
$query1 = "select * from brands where brand_id = $brand_id";
$stmt1 = $con->prepare($query1);
$stmt1->execute();
$result1 = $stmt1->fetchAll();
echo "<ul>";
foreach ($result1 as $data1) {
$brand_name = $data1['brand_title'];
echo "<li><input type='checkbox' value='$brand_id' id='$brand_name' class='brand_check' name='brandchoice'> $brand_name</li>";
}
echo "</ul>";
}
} catch(PDOException $e){
echo "Error in show_brands: ".$e->getMessage();
}
}
function show_price(){
}
?>
</head>
<body>
<div class="wrapper">
<header>
<div class="home_logo">
<a href="index.php">
<img src="images/skyshop_sumopaint.png" alt="Site Home">
</a>
</div>
<div class="login">
<?php user();?> |
<?php login_status(); ?>
</div>
<div class="form">
<form method="get" target="" name="searchbar_form">
<input type="text" name="searchbar" id="searchbar">
<input type="submit" id="search_button" value="Search">
</form>
</div>
</header>
<div class="menubar">
<div class="dropdown">
<button onclick="dropdownToggle()" class="dropdown-button">Shop By Category</button>
<ul class="dropdown-content" id="dropdownContent">
Categories
<?php getcats(); ?>
</ul>
</div>
<div class="menubar-div">
<ul class="menu-items">
<?php getcats(); ?>
</ul>
</div>
<div class="cart">
Cart (0)
</div>
</div>
<div class="content">
<div class="nav">
</div>
<div class="list_wrapper">
<!--/////////////////////////////////////////////// Filter div /////////////////////////////////////////////////////-->
<div class="filter">
<span class="filter_heading">Select Brands</span>
<a href="" class="clear" id="clear_brands">Clear<a>
<div class="brand_div">
<?php
show_brands();
?>
</div>
<div class="price_div">
</div>
</div>
<!--/////////////////////////////////////////////// List div ///////////////////////////////////////////////////////-->
<div class="list">
<div class="loading">
<img src="images/loadingAnimation.gif">
</div>
<?php
show_filtered();
?>
</div>
</div>
<div class="footer">
FOOTER
</div>
</div>
</div>
<?php
?>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
</script>
</body>
</html>
I am using alert() in the beforeSend in the ajax request and it returns the correct data as expected. But the PHP section of the page does not received the values. There are no errors on the PHP side or the browser debug window.
I checked your code line by line. and figure out that you have code for ajax inside the function named "filter" function filter().
Now you are calling this filter function on by onclick event of the element with id clear_brands
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
and by this code i came to know that at the end your ajax call is not being made because you click event was not triggered,
So either you should trigger this event on your document get ready or you have to do it by clicking on that element.
Just think about the flow once.
i was testing your script in my local and
with some modification i have made it working.
did some changes like
at the end of the script i just putted this code below.
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
And ajax call was executed..
check out my entire HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<a href="" class="clear" id="clear_brands">Clear<a>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
</script>
</body>
</html>
In Chrome do Ctrl+Shift+I to open Developer Tools and check Console for errors and Network tab to see if the data is passed in request.
In my code below I am trying to create a load more button using AJAX. I have main.php which includes PHP code for calling blogs from database initially, some jQuery code and a load more button. Then I have ajax_more.php which calls more data from database when load more is clicked. Load more buttons are displayed perfectly and when clicked they change to loading and then disappear. Nothing else happens and main.php still shows those two initial blogs which we call first. Please look into code and help where this code has gone wrong.
main.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.show_more', function () {
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: 'ajax_more.php',
data: 'id=' + ID,
success: function (html) {
$('#show_more_main' + ID).remove();
$('.columns').append(html);
}
});
});
});
</script>
<?php
$query = "
SELECT blogs_id, title, body, posted_by, full_name, bio, posted, category
FROM blogs
INNER JOIN categories
ON categories.category_id=blogs.category_id
WHERE category='cat1' OR category='catt2' OR category='cat3' OR category='cat4'
ORDER BY blogs_id desc
LIMIT 2
";
$result = mysqli_query($con,$query);
$rowCount = mysqli_num_rows($result);
if($rowCount > 0){
while ($row = mysqli_fetch_assoc($result)) {
$blogs_id = $row['blogs_id'];
$title = $row['title'];
$body = $row['body'];
$posted_by = $row['posted_by'];
$full_name = $row['full_name'];
$bio = $row['bio'];
$posted = $row['posted'];
echo "
<div class='db'>
<h2>$title</h2>
<p>$body</p>
<p>$bio</p>
</div>
";
?>
<div class="show_more_main" id="show_more_main<?php echo $blogs_id; ?>">
<span id="<?php echo $blogs_id; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading…</span></span>
</div>
ajax_more.php
<?php
if(isset($_POST["blogs_id"]) && !empty($_POST["blogs_id"])) {
$query = "
SELECT blogs_id, title, body, posted_by, full_name, bio, posted, category
FROM blogs
INNER JOIN categories ON categories.category_id=blogs.category_id
WHERE category='Entertainment' OR category='Politics' OR category='Sports' OR category='Travel'
AND blogs_id < ".$_POST['blogs_id']."
ORDER BY blogs_id DESC
LIMIT 2
";
$result = mysqli_query($con,$query);
$rowCount = mysqli_num_rows($result);
if($rowCount > 0){
while ($row = mysqli_fetch_assoc($result)) {
$blogs_id = $row['blogs_id'];
$title = $row['title'];
$body = $row['body'];
$posted_by = $row['posted_by'];
$full_name = $row['full_name'];
$bio = $row['bio'];
$posted = $row['posted'];
echo "
<div class='db'>
<h2>$title</h2>
<p>$body</p>
<p>$bio</p>
</div>
";
?>
You should change your query to this
$query = "SELECT blogs_id, title, body, posted_by, full_name, bio, posted, category FROM
blogs INNER JOIN categories ON categories.category_id=blogs.category_id WHERE
(category='Entertainment' OR category='Politics' OR category='Sports' OR category='Travel')
AND blogs_id < " . $_POST['blogs_id'] . " ORDER BY blogs_id DESC LIMIT 2";
All the OR's must be enclosed in the brackets....
You can follow below technique to load more data with just replacing morebox html.
blog.php
<div class="tutorial_list">
<!-- LOAD YOUR PHP BLOG DATA -->
<div class="loading"><img src="fb-load.gif"/></div>
<!-- More Button here $ID values is a last post id value. -->
<div id="show_more<?php echo $ID; ?>" class="morebox">
more
</div>
</div>
<script>
$(document).on('click', '.show_more', function() {
{
var ID = $(this).attr("id");
if (ID) {
$('.morebox').hide();
$('.loding').show();
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastpost=" + ID,
cache: false,
success: function(html) {
$('.loading').hide();
$('.tutorial_list').append(html);
$("#show_more" + ID).remove(); // removing old more button
}
});
} else {
$(".morebox").html('The End'); // no results
}
return false;
});
</script>
ajax_more.php
<!-- LOAD YOUR PHP BLOG DATA WITH lastpost ID and remember to add below code for load more -->
<!-- More Button here $ID values is a last post id value. -->
<div id="show_more<?php echo $ID; ?>" class="morebox">
more
</div>
(Just a heads up, its a Lengthy question but im sure its very basic question for a ajax-php coder)
Im trying to 'update db on some drag n drop event on one page' and 'reflect that change in other page without reload'. I have already written pretty much all the code, need your help in figuring out what is wrong. Here is the Html that I have written,
First_html_file:
<head>
<title>Coconuts into Gunnybags</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="coconuts" style="float:left">
<div class="coconut1" ondragover="allowDrop(event)" ondrop="drop(event)">
<img id="drag1" ondragstart="drag(event)" draggable="true" src="coconut.png">
</div>
<div class="coconut2" ondragover="allowDrop(event)" ondrop="drop(event)">
<img id="drag2" ondragstart="drag(event)" draggable="true" src="coconut.png">
</div>
</div>
<div class="gunnybag" style="float:right">
<div id="place1" ondragover="allowDrop(event)" ondrop="drop(event)"></div>
<div id="place2" ondragover="allowDrop(event)" ondrop="drop(event)"></div>
</div>
</body>
so there are 2 drag-able coconuts and there are 2 placeholders(place1 & place2). What I want to do is when the coconuts are dragged and placed on one of the placeholders, database's values should be updated. (say when a coconut is placed in 1st placeholder, place_id 1 - true, place_id 2 - false)
For this, I'm making ajax call to a php file from JS's drop function like this..
JS_file:
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("coconut");
ev.target.appendChild(document.getElementById(data));
var state = true;
var id = ev.target.id;
$.ajax({
url: "db_update.php", //calling db update file.
type: "POST",
data: { id: id, state: state }, //2 variables place_id and its state(True/False)
cache: false,
success: function (response) { //I dont know what to do on success. Can this be left blank like, success: ?
$('#text').html(response);
}
});
}
This is my db_update,
db_update:
<?php
$state = $_POST['state']; //getting my variables state 'n ID
$id = $_POST['id'];
function begin()
{
mysql_query("BEGIN");
}
function commit()
{
mysql_query("COMMIT");
}
$con=mysql_connect("sqlservername","myuname", "mypass") or die(mysql_error());
mysql_select_db("my_db", $con) or die(mysql_error());
$query = "UPDATE gunnybag SET state = '{$state}' where id='{$id}'"; //will this work? or am I doing something wrong here??
begin();
$result = mysql_query($query);
if($result)
{
commit();
echo "successful";
}
?>
On the receiving side I want to update the coconuts in the gunnybag without reloading the page, so I have written this ajax which uses db_fetch.php
ajx.js file:
window.onLoad = doAjax;
function doAjax(){
$.ajax({
url: "db_fetch.php",
dataType: "json",
success: function(json){
var dataArray = JSON.decode(json);
dataArray.each(function(entry){
var i=1;
if(entry.valueName==true){
$q('place'+i).css( "display","block" );
}
else{
$q('place'+i).css( "display","none" );
}
i=i++;
})
}
}).complete(function(){
setTimeout(function(){doAjax();}, 10000);
});
}
here is the db_fetch.php:
<?php
try{
$con=mysql_connect("sqlservername","myuname", "mypass") or die(mysql_error());
}
catch(Exception $e){
echo $e;
}
mysql_select_db("my_db", $con) or die(mysql_error());
$q = mysql_query("SELECT 'state' FROM 'gunnybag' "); //fetching all STATE from db
$query = mysql_query($q, $con);
$results = mysql_fetch_assoc($query);
echo json_encode($results); //making it JSON obj
?>
Finally my other page where this ajax is being called from.
Second_html_file:
<head>
<title>Coconuts into Gunnybags</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="ajx.js"></script>
//if i simply include the ajax script here will it be called
//automatically? i want this script to keep up with the changes in db.
</head>
<body>
<div class="gunnybag" style="float:right">
<div id="place1" style="display: ;"><img id="drag1" draggable="true" src="coconut.png"></div>
<div id="place2" style="display: ;"><img id="drag2" draggable="true" src="coconut.png"></div>
</div>
</body>
MAP:
First_html_file->JS_file->db_update :: Second_html_file->ajx.js->db_fetch.
Please point out what is wrong in this code, also respond to the //comments which are put along code.
Your response is much appreciated. Thanks! #help me get this right#
For ref I have hosted the files here, http://www.nagendra.0fees.net/admin.html & http://www.nagendra.0fees.net/cng.html
First thing I see is:
You say:
var id = event.target.id;
but you decalare ev in drop(ev)
so change that:
var id = event.target.id;
to:
var id = ev.target.id;
for starters.
Then you should use mysqli since mysql is deprecated:
Your code is also open for SQL-injections, so change:
$state = $_POST['state']; //getting my variables state 'n ID
$id = $_POST['id'];
to:
$state = ($_POST['state']) ? true : false;
$id = intval($_POST['id']); //make sure an integer