Can't Figure out Why JSON / JSONP Isn't Working - php

I have this PHP code:
JSON.php
<?php
$array = array('items' => 38);
$JSONItems = json_encode($array);
return $JSONItems;
?>
Items.html
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$.getJSON("http://domain.com/JSON.php?callback=?",
function(data){ alert(data.items) }
);
</script>
When Items.html is displayed no alert is fired, and nothing happens. (No Console Errors Or Anything)
Any idea what I'm doing wrong?

You're calling return in your PHP script. That doesn't do what you think it does.
you need to use echo

i just tried this and it works fine
<script type="text/javascript">
</script>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/json.php",
function(data){ alert(data.items) }
);
});
</script>
PHP
<?php
$array = array('items' => 38);
$JSONItems = json_encode($array);
print_r( $JSONItems ) ;
?>

Related

Take a value in php page sent with jquery function

In this html page at the begin of the script i send the value of variable fin at the php page (http://sat3.altervista.org/index.php?valore="+ fin). In this php page i tried to take the value of variable but i didn't have success. Someone can help me?
<!doctype html>
<html>
<head>
<title>Parsing</title>
<script type="text/javascript" src="jquery-2.1.0.min.js"></script>
</head>
<script>
var fin = "SAT000000002575";
url = "http://sat3.altervista.org/index.php?valore="+ fin,
data = {
get_param: 'value'
};
$.getJSON(url, data, function (data) {
for (var i = 0; i < data.length; i++) {
var lin = data[i]["Nr SAT"];
$('body').append($('<p>').html('Numero Sat: ' + data[i]["Nr SAT"] + ''));
$('body').append($('<p>').html('Data Apertura: ' + data[i]["Data Apertura"]));
}
});
</script>
<body>
<header>
</header>
</body>
</html>
This is the php page:
<?php
// Sopprimo gli errori del php
error_reporting(0);
// Includo la libreria
require_once 'excel_reader2.php';
$file_handle = fopen("leggimi2.csv", "r");
//EDIT: Define an array to hold individual lines
$data = array();
while (!feof($file_handle) ) {
//HERE I TAKE THE VALUE BUT IT DON'T CONTAIN NOTHING
$myValue = $_GET["valore"];
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[0] == $myValue)
{
$arr = array('Nr SAT' => $line_of_text[0],'Data Apertura' => $line_of_text[13], 'Tipo Servizio' => $line_of_text[1], 'Stato SAT' => $line_of_text[2],'Marca Terminale' => $line_of_text[4], 'Modello Terminale' => $line_of_text[5], 'IMEI guasto' => $line_of_text[6],'IMEI consegnato' => $line_of_text[7],'Famiglia guasto' => $line_of_text[8],'Descrizione guasto' => $line_of_text[9] );
//EDIT: Add the line to the array
$data[] = $arr;
}
}
//EDIT: Encode the array as a JSON array of line objects
echo json_encode($data);
//$myValue = isset($_GET['myValue']) ? $_GET['myValue'] : '';
fclose($file_handle);
?>
jQuery reference here http://api.jquery.com/jQuery.getJSON/ says that
second argument is "A plain object or string that is sent to the server with the request."
Try this:
<script type="text/javascript">
var fin = "SAT000000002575",
url = "http://sat3.altervista.org/index.php",
getVars = {
valore : fin
};
$.getJSON(url, getVars, function(data) {
// rest of your code
});
</script>
And let us know :)
EDIT
Regarding your PHP code, you have to put this $myValue = $_GET["valore"]; before your while begins.

Get php boolean value with javascript

I want to get php booelan value with javascript.
That is my code.
<script type="text/javascript">
var $j = jQuery.noConflict();
var isValue = $j(<?php isset($getResult[]); ?>);
alert(isValue);
</script>
php is a server side programming, and javascript is client side. so you need to "echo" the php value to get result on javascript
var isValue = $j(<?php echo isset($getResult[]) ? "true" : "false"; ?>);
You'll have to convert the boolean result of isset() into a string representation of 'true' or 'false' so that it can be understood by the javascript parser. Like this:
var isValue = $j(<?php isset($getResult[]) ? echo 'true' : echo 'false'; ?>);
It should be like this
<script type="text/javascript">
var $j = jQuery.noConflict();
var isValue = $j(<?php if (isset($getResult)){ echo true;} else {echo false;} ?>);
alert(isValue);
</script>
You cannot use $getResult[] for reading using issest. It will return fatal error or you have to specify some index in the array.
If you want to check if it is an array then you can use :
<script type="text/javascript">
var $j = jQuery.noConflict();
var isValue = $j(<?php if (isset($getResult) && is_array($getResult)){ echo true;} else {echo false;} ?>);
alert(isValue);
</script>

Antibot with PHP and JQuery Ajax

I am building a simple antibot for my email form.
This is a code which makes a problem:
<?php
session_start();
$a = rand(1, 10);
$b = rand(1, 10);
$antibot = $a + $b;
$_SESSION["antibot"] = $antibot;
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("#sendEmail").click(function(){
var antibot = $("#antibot").val();
$.post(
"test.php",
{antibot: antibot},
function(data){
alert(data.info);
},
"json"
);
);
);
);
</script>
</head>
<body>
<table>
<tr><td>AntiBot: <?php echo $a . ' + ' . $b;?> = </td><td><input type='text' id='antibot' /></td></tr>
<tr><td colspan='2'><input type='button' id='sendEmail' value='Send'/></td></tr>
</table>
</body>
</html>
And my test.php
<?php
session_start();
$antibot = $_POST["antibot"];
$data = array();
if(isset($_SESSION["antibot"])){
if($_SESSION["antibot"] == $antibot){
$data["info"] = "Session is isset and answer is right!";
}
else{
$data["info"] = "Session is isset but answer is NOT right!";
}
}
else{
$data["info"] = "Session is NOT isset!";
}
echo json_encode($data);
?>
I constantly get this info: "Session is isset but answer is NOT right!"
If you can see $_SESSION["antibot"] in test.php is setted but value is "" no matter what I type in input field #antibot!
I do not understand why this is happening, please can someone tell me where the problem is and how can I fix it?
I tested this code here:
http://onlinephpfunctions.com/stackoverflow/11981309/
And it seems completely valid.
I had to make some modifications to your javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#sendEmail").click(function(){
var antibot = $("#antibot").val();
$.post(
"test.php",
{antibot: antibot},
function(data){
alert(data.info);
},
"json"
)
})
})
</script>
After that it was working fine. It may just be some problems with cookies in your browser, or an error in your PHP config so sessions wont be stored right. Please check this, your code works OK, as you can see in the demo.

Jquery Autocomplete with PHP

I have been messing with this for too long trying to get it to work. Can anyone please see if you have any pointers.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="autocomplete.css" />
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<style>
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script>
$(function() {
$( "#materials" ).autocomplete({
source: "autocomplete.php",
minLength: 2
});
});
</script>
<div class="demo">
<div class="ui-widget">
<label for="materials">Materials: </label>
<input id="materials" />
</div>
</div><!-- End demo -->
</body>
</html>
and the php file is
require_once "db_con.php"; // Database connection, I know this works.
$q = strtolower($_GET["q"]);
if (!$q)
return;
$sql = "SELECT * FROM materials WHERE name LIKE '%$q%'";
$rsd = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
while ($rs = mysqli_fetch_array($rsd)) {
$cname = $rs['name']; // I know this all returns correctly
echo json_encode($cname); // First time I have ever used json, error might be here.
}
I am trying to have a webpage with an autocomplete powered by Jquery that is supplied data from mysql using PHP. Simples. Only its not working...
Anyone have any ideas what I am missing ?
Regards
---- EDIT ----
In order to check this was working I completed the following:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="autocomplete.css" />
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<style>
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script>
$(function() {
$( "#materials" ).autocomplete({
source: <?php
include_once 'db_con.php';
$sql = "SELECT name FROM materials";
$rsd = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
echo '[';
while ($rs = mysqli_fetch_array($rsd)) {
echo "'" . $rs['name'] . "', "; //add results to array
}
echo ']';
?>,
minLength: 2
});
});
</script>
<div class="demo">
<div class="ui-widget">
<label for="materials">Materials: </label>
<input id="materials" />
</div>
</div><!-- End demo -->
</body>
</html>
Which works perfectly. So good infact I think im going to keep this code not quite how its supposed to work but...
Try this code, Its works for me
$().ready(function() {
$("#materials").autocomplete("autocomplete.php", {
width: 260,
matchContains: true,
autoFill:true,
selectFirst: false
});
});
In the PHP part, maybe try something like that:
$res = array(); //create a new array
while ($rs = mysqli_fetch_array($rsd)) {
$res[] = (string)$rs['name']; //add results to array, casted as string
}
header('Content-type: application/json'); //add JSON headers (might work w/o)
echo json_encode($res); //output array as JSON
...that way you should have all results in one array like
['name1', 'name2', 'name3']
Your PHP is all wrong:
while ($rs = mysqli_fetch_array($rsd)) {
$cname = $rs['name']; // I know this all returns correctly
echo json_encode($cname); // First time I have ever used json, error might be here.
}
Should be:
$cname = array();
while ($rs = mysqli_fetch_array($rsd)) {
$cname[]['label'] = $rs['name']; // I know this all returns correctly
break;
}
echo json_encode($cname); // First time I have ever used json, error might be here.
label is the default label field within an array row that is used by jqueryautocomplete (I believe). Also the return must be an array of arrays each array row representing a match.
You can make it more complicated by adding a value field for what to make the textbox to actually equal to by doing:
$cname = array();
while ($rs = mysqli_fetch_array($rsd)) {
$cname[]['label'] = $rs['name']; // I know this all returns correctly
$cname[]['value'] = $rs['id'];
break;
}
echo json_encode($cname); // First time I have ever used json, error might be here.
Of course I don't think your actually wanting the break; I put this in because:
while ($rs = mysqli_fetch_array($rsd)) {
$cname = $rs['name']; // I know this all returns correctly
echo json_encode($cname); // First time I have ever used json, error might be here.
}
Denotes to me that you are actually returning a single row from your results. If you are not and are actually returning all results then take the break; out.
to handle a json answer from a php ajax call i customize the source function and handle the result myself this way:
$(function() {
$( "#materials" ).autocomplete({
source: function(request, response){
$.post("autocomplete.php", {
term: request.term
}, function(data){
if (data.length == 0) {
data.push({
label: "No result found",
});
}
response($.map(data, function(item){
return {
label: item.name,
value: item.name
}
}))
}, "json");
},
minLength: 2,
dataType : "json"});
});

Jquery autosuggest not working

Hey guys, I'm using jQuery's autosuggest plugin by using php to get the data. But it doesn't seem to work since I always get: No Results Found, even though I'm sure there are results:
Here's the php code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$input = mysql_escape_string($_GET["q"]);
$data = array();
$mysql=mysql_connect('localhost','***','***');
mysql_select_db('jmtdy');
$query = mysql_query("SELECT * FROM users WHERE username LIKE '%".$input."%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
And the script:
<script >
$(document).ready(function () {
$("#suggestedfriend").autoSuggest("suggestedf.php");
});
</script>
<script >
$(document).ready(function () {
$("#suggestedfriend").autoSuggest(
"suggestedf.php",
{
selectedValuesProp: "value",
selectedItemProp: "name",
searchObjProps: "name"
});
});
</script>
Add the above parameters, it will start to work :)
Just look at data, that server sends you back. If you use firefox you can watch it in network tab of firebug, or if you use chrome see it in resources.
The header must be in top of the file, right after the
<?php
header('Content-type: application/json');
include_once 'resources/dbconn.php';
$term = $_REQUEST['term'];
$query = "SELECT * FROM cds WHERE titel LIKE '%$term%'";
$result = $mysqli->query($query);
$arr = array();
while ($obj = $result->fetch_array()) {
$arr[] = $obj;
}
//for jsonp echo '('.json_encode($arr).')';
echo json_encode($arr);
?>
The JS/jQuery string
<script type="text/javascript">
$(function() {
var cache = {},
lastXhr;
$("#exercise").autocomplete({
minLength: 2,
source: function(request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.getJSON("json_Search.php", request, function(data,status,xhr) {
cache[term] = data;
if (xhr === lastXhr) {
response(data);
}
});
}
});
});
</script>

Categories