I'm running into an issue where the JSON returned from a PHP query is not valid and I'm not really sure why; I'm still learning. When the datatype is excluded the below code returns:
{"Customer_ID":"0", "FirstName":"John", "LastName":"Smith"}
{"Customer_ID":"1", "FirstName":"Jane", "LastName":"Smith"}
otherwise it returns:
SyntaxError: "JSON.parse: unexpected non-whitespace character after ..."
I thought this might be because the record is not being returned in a single JSON response, but I can't see that being the issue as the concurrent responses are JSON. Any ideas? Any suggests? Feel free to point out the semantic issues.
HTML:
getRecord("*", "customer", "");
JavaScript:
function getRecord(field, table, condition) {
var request = $.ajax({
url: "./handler.php",
method: "GET",
dataType: "JSON",
cache: "false",
data: {
action: "SELECT",
field: `${field}`,
table: `${table}`,
condition: `${condition}`,
},
});
request.done(function(data, status, xhr) {
console.log(data, status, xhr);
});
request.fail(function(xhr, status, error) {
console.log(xhr, status, error);
});
};
PHP:
<?php
# IMPORT SETTINGS.
include "settings.php";
# FUNCTION DISPATCHER.
switch($_REQUEST["action"]) {
case "SELECT":
getRecord($conn);
break;
default:
printf('Connection Error: Access Denied.');
mysqli_close($conn);
}
# LIST OF COLUMNS THAT WE NEED.
function getRecord($conn) {
$table = $_REQUEST["table"];
$field = $_REQUEST["field"];
$condition = $_REQUEST["condition"];
if (!empty($condition)) {
$query = "SELECT $field FROM $table WHERE $condition";
} else {
$query = "SELECT $field FROM $table";
}
if ($result = mysqli_query($conn, $query)) {
while ($record = mysqli_fetch_assoc($result)) {
echo json_encode($record);
}
}
# CLOSE THE CONNECTION.
mysqli_close($conn);
}
?>
Your JSON is not valid because it consists of multiple objects. What you need to do is put all your results into an array and then echo the json_encode of that. Try something like this:
$records = array();
if ($result = mysqli_query($conn, $query)) {
while ($records[] = mysqli_fetch_assoc($result)) {
}
}
echo json_encode($records);
This will give you an output that looks something like this:
[
{"Customer_ID":"0", "FirstName":"John", "LastName":"Smith"},
{"Customer_ID":"1", "FirstName":"Jane", "LastName":"Smith"}
]
and you can access each of the elements in your Javascript by something like
let customer = data[0].FirstName + ' ' + data[0].LastName;
I use this jQuery function to get data through Ajax:
function addContentPrt(cid){
$.ajax({
url: "<?=parseLink('addContent.php')?>",
type: "POST",
cache: true,
dataType:'json',
data: {id: cid},
success: function(returnedData){
console.log(returnedData);
},
error: function (xhr, tst, err) {
console.log(err);
}
});
}
and on the receiving end:
<?
header("Content-Type: application/json", true);
if(isset($_POST['id'])) {
$id = $_POST['id'];
}
$sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");
$r = mysql_fetch_array($sql);
echo $r['title'];
echo $id;
?>
the echo $id does return to ajax, but not $r['title'], with that it goes null in console. If I add some dummy text like hello world, I get a synthax error SyntaxError: Unexpected token h {stack: (...), message: "Unexpected token h"}
What could be the cause of this and what could I do to fix it?
<?
header("Content-Type: application/json", true);
if(isset($_POST['id'])) {
$id = $_POST['id'];
}
$sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");
$r = mysql_fetch_array($sql);
echo json_encode('id' => $id, 'title' => $r['title']);
?>
and in your ajax success:
success: function(returnedData){
console.log(JSON.parse(returnedData));
},
In the ajax, you specified the datatype as json which is the format expecting from the server, So in order to get a result, you need to return the json result from the server. Either by using json_encode($r) where $r can be any array.
return json_encode($r); then you can read variable $r in sucess
I'm trying to use the $.map in ajax and I don't success with getting the data from json array. I'll show you the json file, the ajax code and the json output i get. Hope you can help me, thank you very much :) and sorry for my english! Here is the ajax:
$.ajax({
url: 'searchapi.php',
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map(data.table, function( item ) { //dont get this line!
return {
label: item.trid,
value: item.trid
}
}));
}
});
And here is the json file:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "mydb";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$data = ("select * from table;");
$json = array();
$result = mysql_query($data);
while($row = mysql_fetch_array ($result))
{
$array = array(
'trid' => $row['name'],
);
array_push($json, $array);
}
$jsonstring = json_encode($json);
echo $jsonstring;
die();
?>
Here is the json output:
[{"name":"Emma"},{"name":"Eric"},{"name":"Peter"},{"name":"Sam"},{"name":"Roger"},{"name":"Sven"},{"name":"Julia"}]
You are referring to the wrong key, try it like this
$.map(data, function( item ) { //dont get this line!
return {
label: item.name,
value: item.name
}
})
I have the following code in JavaScript:
$('input#search_user').typeahead({
source: function(query, process) {
$.ajax({
url: 'modulos/search_user.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(data);
}
});
}
});
And the following code in my PHP file:
if (isset($_POST['query'])) {
$query = $_POST['query'];
$sql = mysql_query ("SELECT nombre FROM users_r WHERE nombre LIKE '%{$query}%'",$link);
}
$data = array();
while ($row = mysql_fetch_object($sql))
{
$data[] = $row['nombre'];
}
echo json_encode( $data );
mysql_close($link);
But with jQuery 1.10.2 it throws the following error:
Uncaught Error: one of local, prefetch, or remote is required
What should I do about this?
now works with the next code
javascript
$(document).ready(function ()
{
$("input[name='search_user']").typeahead({
name: 'nombre',
remote: 'modulos/search_user.php?query=%QUERY'
});
}); // $(document).ready(function ()
php file
$query = $_GET['query'];
$sql = mysql_query ("SELECT nombre FROM users_r WHERE nombre LIKE '%{$query}%'",$link);
$data = array();
while ($row = mysql_fetch_assoc($sql))
{
$data[] = $row['nombre'];
}
mysql_close($link);
echo json_encode( $data );
my problem was the each method, for get column work with mysql_fetch_assoc but no with mysql_fetch_object
Trying to get tag-it to work with an ajax call.
Everything works so far. Except, I am unable to assign a tagSource via an ajax call.
In firebug, the 'data' is returning:
["Ruby","Ruby On Rails"]
But its not showing up as I type into the input box.
$('.tags ul').tagit({
itemName: 'question',
fieldName: 'tags',
removeConfirmation: true,
availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"],
allowSpaces: true,
// tagSource: ['foo', 'bar']
tagSource: function() {
$.ajax({
url: "/autocomplete_tags.json",
dataType: "json",
data: { term: 'ruby' },
success: function(data) {
console.log(data);
return data;
}
});
}
});
console.log(data) returns ["Ruby", "Ruby On Rails"].
Am I missing something here? Anyone else got this to work?
Seems this question hasn't been answered for a long time, I bet you have already found a solution but for those who haven't here is my answer:
The indention got all messed up when i copied from my code ;)
<input type="hidden" name="tags" id="mySingleField" value="Apple, Orange" disabled="true">
Tags:<br>
<ul id="mytags"></ul>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#mytags").tagit({
singleField: true,
singleFieldNode: $('#mySingleField'),
allowSpaces: true,
minLength: 2,
removeConfirmation: true,
tagSource: function( request, response ) {
//console.log("1");
$.ajax({
url: "search.php",
data: { term:request.term },
dataType: "json",
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.label+" ("+ item.id +")",
value: item.value
}
}));
}
});
}});
});
and the "search.php" you can find this in some autocomplete jQuery examples actually.
<?php
$q = strtolower($_GET["term"]);
if (!$q) return;
$items = array(
"Great Bittern"=>"Botaurus stellaris",
"Little Grebe"=>"Tachybaptus ruficollis",
"Black-necked Grebe"=>"Podiceps nigricollis",
"Little Bittern"=>"Ixobrychus minutus",
"Black-crowned Night Heron"=>"Nycticorax nycticorax",
"Heuglin's Gull"=>"Larus heuglini"
);
function array_to_json( $array ){
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = "key_$key";
}
$key = "\"".addslashes($key)."\"";
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "\"".addslashes($value)."\"";
}
// Add to staging array:
$construct[] = "$key: $value";
}
// Then we collapse the staging array into the JSON form:
$result = "{ " . implode( ", ", $construct ) . " }";
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = "[ " . implode( ", ", $construct ) . " ]";
}
return $result;
}
$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
}
if (count($result) > 11)
break;
}
echo array_to_json($result);
?>
check this out:
How to get tagSource to work with $.ajax()? (from tag-it's github issue list).
this is an example:
HTML file:
<!doctype html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/tag-it.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css">
<link href="css/jquery.tagit.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
$(document).ready(function() {
$("#mytags").tagit({
tagSource: function(search, showChoices) {
$.ajax({
url: "auto.php",
data: {search: search.term},
success: function(choices) {
showChoices(choices);
}
});
}
});
});
</script>
</head>
<body>
<ul id="mytags">
<li>Tag1</li>
</ul>
</body>
</html>
(get tag-it.js file from [here][1])
and this is the PHP file:
<?php
header('Content-type: application/json');
$q = $_GET["search"];
//check $q, get results from your database and put them in $arr
$arr[] = 'tag1';
$arr[] = 'tag2';
$arr[] = $q;
echo json_encode($arr);
?>
None of these answers worked as is for me, so I thought I would come back and post my code that does work.
var tagThis = $(".tagit");
tagThis.tagit({
tagSource: function(search, showChoices) {
$.ajax({
url: "/tags/search",
data: { search: search.term },
dataType: "json",
success: function(data) {
var assigned = tagThis.tagit("assignedTags");
var filtered = [];
for (var i = 0; i < data.length; i++) {
if ($.inArray(data[i], assigned) == -1) {
filtered.push(data[i]);
}
}
showChoices(filtered);
}
});
}
});
This code assumes the URL returns a JSON encoded string (an array of strings). It will then filter out any tags that have already been selected in the input. So they aren't repeated in the list. Otherwise, this works for me.
Thanks to the others for sending me on the right path.
tagSource has been depreciated.
Just use:
<script>
$(document).ready(function(){
$("#tagit").tagit({
autocomplete: {
source: "your-php-file.php",
}
});
});
</script>
You can add all the attributes to this:
<script>
$(document).ready(function(){
$("#tagit").tagit({
allowSpaces: true,
singleFieldDelimiter: ';',
allowDuplicates: true,
autocomplete: {
source: "your-php-file.php",
}
});
});
</script>
You should remove your availableTags, as you are overloading tagSource, which is used as source for the autocompletion.
Also that may be a typo, but it "return", and not "eturn".
Edit:
I think the problem is that the function you provided to tagSource doesn't seems to return anything. However my javascript knowledge seems to end here :/
I think that you can overwrite the autocomplete method from jquery UI :
$('.tags ul').tagit({
itemName: 'question',
fieldName: 'tags',
removeConfirmation: true,
//availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"]
allowSpaces: true,
// tagSource: ['foo', 'bar']
tagSource: function () {
$.ajax({
url: "/autocomplete_tags.json",
dataType: "json",
data: {
term: 'ruby'
},
success: function (data) {
console.log(data);
return data;
}
});
},
autocomplete: {
delay: 0,
minLength: 2,
source: this.tagSource()
}
});
Just to add
Assuming your script page looks like
<script>
$(document).ready(function(){
$("#myULTags").tagit({
allowSpaces: true,
singleFieldDelimiter: ';',
allowDuplicates: true,
autocomplete: {
source: "searchtag.php",
}
});
});
</script>
Your simple php page if you are fetching values from database would look like
<?php $link = mysqli_connect("localhost","root","dbpassword","dbname") or die("Couldn't make connection."); ?>
<?php
$q = strtolower($_GET["term"]);
if (!$q) return;
header('Content-type: application/json');
$query_tags = mysqli_query($link,"SELECT TagName FROM `tagstable` WHERE `TagName` LIKE '%".$q."%' LIMIT 10");
$items = array(); // create a variable to hold the information
while ($row = mysqli_fetch_array($query_tags)){
$items[] = $row['TagName']; // add the row in to the results (data) array
}
echo json_encode($items);
?>
Regards