Autocomplete: Formatting the results - php

Let me try ask this again with a code snippet with what I have tried
I'm trying to format a Jquery autocomplete to include a heading for each of the data sources and to highlight the term. I'm using Codeigniter and thought maybe the easiest would be to format it before i send it back:
JS:
$( ".auto-search" ).autocomplete({
source: '/json/autocomplete_search',
minLength: 2,
});
PHP (Codeigniter)
public function autocomplete_search()
{
$term = $this->input->get('term');
//load model and get results
$this->load->model("mymodel");
$results1= $this->mymodel->search_one($term);
$results2= $this->mymodel->search_two($term);
//Start JSON string
$json='[';
//first source
if ($result1->num_rows() > 0)
{
$json .= '{"value":"<h3>Heading One<h3>"}';
foreach ($results1->result_array() as $r1)
{
$result = str_replace($term,"<strong>".$term."</strong>",$r1['title']);
$json .= ',{"value":"'.$result.'"}';
}
}
//second source
if ($result2->num_rows() > 0)
{
if ($result1->num_rows() > 0){$json .= ',';}
$json .= '{"value":"<h3>Heading Two<h3>"}';
foreach ($results2->result_array() as $r2)
{
$result = str_replace($term,"<strong>".$term."</strong>",$r2['location']);
$json .= ',{"value":"'.$result.'"}';
}
}
//Close JSON string
$json .= ']';
echo $json;
}`
Unfortunately I'm not getting a formatted output, instead, it actually adds the words < h1> and < strong> to the output. Here is sample output:

Okay so I've found a way to do it. Here is how I did it:
Javascript:
$( ".auto-search" ).autocomplete({
source: '/hotpepper/json/autocomplete_search2',
minLength: 2,
open: function(event, ui) {
$(".ui-autocomplete .ui-menu-item a").each(function (i) {
var row = $(this).html();
row=row.replace(/</g,"<");
row=row.replace(/>/g,">");
$(this).html(row);
});
},
});
PHP(Codeigniter):
public function autocomplete_search2()
{
$term = $this->input->get('term');
//load model and get results
$this->load->model("establishment_model");
$results1= $this->establishment_model->search_autocomplete_est($term);
$results2= $this->establishment_model->search_autocomplete_loc($term);
//Start JSON string
$json='[';
//first source
if ($results1->num_rows() > 0)
{
$header= "<h3 style='font-weight:bold'>Accommodation:</h3>";
$json .= '{"value":"'.$header.'"}';
foreach ($results1->result_array() as $r1)
{
$result = str_replace($term,"<strong style='color:#C00'>".$term."</strong>",$r1['establishment_name']);
$json .= ',{"value":"'.$result.'"}';
}
}
//second source
if ($results2->num_rows() > 0)
{
if ($results1->num_rows() > 0){$json .= ',';}
$header= "<h3 style='font-weight:bold'>Destinations:</h3>";
$json .= '{"value":"'.$header.'"}';
foreach ($results2->result_array() as $r2)
{
$result = str_replace($term,"<strong style='color:#C00'>".$term."</strong>",$r2['establishment_location']);
$json .= ',{"value":"'.$result.'"}';
}
}
//Close JSON string
$json .= ']';
echo $json;
}
Since auto-complete escapes my html that I send through, I just unescape it by replacing < and > with <> when i open the auto complete box.
EDIT:
Also had to add the following event to format the result back:
close: function(event, ui) {
var result = $(this).val();
if (result.search("</h3>") ==-1)
{
result=result.replace(/<strong style='color:#C00'>/g,"");
result=result.replace(/<\/strong>/g,"");
}
else
{
result="";
}
$(this).val(result);
}

Related

Pass array data inside value="" separated with ':' using AJAX/JSON | PHP, HTML

Is it possible to pass data in aray using AJAX/JSON? Like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."?
This is the sample code.
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
$emp=$row['empno'];
$empno = str_pad(++$emp,7,"0",STR_PAD_LEFT);
echo "<option value='".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."".$empno."'>".$row['departmentname']." : ".$row['jobposition']."</option>";
}
}
I understand that this can work using AJAX, but I don't know how to set it up for array that is only separated with ":"
<script>
$(document).ready(function() {
$("#accounttype").change(function() {
var accounttype = $(this).val();
if(accounttype != "") {
$.ajax({
url:"earnings_amendment-employee_select_title.php",
data:{accounttitleselector:accounttype},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#accounttitleselector").html(resp);
}
});
}
else {
$("#accounttitleselector").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
Thank you.
Add the row data in new array results and return the results in json format using json_encode
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
$emp=$row['empno'];
$empno = str_pad(++$emp,7,"0",STR_PAD_LEFT);
$array[] ="<option value='".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."".$empno."'>".$row['departmentname']." : ".$row['jobposition']."</option>";
}
}
echo json_encode($array);
In jquery after ajax success parse the response with JSON.parse(), and the data becomes a JavaScript object.
//use each loop to get the option data from response
success:function(response) {
var data = JSON.parse(response);
$("#accounttitleselector").html($.each(data, function(index, value) {
value
}))
}
});

Autocomplete doesn't work with mysql

Okay I am using prepared statement to get all the cities.
this is my php file
<?php
include_once '../includes/db_connect.php';
$search = $_GET['term'];
if($stmtgetstore = $mysqli->prepare("SELECT * FROM cities WHERE city LIKE '%$search%'"))
{
//$stmtgetstore->bind_param("s",$search);
$stmtgetstore->execute();
$getstore = $stmtgetstore->get_result();
$stmtgetstore->close();
}
else
{
echo $mysqli->error;
}
$array = array();
$json = '[';
$first = true;
while($store = $getstore->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$store['city'].'"}';
}
$json .= ']';
?>
And this is my script and html
<script type="text/javascript">
$(document).ready(function()
{
$('#autoCity').autocomplete(
{
source: "scripts/search_store_by_city.php",
minLength: 2
})/*.data( "autocomplete" )._renderItem = function( ul, item )
{
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.city )
.appendTo( ul );
};*/
});
</script>
<div class="container">
<form action="" method="GET">
<input type="text" id="autoCity">
</form>
</div>
But somehow when I enter letters in textbox I see no result coming in console and no error also but when I run query in database it gives me rows
This query
SELECT * FROM cities WHERE city LIKE '%Kara%'
Any idea what me doing wrong?
Okay I forgot to echo my json at the end of the script
<?php
include_once '../includes/db_connect.php';
$search = $_GET['term'];
if($stmtgetstore = $mysqli->prepare("SELECT * FROM cities WHERE city LIKE '%$search%'"))
{
//$stmtgetstore->bind_param("s",$search);
$stmtgetstore->execute();
$getstore = $stmtgetstore->get_result();
$stmtgetstore->close();
}
else
{
echo $mysqli->error;
}
$array = array();
$json = '[';
$first = true;
while($store = $getstore->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$store['city'].'"}';
}
$json .= ']';
echo $json;
?>

unable to fetch all values from ajax GET method

<script type="text/javascript">
function bindCity() {
// Some javascript code
//declare options array and populate
var modelnames = new Array();
$.get("file.php?mt=" + qs, function(data) {
eval(data);
if(modelnames.length > 0) {
addOptions(modelnames);
}
}
);
}
function addOptions(cl) {
//enable child select and clear current child options
$("#mn").removeAttr("disabled");
$("#mn").html('');
//repopulate child list with array from helper page
var city = document.getElementById('mn');
for(var i = 0; i < cl.length; i++) {
city.options[i] = new Option(cl[i].text, cl[i].value);
}
}
</script>
This is the PHP script (After getting the values to $mt):-
$SQLqueryTry = "SELECT mn FROM pd WHERE pd_mt = '$mt'";
$SQLqueryETry = mysql_query($SQLqueryTry, $dacreint) or die(mysql_error());
while ($Try = mysql_fetch_array($SQLqueryETry))
{
$output = "modelnames.push(new Option('$Try[mn]', '$Try[mn]'));\n";
}
My output code in PHP file:-
header('Content-type: text/plain');
echo $output;
Now i am able to fetch only one value when it is $output = "modelnames.push(new Option('$Try[mn]', '$Try[mn]'));\n";
However when i add . to $output =, to make it $output .= "modelnames.push(new Option('$Try[mn]', '$Try[mn]'));\n";
I am unable to get any value. What is the problem?
Are you able to see any errors in your error log?
My first guess is that you've forgotten to initialize the $output variable before using .= on it.
Maybe try:
$output = "";
while ($Try = mysql_fetch_array($SQLqueryETry))
{
$output .= "modelnames.push(new Option('$Try[mn]', '$Try[mn]'));\n";
}

how to get data to javascript from php using json_encode?

I am trying to map traceroutes to google maps.
I have an array in php with traceroute data as
$c=ip,latitude,longitude, 2nd ip, its latitude, longitude, ....target ip, its lat, its lng
I used json_encode($c, JSON_FORCE_OBJECT) and saved the file
Now, how do I access this using javascript, by directly equating it to new JS object?
earlier I used to have a data format like this on harddrive
var data12 = {
"route":[
{
"ip": "some ip",
"longitude": "some lng",
"latitude": "some lat",
.....
and in my javascript it was used as
data=data12.route;
and then simply acces the members as data[1].latitude
I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.
For parsing JSON, simply do
var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );
You can now access everything easily:
alert ( obj.name );
Note: jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval () method.
Edit: To get data from the server side to the client side, there are two possibilities:
1.) Use an AJAX request (quite simple with jQuery):
$.ajax ( {
url: "yourscript.php",
dataType: "json",
success: function ( data, textStatus, jqXHR ) {
// process the data, you only need the "data" argument
// jQuery will automatically parse the JSON for you!
}
} );
2.) Write the JSON object into the Javascript source code at page generation:
<?php
$json = json_encode ( $your_array, JSON_FORCE_OBJECT );
?>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );
//]]>
</script>
I know this is old, but I recently found myself searching for this. None of the answers here worked for my case, because my values had quotes in them. The idea here is to base64 encode the array before echo'ing to the page. That way the quotes don't conflict.
< ?php
$names = ['first' => "some'name"];
?>
var names = JSON.parse(atob('< ?php echo base64_encode(json_encode($names)); ?>'));
console.log(names['first']);
I could get the JSON array by using PHP's json_encode() from backend like this example:
<!doctype html>
<html>
<script type="text/javascript">
var json = <?php echo json_encode(array(1 => '123', 'abc' => 'abd', 2 => 5));?>;
console.log(json[1]);
console.log(json.abc);
</script>
</html>
No quotation marks means an eval() of whatever was printed out. This is a quick hack that we utilised often to quickly add initial values to our AJAX page.
no need for jquery, just:
var array= <?php echo json_encode($array); ?>;
console.log(array->foo);
we have to display the json encode format in javascript , by using below one:
var responseNew = JSON.parse(' {"name" : "John"} ' );
alert(responseNew['name']);
This function works for you I guess:
function json_encode4js($data) {
$result = '{';
$separator = '';
$count = 0;
foreach ($data as $key => $val) {
$result .= $separator . $key . ':';
if (is_array($val)){
$result .= json_encode4js($val).(!$separator && count($data) != $count ? ",":"");
continue;
}
if (is_int($val)) {
$result .= $val;
} elseif (is_string($val)) {
$result .= '"' . str_replace('"', '\"', $val) . '"';
} elseif (is_bool($val)) {
$result .= $val ? 'true' : 'false';
} elseif (is_null($val)) {
$result .= 'null';
} else {
$result .= $val;
}
$separator = ', ';
$count++;
}
$result .= '}';
return $result;
}
$a = array(
"string"=>'text',
'jsobj'=>[
"string"=>'text',
'jsobj'=>'text2',
"bool"=>false
],
"bool"=>false);
var_dump( json_encode4js($a) ); //output: string(77) "{string:"text", jsobj:{string:"text", jsobj:"text2", bool:false}, bool:false}"
var_dump( json_encode($a));//output: string(85) "{"string":"text","jsobj":{"string":"text","jsobj":"text2","bool":false},"bool":false}"
HTML
<select name="sub" id="subcat" class="form-control" required="required">
</select>
PHP
$this->load->model('MainModel');
$subvalue = $this->MainModel->loadSubData($var);
echo json_encode($subvalue);
//if MVC
// or you can just output your SQLi data to json_encode()
JS
$("#maincat").change(function(){
var status = this.value;
$.ajax({
type: 'POST',
url: 'home/subcat/'+status,
success: function(data){
var option = '';
var obj = JSON.parse(data);
if(obj.length > 0){
for (var i=0;i<obj.length;i++){
option += '<option value="'+ obj[i].id + '">' + obj[i].name + '</option>';
}
//Now populate the second dropdown i.e "Sub Category"
$('#subcat').children("option").remove();
$('#subcat').append(option);
}else{
option = '<option value="">No Sub Category Found</option>';
$('#subcat').children("option").remove();
$('#subcat').append(option);
}
},
error: function(){
alert('failure');
}
});

JSON save in Database and load with JQuery

I create a huge JSON-Object and save it in my database. But when I load the "string" and echo it in PHP, I can't access the JSON Object in JQuery. Do I have to consider something if I want to save my JSON Object in a MySQL Database (when I just create the Array and then echo it with "echo json_encode($arr);" it works fine, but I need to save the Object for caching).
{"247":{"0":"This is a
question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
2","962","0"],["Answer
3","961","0"],["Answer
4","963","0"]]},{"248":{"0":"This is a
question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
2","962","0"],["Answer
3","961","0"],["Answer
4","963","0"]]}}
just an excerpt
If I just echo this JSON-Object, everything works fine, but if I load the same string from the database and echo it, it doesn't work.
Update 1: forget to tell that I'm using a TEXT-Field with UTF8_general_ci collation
Update 2: Maybe a little bit more code:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data[247][0]);
}, "json");
return false;
});
}
this loads the script and should alert "This is a question"
<?php
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
echo $output;
?>
this is the script, where I load the database entry with the JSON-Object.
Update 3:
I think I solved the problem. Some break sneaked into my JSON-Object so I do this, before the output:
$output = str_replace("\n", "", $output);
$output = str_replace("\r", "", $output);
$output = str_replace("\r\n", "", $output);
I'd suggest looking at what your javascript is seeing. Instead of asking jQuery to interpret the json for you, have a look at the raw data:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data);
}, "text");
return false;
});
}
For example, if part of the string gets oddly encoded because of the UTF-8, this might cause it to appear.
Once you've done that, if you still can't spot the problem, try this code:
var data1, data2;
function start() {
$(".start").click(function () {
$.post("load_script.php", {src: "db" }, function(data){
data1 = data;
}, "text");
$.post("load_script.php", {src: "echo" }, function(data){
data2 = data;
}, "text");
if (data1 == data2) {
alert("data1 == data2");
}
else {
var len = data1.length < data2.length ? data1.length : data2.length;
for(i=0; i<len; ++i) {
if (data1.charAt(i) != data2.charAt(i)) {
alert("data1 first differs from data2 at character index " + i);
break;
}
}
}
return false;
});
}
And then change the PHP code to either return the data from the database or simply echo it, depending on the post parameters:
<?php
if ($_POST['src'] == 'db')) {
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
}
else {
$output = '{"247":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]},{"248":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]}}';
}
echo $output;
?>
Hope that helps!
I got this to work in a slightly different manner. I've tried to illustrate how this was done.
In Plain English:
use urldecode()
In Commented Code Fragments
$json = $this->getContent($url); // CURL function to get JSON from service
$result = json_decode($json, true); // $result is now an associative array
...
$insert = "INSERT INTO mytable (url, data) ";
$insert .= "VALUES('" . $url . "', '" . urlencode(json_encode($result)) . "') ";
$insert .= "ON DUPLICATE KEY UPDATE url=url";
...
/*
** Figure out when you want to check cache, and then it goes something like this
*/
$sqlSelect = "SELECT * FROM mytable WHERE url='" . $url . "' LIMIT 0,1";
$result = mysql_query($sqlSelect) or die(mysql_error());
$num = mysql_numrows($result);
if ($num>0) {
$row = mysql_fetch_assoc($result);
$cache = json_decode(urldecode($row['data']), true);
}
Hope this is helpful
Maybe you use varchar field and your string just doesn't fit in 255 chars?

Categories