I am learning Javascript and have been following a tutorial on coding an autofill search box. I have got so far but am now stuck on parsing some JSON code. The JSON code is the result of a PHP SELECT from my database.
The JSON result looks like the below.
["Leeds","Leicester"]
According to JSONLint it is valid JSON code.
However when I run the snippet of code below I get a script 1014 Invalid Character at the jQuery.parseJSON line...................I know its something to do with the fact that my JSON code is not an object but cannot work out what to do. I even tried stringify on the data before parsing but that did not work either
................other code
$.get("No1PHPfile.php",{keyword:keyword})
.done(function(data) {
console.log(data);
var results=jQuery.parseJSON(data);
console.log(results);
...................other code
EDIT
Two sets of PHP Files
No. 1
<?php
require('..........sqldatabase.php');
require('.........selectdatabasecode.php');
if(!isset($_GET['keyword'])) {
die();
}
$keyword=$_GET['keyword'];
$data=searchForKeyword($keyword);
echo json_encode($data);
?>
No. 2
<?php
function getDbconnection() {
$db=new PDO(DB_DRIVER.":dbname=".DB_DATABASE.";host=".DB_SERVER.";charset=utf8",DB_USER,DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $db;
}
function searchForKeyword($keyword) {
$db=getDbconnection();
$stmt=$db->prepare("SELECT stationlong FROM `station` WHERE stationlong LIKE ? ORDER BY stationlong ");
$keyword=$keyword.'%';
$stmt->bindParam(1,$keyword,PDO::PARAM_STR,100);
$isQueryOk=$stmt->execute();
$results=array();
if ($isQueryOk) {
$results=$stmt->fetchAll(PDO::FETCH_COLUMN);
} else {
trigger_error('Error Executing Staement.',E_USER_ERROR);
}
$db=null;
return $results;
}
?>
something like
$result = json_encode ($data_i_want_to_send);
header('Content-type: application/json');
echo $result;
may help
UPD
Yes. i'm sclerotic((
Try
$data=searchForKeyword($keyword);
$data=array ('data' => $data); // so you send OBJECT anyway
$data=json_encode($data);
header('Content-type: application/json');
echo $data;
and on client side
var results= data.data; // instead of jQuery.parseJSON(data);
It should help to avoid different "magic" differences how it interpret your data and it works for sure in my site.
Related
I have a function in JS that fetches data from a php page.
JS code:
fetch("print.php)
.then(function (r) {
return r.json()
})
.then(function (values) {
......
......
})
}
PHP print.php code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$num = $_GET['num'];
$datas = array_chunk(array_map('rtrim', file('./myFile.txt')), 5);
$result;
foreach ($datas as $index => $data) {
if ($data[0] == $num) {
$result = $data;
}
}
echo json_encode($result);
}
When I run my code, I am getting the error below:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Can anyone help me debug this.
I have tried echo-ing json_encode([$result]); but it didn't work.
I have been trying to fix it for the past 3 hours, but i am hopeless. I have no clue in which direction to go.
UPDATE:
First of all, you have extra closing braces at the end of PHP file if that is not just a typo while pasting in code here.
About the code, well as it is unclear what is in the file myFile.txt, let me show you an example of how it works.
You can follow these steps on your local computer to replicate the example and see it working on your end.
let's say I have this simple PHP filename fetch.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo json_encode(['Message'=>'you successfully received the response.']);
}
?>
Create an HTML page sample.htmland add the following inside the body tag.
<ul>
<li class="print"></li>
</ul>
Now add the following script in the bottom of HTML page before the </body> tag.
<script type="text/javascript">
$(document).ready(function(){
var resultContainer = document.querySelector('ul li.print');
fetch('fetch.php')
.then(function (response) {
return response.json();
})
.then(function (response) {
resultDiv.innerHTML = response.success;
}).catch(function(err){
resultDiv.innerHTML='There was an error reading the JSON response see here '+err;
});
});
</script>
Since we are fetching a PHP file which is returning json, we return response.json() on the response to give it the proper MIME type so it will be handled properly, then display it in the <li> element. Additionally, i am using the .fail to show the error message if the Promise is rejected
This is as simple as it gets and it should show you the text you successfully received the response. inside the li once the Promise resolves. If it does then it means you need to troubleshoot your PHP file first to see what is in the myFile.txt and what is printed in response when it reaches that last line echo json_encode($result);.
Also, your PHP file states that you are sending the query parameter num to the PHP file whereas your script does not contain any query string parameter with the name num.
secondly what is the $result; doing after the line $datas = array_chunk(array_map('rtrim', file('./myFile.txt')), 5);, most of your code makes no sense, you should work on your assignment and provide actual sensible code that others can understand and help you out.
Hope that helps you out
The idea here is to automatically load (or load at all) my index page with some products out of a MySQL database table.
Firstly, my PHP.
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
echo json_encode($itemsJSON);
}
This seems to be working great, and gives me two properly encoded JSON objects of my Item class.
{"name":"Slippers","quantity":"3","cost":"4.00"}
{"name":"Gloves","quantity":"5","cost":"9.00"}
My JavaScript looks like this(and many other similar variations)
$(document).ready(function () {
$.post( "productloader.php", function( data ) {
$( "#result" ).html( data );
});
});
I'm not sure why it is not working. I did not want to use $.getJSON() because there is no query string to work with, so I'd assume I would need $.post().
It seems like this is a pretty common issue, but I've not found a solution yet. Any help would be appreciated. Thank you.
You can't json_encode() each item separately. The data you're sending to the browser is not valid JSON, just many little chunks of valid JSON one after the other. Build an array inside your loop and then encode the whole thing. See also http://jsonlint.com/
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON[] = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
}
echo json_encode($itemsJSON);
In your method of AJAX, you're outputting multiple JSON strings while the js side is expecting 1 string (data). Try removing your for loop to just:
echo json_encode($items);
You are creating JSON for each row, so you are getting separate JSON objects for each row in front end.
You should put all row in to and array and create the JSON object outside the loop, and echo the encoded JSON string.
<?php
$allitem = $db->getRows('SELECT * FROM products');
$itemArr=array();
foreach($allitem as $item){
array_push( $itemArr , new Item($item->product_name, $item->product_quantity, $item->product_cost) );
}
echo json_encode($itemArr);
?>
or
$allitem = $db->getRows('SELECT * FROM products');
echo json_encode($allitem );
I want to form a string in my php server code as xml, and then send it to javascript so that ajax.responseXML can navigate through it and do things with the data. I haven't been able to find exactly what I need to accomplish this and have tried a few different methods. Here's the most recent thing I've tried.
<?php
header("Content-type: text/xml");
$xmlstring = "<?xml version'1.0' encoding='UTF-8'>";
$xmlstring = $xmlstring . "<book name='$name' author='$author'>";
foreach($rankings as $entry)
{
$xmlstring = $xmlstring . "<rank>$entry</rank>";
}
echo $xmlstring;
?>
I know the data is getting there because if I echo it as a string and open it directly, the numbers I need are getting printed. I'm using Ajax.Request to open the php file with certain parameters, and when it reaches the onSuccess function, ajax.responseXML is null. This is my first time dealing with xml so I could be doing something stupid.
function that makes the call:
function findRankings(author, name)
{
new Ajax.Request("server_code.php",
{
method: "get",
paramters: {"type": "rank", "name": name, "author": author},
onSuccess: makeGraph,
onFailure: ajaxFailed
});
}
function makeGraph(ajax)
{
alert(ajax.responseXML); // testing that it made it
.....// do stuff with the response
}
EDIT: I added the header and made it echo just the string. I also added the ajax functions. I keep getting null though. :(
As Dustin said, you need to echo $xmlstring; instead and add header('Content-Type: text/xml');
But you also have a couple of errors in your XML declaration. You're missing a = and a ?:
$xmlstring = "<?xml version='1.0' encoding='UTF-8'?>";
I'd recommend using an XML validator in future.
You used simplexml_load_string, which converts your XML string to an object.
Just echo your $xmlstring
For clean coding you should insert header('Content-Type: text/xml'); as #Twisty mentioned.
Sorry if this is still another thread on the subject but I am struggling since hours but could not find the solution.
I am trying to get data from a Mysql database, create a JSON with php, then parse this JSON in javascript.
Here is my json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
Then I try to parse it into java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
when I replace localhost/json.php by the result in a file data.json, it works, when I open localhost/json.php with firefox, I can see the JSON table...so I do not know why it does not work with localhost/json.php.
Is my php code or javascript code wrong ?
Thanks in advance for your help !
Try this method
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})
Try This in php
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);
I think your web application server (like Apache or nginx) sends Content-Type: text/html by default or something of that sort for your json.php file. On the other hand, it looks like $.getJSON method requires a application/json content type field.
Try adding:
header("Content-Type: application/json");
to the top of the json.php file.
Edit - additional info:
I couldn't find in the original documentation of the $.getJSON method whether it, in fact, requires the specific Content-Type so I looked into the source code:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
Here is the line of source code for jQuery 1.7.1 (which is the version you said that you use, I hope) for getJSON and as you can see, it calls jQuery.get with the last argument set to "json".
In turn, the jQuery.get documentation reveals that this argument means:
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
from: http://api.jquery.com/jQuery.get/
Thus, when you call $.getJSON("/url/to/file", ...) that first argument is expected to be a JSON. If you add the PHP code from the top of my answer, your web application server will mask the output of the php file as a JSON.
I couldn't get the code below to display the success word, any idea what's the problem with the code below?
Thanks in advance.
<script type="text/javascript">
function verification(){
var s = document.test_form.textfield.value;
if (s == "") {
alert("Please enter a value");
return false;
} else {
<?php echo "sucess"; ?>
}
}
</script>
You need to wrap your echo in an alert
alert("<?php echo 'sucess'; ?>")
Your output in javascript is:
else {
sucess
}
What this mean? Try something like this if you want to force output by PHP:
else {
<?php echo "alert('success');"; ?>
}
Or just return true to confirm submitting the form:
else {
return true;
}
You can do 2 things:
console.log("<?php echo 'success'; ?>"); // Will display a message into JS console
or:
alert("<?php echo 'success'; ?>"); // Will display a message into JS alert box
In your code, you only writing 'success' inside the javascript code, and when the browser will try to execute this JS code, it will not understand 'success'and it will throw an error.
If you want to display the text on your page, you can use inside a document.write:
document.write("<?php echo "success"; ?>");
Otherwise, you can use an alert() or console.log()
document.getElementById('body').innerHTML('<?php echo 'sucess'; ?>');
assuming that your body tag has the id body(<body id="body">)
EDIT. of course you can do that with every tag that has an id.
If you are getting PHP to write Javascript you might want to think about using a templating engine like Smarty or Twig.
For the case the file is a Javascript
If the original file is an external .js (not a .php) and is being read on the client side (browser) then it simply does not know how to parse PHP.
Therefore when the browser gets to:
} else {
<?php echo "sucess"; ?>
}
It simply does not recognize the <?php and thus is throwing an error.
Replace the PHP string by alert("success") or, if you do want to query the server and have the server output something take a look into Ajax.
For the case the file is a PHP and the Javascript code is embedded in the html
Replace the code by
} else {
<?php echo 'alert("sucess";)' ?>
}