jQuery json/jsonp does not fetch items on php server - javascript

I have a web service written in php but I could not fetch data with jquery getJSON().
It's my web service and works fine.
<?php
include 'config.php';
$sql = "select s.id, s.title, s.content, s.date, s.confirm " .
"from sap s";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$sapList = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
header('Content-Type: application/json; charset=UTF8');
$data = array('items'=>$sapList);
echo json_encode($data,JSON_UNESCAPED_UNICODE);
//echo '{"items":'. json_encode($sapList,JSON_UNESCAPED_UNICODE) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
I am trying to develop a jQuery mobile app.and source codes:event.js I used for loop in event.js.because I want to pull data from multiple separate services.
var db=openDatabase('servicesDB','1.0','servcesdatabase', 2*1024*1024);
tablo();
var olaylar;
$('#eventListPage').bind('pageinit', function(event) {
console.log("geteventlist fonksiyon running");
getEventList();
});
function getEventList() {
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM services',[],function (tx,sonuc) {
var toplam=sonuc.rows.length;
var kayit="";
var id="";
var ad="";
var url="";
$('#olaylar li').remove();
for (var i=0;i < toplam; i++) {
kayit=sonuc.rows.item(i);
id=kayit.id;
ad=kayit.ad;
url=kayit.url;
$.getJSON(url+'?callback=?', function(data) {
olaylar = data.items;
$.each(olaylar, function(index, olay) {
/*var confirm="";
switch(olay.confirm){
case 0:
confirm="accept";
break;
case 1:
confirm="wait";
break;
case 2:
confirm="reject";
break;
}*/
$('#olaylar').append(
'<li><a href="eventDetails.html?id=' + olay.id + '">' +
'<img src="pics/mr.jpg"/>' +
'<h4>' + olay.title + '</h4>' +
'<p>' + olay.confirm + '</p>' +
'</a></li>');
});
$('#olaylar').listview('refresh');
alert("getjsondan cikti");
});
}
}, hata);
});
}
function tablo(){
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS services('
+'id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,'
+'ad VARCHAR(25) NOT NULL, url VARCHAR(100) NOT NULL)');
});
}
function hata(transaction, err){
alert("Hata oldu : "+err.message);
return false;
}
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Personel Listesi</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="css/styles.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.4.3.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.4.3.min.css" />
</head>
<body>
<div id="eventListPage" data-role="page">
<div data-role="header" data-position="fixed">
<h1>Event List</h1>
</div>
<div data-role="content">
<ul id="olaylar" data-role="listview" data-filter="true"></ul>
</div>
</div>
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/jquery.mobile-1.4.3.min.js"></script>
<script src="js/events.js"></script>
<script src="js/eventDetails.js"></script>
</body>
</html>
I tried $.getJSON(...){ alert("in getjson"); but that does not work. this alert.getjson function does not work. But it works very well before, now the getjson function returns blank as if no data has been retrieved.. I need your help,thanks!

I am little doubt about '{"items":'. json_encode($sapList,JSON_UNESCAPED_UNICODE) .'}'. I am not sure whether the above piece of code frame proper json.
The better way is create your JSON structure in PHP associate array itself and then generate the JSON in single stroke like as follows,
<?php
// Some code
$data = array('item'=>$sapList);
echo json_encode($sapList);
?>
Note: Since I haven't tested my code and it is GET request, you can test your code by directly type the URL in browsers address-bar. And copy and paste printed code in chrome's console and validate them in Javascript.
OR
Use online JSON validator like http://jsonlint.com/

Related

Make a pagination using JQuery after getting data from api.php

Here is my codes-
client.php
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style>
#show{
background:red;
}
</style>
</head>
<body>
<?php
<div id="show"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('api.php')
});
});
</script>
</body>
</html>
api.php
<?php
$conn = new mysqli('localhost', 'root', '', 'ajax01');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT name FROM variables");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['name'] . '<br>';
}
}
?>
These codes are giving me the results like-
Result of above codes
I am getting the values from database and it is fetching all the data. Therefore, I need a pagination with these value. Need help.
Based on your comments,
I want a pagination that will show only one value and next page will show another...second result will show after click on next>
There are few things you need to consider here,
Instead of setInterval() and load() functions, simply use an AJAX request to implement your pagination functionality
Use prepared statements because that will help you in preventing SQL injection. Also, read about how you can prevent SQL injection in PHP.
Based on these above points and your below comments, the solution would be like this:
client.php:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style>
#show{
background:red;
}
</style>
</head>
<body>
<div id="show">
<?php
$conn = new mysqli('localhost', 'root', '', 'ajax01');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
// prepare query statement
if($stmt = $conn->prepare("SELECT name FROM variables LIMIT 0, 1")){
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($name);
// fetch values
$stmt->fetch();
// display name and pagination link
if(isset($name) && !empty($name)){
echo $name . '<br />';
?>
<div id='link-div' style='background-color:#ffffff'>
<a href='' class='showmore' id='1'>Next »</a>
</div>
<?php
}
// close statement
$stmt->close();
}
?>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click','.showmore',function(event){
event.preventDefault();
var offset = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'api.php',
cache: 'false',
data: {offset: offset},
beforeSend: function(){
$('#link-div').html('<span>Loading...</span>');
},
success: function(data){
$('#link-div').remove();
$('#show').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
// error
}
});
});
});
</script>
</body>
</html>
api.php:
<?php
if(isset($_POST['offset'])){
$offset = $_POST['offset'];
$prev = $offset - 1; // Previous link in the pagination series
$next = $offset + 1; // Next link in the pagination series
$conn = new mysqli('localhost', 'root', '', 'ajax01');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
// prepare query statement
if($stmt = $conn->prepare("SELECT COUNT(name) FROM variables")){
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($total_rows);
// fetch values
$stmt->fetch();
// close statement
$stmt->close();
}
// prepare query statement
if($stmt = $conn->prepare("SELECT name FROM variables LIMIT ?, 1")){
// bind parameter
$stmt->bind_param('i', $offset);
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($name);
// fetch values
$stmt->fetch();
// display name and pagination link
if(isset($name) && !empty($name)){
echo $name . '<br />';
?>
<div id='link-div' style='background-color:#ffffff'>
<?php
if($offset > 0){
?>
<a href='' class='showmore' id='<?php echo $prev; ?>'>«Prev </a>
<?php
}
if($offset < $total_rows - 1){
?>
<a href='' class='showmore' id='<?php echo $next; ?>'>Next »</a>
<?php
}
?>
</div>
<?php
}
// close statement
$stmt->close();
}
}
?>

Ajax request working but no output

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;
}
}

bootstrap typeahead is not fetching results

i am trying to autocomplete using bootstrap typeahead but its not fetching results.
i tried many times using jquery,ajax
index.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="typeahead.js"></script>
<script>
$(function() {
$('#typeahead').typeahead({
source:function(typeahead,query)
{
$.ajax({
url :'mysql.php',
type :'POST',
data :'query=' + query,
dataType :'json',
async :false,
success:function(data)
{
typeahead.process(data);
}
});
}
});
});
</script>
</head>
<body>
<input type="text" name="term" id="typeahead" class="form-control" size="50" placeholder="Search" >
</body>
</html>
mysql.php
<?php
$conn = mysqli_connect('localhost', 'root','','mydb');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$searchTerm = $_POST['query'];
$query = mysqli_query($conn,"SELECT * FROM content_ref_table WHERE title LIKE '%{$searchTerm}%' ORDER BY title ASC");
while ($row = mysqli_fetch_assoc($query)) {
$data[] = $row['title'];
}
echo json_encode($data);
?>
i am using typeahead along with ajax call,but its not giving results
I believe you are using bootstrap3-typeahead / or another bootstrap 2.x typeahead deriviation? If so, you have messed up the arguments for the source method - it should be process, query where process is the async callback. Your code could be reduced to
$('#typeahead').typeahead({
source: function(query, process) {
var url = 'mysql.php?query=' + query
return $.get(url, {}, function(data) {
return process(data)
})
}
})

Run a php update file from javascript

I am trying to run a update to mysql when a link in a table is clicked.
For this I have made 3 files:
movies.php
<html>
<head>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<script src="video.js" type="text/javascript"></script>
</head>
<?php
include 'combo_new.php';
include 'config.php';
include 'opendb.php';
$ndate = $_POST['ndate'];
$result = mysql_query("SELECT *
FROM DayMovie
WHERE FileDate LIKE '$ndate%' ORDER BY FileDate DESC")
or die(mysql_error());
echo "<table border='0'>";
echo "<tr> <th>Dato</th><th>Visninger</th><th>Handling</th></tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo date('d.m.Y', strtotime($row['FileDate']));
echo "</td><td>";
echo $row['Counter'];
echo "</td><td>";
echo "<a href='alldaymovies/{$row['FileName']}' onclick='playVideo(this.href, {$row['FileName']});' onkeypress='playVideo(this.href, {$row['FileName']});'>Se film</a>";
echo "</td></tr>";
}
echo "</table>";
include 'closedb.php';
?>
</html>
video.js
function playVideo(filename)
{
$.post( "update.php" {"filename":filename},
function( data ) {
alert( "Data Loaded: " + data );
});
}
update.php
<?php
include 'config.php';
include 'opendb.php';
$filename = $_POST['filename'];
$result = mysql_query("UPDATE DayMovie SET Counter=Counter+1 WHERE FileName='$filename'")
or die(mysql_error());
include 'closedb.php';
?>
However theres something not correct here... Can anyone see where I am going wrong?
The problem is probably that your user is already redirect to the other page before the call to update.php got finished. Keep in mind that if you redirect the browser to another page that request that are busy get cancelled.
To test if this is really the problem try to replace the href of the "a" element with "#".
And change your playVideo function to look like this:
function playVideo(filename)
{
$.post( "update.php" {"filename":filename},
function( data ) {
alert( "Data Loaded: " + data );
setTimeout(function(){ document.location.href="alldaymovies/" + filename;}, 300);
});
}

dynamic dropdown based on autocomplete value

I am trying to populate a dynamic dropdown list based on the value user has inserted in the previous textbox(auto-complete). So, when user insert an actor/actress name in the auto-complete textbox, a dropdown will be populated by list of movies in which that actor has played.
Problem:
Could someone kindly let me know what is the problem with this code and why it populate an empty dropdown?
Here is the html/js code:
<html>
<?php
print_r($_POST);
?>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
</head>
<body>
Source:
<input type="textbox" name= "tag" id="tags">
<select id="movieImdbId" name="movieImdbId[]" multiple="multiple" width="200px" size="10px" style=display:none;>
</select>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
select: function (event, ui){
$("#tags").change(function () {
var selectedVal = $(this).val(); //this will be your selected value from autocomplete
// Here goes your ajax call.
$.post("actions.php", {q: selectedVal}, function (response){
// response variable above will contain the option tags. Simply put in the dropdown.
$("#movieImdbId").html(response).show();
});
});
}
});
});
</script>
</body>
</html>
and this is actions.php code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['q']) && !empty($_POST['q'])){
$q = $_POST['q'];
$html = "";
try{
$conn = new PDO('mysql:host=localhost;dbname=imdb;charset=utf8mb4','user','pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = $conn->prepare("SELECT DISTINCT movieImdbId FROM movie_roleNames WHERE castName = :q");
$sql->execute(array(':q' => $_POST['q']));
while($rows = $sql->fetch(PDO::FETCH_OBJ)){
$option = '<option value="' . $rows['movieImdbId'] . '">' . $rows['movieImdbId'] . '</option>';
}
$html .= $option;
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
echo $html; // <-- this $html will end up receiving inside that `response` variable in the `$.post` ajax call.
exit;
}
?>
I really appreciate if someone can help me fix it.
Thanks.
You call via POST
$.post("actions.php")
but check for GET Variables
if(isset($_GET['q']) && !empty($_GET['q']))
So i guess your php script delivers an empty string.
Print the response to console and see if you get a result.

Categories

Resources