location.reload() make a difference with my DB - php

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();

Related

SEE server not working with join room at screen sharing RTCMultiConnection

I am creating screen share with SEE server, everything is working properly
when the user opens a room for screen share he enters a room
But when the second user wants to turn it on room nothing happens
I checked and error gives no room found
How I can resolve that?
(i test script with socket.io server it's working properly)
my front end code :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>SSE+PHP Signaling using RTCMultiConnection</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<link rel="shortcut icon" href="logo.png">
<link rel="stylesheet" href="stylesheet.css">
<script src="menu.js"></script>
</head>
<body>
<header>
<a class="logo" href="/"><img src="logo.png" alt="RTCMultiConnection"></a>
Menu<img src="menu-icon.png" alt="Menu">
<nav>
<li>
Home
</li>
<li>
Demos
</li>
<li>
Getting Started
</li>
<li>
FAQ
</li>
<li>
YouTube
</li>
<li>
Wiki
</li>
<li>
Github
</li>
</nav>
</header>
<h1>
SSE+PHP Signaling using RTCMultiConnection
<p class="no-mobile">This demo is using SSE (Server Sent Events) to setup WebRTC one-to-one connection. Check PHP Source Codes</p>
</h1>
<section class="make-center">
<input type="text" id="room-id" value="abcdef" autocorrect=off autocapitalize=off size=20>
<button id="open-room">Open Room</button>
<button id="join-room">Join Room</button>
<button id="open-or-join-room">Open or Join Room</button>
<div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div>
<div id="videos-container"></div>
</section>
<script src="adapter.js"></script>
<script src="RTCMultiConnection.js"></script>
<script src="SSEConnection.js"></script>
<link rel="stylesheet" href="getHTMLMediaElement.css">
<script src="getHTMLMediaElement.js"></script>
<script>
window.enableAdapter = true; // enable adapter.js
// ......................................................
// .......................UI Code........................
// ......................................................
document.getElementById('open-room').onclick = function() {
disableInputButtons();
connection.open(document.getElementById('room-id').value, function() {
showRoomURL(connection.sessionid);
});
};
document.getElementById('join-room').onclick = function() {
disableInputButtons();
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: false,
OfferToReceiveVideo: true
};
console.log(document.getElementById('room-id').value);
connection.join(document.getElementById('room-id').value);
};
document.getElementById('open-or-join-room').onclick = function() {
disableInputButtons();
// connection.openOrJoin(document.getElementById('room-id').value);
connection.checkPresence(document.getElementById('room-id').value, function(isRoomExist, roomid) {
console.info('checkPresence', isRoomExist, roomid);
if(isRoomExist) {
connection.join(roomid);
}
else {
connection.open(roomid);
}
});
};
// ......................................................
// ..................RTCMultiConnection Code.............
// ......................................................
var connection = new RTCMultiConnection();
// Using SSE (Server Sent Events) for signaling
connection.socketURL = 'https://127.0.0.1/see/';
connection.setCustomSocketHandler(SSEConnection);
connection.session = {
screen: true,
oneway: true
};
connection.sdpConstraints.mandatory = {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
};
// https://www.rtcmulticonnection.org/docs/iceServers/
// use your own TURN-server here!
connection.iceServers = [{
'urls': [
'stun:stun.l.google.com:19302',
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
'stun:stun.l.google.com:19302?transport=udp',
]
}];
connection.videosContainer = document.getElementById('videos-container');
connection.onstream = function(event) {
event.mediaElement.id = event.streamid;
connection.videosContainer.appendChild(event.mediaElement);
if (event.type === 'remote') {
connection.socket.close(); // release SSE connection
}
};
connection.onstreamended = function(event) {
var mediaElement = document.getElementById(event.streamid);
if (mediaElement && mediaElement.parentNode) {
mediaElement.parentNode.removeChild(mediaElement);
}
};
function disableInputButtons() {
document.getElementById('open-room').disabled = true;
document.getElementById('join-room').disabled = true;
document.getElementById('open-or-join-room').disabled = true;
document.getElementById('room-id').disabled = true;
}
// ......................................................
// ......................Handling Room-ID................
// ......................................................
function showRoomURL(roomid) {
var roomHashURL = '#' + roomid;
var roomQueryStringURL = '?roomid=' + roomid;
var html = '<h2>Unique URL for your room:</h2><br>';
html += 'Hash URL: ' + roomHashURL + '';
html += '<br>';
html += 'QueryString URL: ' + roomQueryStringURL + '';
var roomURLsDiv = document.getElementById('room-urls');
roomURLsDiv.innerHTML = html;
roomURLsDiv.style.display = 'block';
}
(function() {
var params = {},
r = /([^&=]+)=?([^&]*)/g;
function d(s) {
return decodeURIComponent(s.replace(/\+/g, ' '));
}
var match, search = window.location.search;
while (match = r.exec(search.substring(1)))
params[d(match[1])] = d(match[2]);
window.params = params;
})();
var roomid = '';
if (localStorage.getItem(connection.socketMessageEvent)) {
roomid = localStorage.getItem(connection.socketMessageEvent);
} else {
roomid = connection.token();
}
document.getElementById('room-id').value = roomid;
document.getElementById('room-id').onkeyup = function() {
localStorage.setItem(connection.socketMessageEvent, this.value);
};
var hashString = location.hash.replace('#', '');
if (hashString.length && hashString.indexOf('comment-') == 0) {
hashString = '';
}
var roomid = params.roomid;
if (!roomid && hashString.length) {
roomid = hashString;
}
if (roomid && roomid.length) {
document.getElementById('room-id').value = roomid;
localStorage.setItem(connection.socketMessageEvent, roomid);
// auto-join-room
connection.join(roomid);
disableInputButtons();
}
</script>
<footer>
<small id="send-message"></small>
</footer>
</body>
</html>
PHP side :
https://github.com/muaz-khan/RTCMultiConnection/tree/master/demos/SSEConnection

Deleted rows removed from page but not from mysql database (PHP/jQuery)

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 . '"');

My jquery doesn't update automatically my page

I realized a code for a rate system with five hearts. I would like, when I chose the value of my vote, that the system actualize the average because I must update the page for it.. It must be automatic with my code ... where did I wrong?
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)));
}
}
}
?>

Ajax request to the same PHP page gives no errors but doesn't work

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.

PHP "Error: parsererror" trying to use search API with result list

Hello stackoverflow,
I am trying to make a search function to search events on a Search API.
The API can be viewed here: http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=opera this is the output XML if you search on the word "opera".
I'm still quite a noob at PHP so i"m having a hard time. I used this tutorial/example as help:http://designm.ag/tutorials/deviantart-api-instant-search-app-using-ajax-php/
So I built my code and I ended up getting the error "Error: parsererror" every time I type in a keyword in the text area. Can anyone help me fix this please?
Here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Culture Reminder</title>
<!-- Stylesheets -->
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
<!-- Scripts -->
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<!-- <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> -->
<script type="text/javascript" src="uitdatabase.js"></script>
<!-- HTML5 Shiv -->
    <!--[if lt IE 9]>
            <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>
<header>
<h1>Search events</h1>
</header><!-- /header -->
<div id="container">
<div id="searchform">
<h2>Search for culture</h2>
<input id="s" name="s" placeholder="Type in keyword(s)" size="30" type="text" />
</div><!-- /searchform -->
<center id="loader"><img src="images/loader.gif" alt="loading..."></center>
<div id="content">
</div><!-- /content -->
</div><!-- /container -->
<div id="footer">
<div id="nav">
<img src="images/searchbutton.gif" />
<img src="images/mylistbutton.gif" />
<img src="images/settingsbutton.gif" />
</div>
</div><!-- /footer -->
</body>
</html>
Here is the Javascript file:
$(document).ready(function(){
var s = $("#s");
var wrap = $("#content");
var delay = 1500;
var keycode;
var timer;
$(s).keydown(function(e){
// clear old page content and reset timer
$(wrap).empty();
clearTimeout(timer);
});
$(s).keyup(function(){
$("#loader").css("display", "block");
timer = setTimeout(startSearch, delay); // end timeout() function
}); // end keyup() event function
function startSearch() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: "q="+$(s).val(),
success: function(data){
// hide the loader and blur focus away from input
$("#loader").css("display", "none");
$(s).blur();
var code = "<span class=\"results\">Total Results: "+data['total']+"</span>";
$.each(data, function(i, item) {
if(typeof(data[i].title) !== 'undefined') { // check if data is undefined before setting more variables
code = code + '<div class="listing clearfix"><header><h3>'+data[i].title+'</h3><span class="userdata"><span class="date">'+data[i].calendarsummary+'</span>'+'<span class="location">' + data[i].location+'</span>'+'<span class="description">'+ data[i].shortdescription+'</span></span></header></div>';
code = code + '<img src="'+data[i].thumbnail+'" class="thumbnail">';
}
});
$(wrap).html(code);
},
error: function(xhr, type, exception) {
$("#loader").css("display", "none");
$(wrap).html("Error: " + type);
}
}); // end ajax call
}
}); // end ready() function
And here is my ajax.php code:
<?php
header('Content-Type: application/json');
$query = urlencode(stripslashes($_POST['q']));
$keywords = $query;
$xmlurl = "http://http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=".$keywords;
$xmlrss = file_get_contents($xmlurl);
$xmlrss = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xmlrss);
$object = simplexml_load_string($xmlrss);
// setup return array
$return = array();
$i = 0;
// get total number of results, max 60
$total = count($object->list->item);
$return["total"] = $total;
foreach($object->list->item as $item) {
$title = (string) $item->title;
$date = (string) $item->calendarsummary; //url
$loc = (string) $item->location; // authorname
$desc = (string) $item->shortdescription;//authorpic
$thumburl = (string) $item->thumbnail;//authorpic
// configure array data for each item
$return[$i]["title"] = $title;
$return[$i]["calendarsummary"] = $date;
$return[$i]["location"] = $loc;
$return[$i]["shortdescription"] = $desc;
$return[$i]["thumbnail"] = $thumburl;
$i++;
}
$json = json_encode($return);
die($json);
?>
If anyone could help me I would be so grateful. This is a project for school and I'm still learning basic PHP.
Try this code
<?php
header('Content-Type: application/json');
if(isset($_POST['q']))
{
$query = urlencode(stripslashes($_POST['q']));
$keywords = $query;
$xmlurl = "http://build.uitdatabank.be/api/events/search?key=AEBA59E1-F80E-4EE2-AE7E-CEDD6A589CA9&q=".$keywords;
$xmlrss = file_get_contents($xmlurl);
$xmlrss = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xmlrss);
$object = simplexml_load_string($xmlrss);
// setup return array
$return = array();
$i = 0;
if(isset($object->list->item))
{
// get total number of results, max 60
$total = count($object->list->item);
$return["total"] = $total;
if($total>0)
{
foreach($object->list->item as $item) {
$title = (string) $item->title;
$date = (string) $item->calendarsummary; //url
$loc = (string) $item->location; // authorname
$desc = (string) $item->shortdescription;//authorpic
$thumburl = (string) $item->thumbnail;//authorpic
// configure array data for each item
$return[$i]["title"] = $title;
$return[$i]["calendarsummary"] = $date;
$return[$i]["location"] = $loc;
$return[$i]["shortdescription"] = $desc;
$return[$i]["thumbnail"] = $thumburl;
$i++;
}
$json = json_encode($return);
die($json);
}else{
//count is empty
}
}else{
//object is not ready
}
}else{
//no post data found
}

Categories