How can I add link to json_encode? - php

How can I add clickable link to json_encode?
I did a multiple query auto complete textbox with jquery. Maybe that's not the correct way how to do multiple queries but that's works anyway.
$conn = new PDO("mysql:host=".DB_SERVER.";port=3306;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM azonositok WHERE guid LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['guid']; /// I want to link to http://example.com/guid.php
}
$stmt1 = $conn->prepare('SELECT * FROM felhasznalok WHERE fnev LIKE :term');
$stmt1->execute(array('term' => '%'.$_GET['term'].'%'));
while($row1 = $stmt1->fetch()) {
$return_arr[] = $row1['fnev']; /// I want to link to http://example.com/profile.php
}
} catch(PDOException $e) {
echo 'HIBA: ' . $e->getMessage();
}
echo json_encode($return_arr);
}

You'll have to add a function to execute on selection of an item in the autocomplete widget's dropdown list.
This is done with the select property as follows:
$(".auto").autocomplete({
source: "search.php",
minLength: 1,
select: function(event, ui) {
window.location.href = ui.item.value;
}
});
This changes the current window's location to the selected item's value.
EDIT:
To change the default behavior where the value is displayed on focus/select to display the label instead, you could try:
$(".auto").autocomplete({
source: "search.php",
minLength: 1,
select: function(event, ui) {
event.preventDefault();
$('.auto').val(ui.item.label);
window.location.href = ui.item.value;
},
focus: function(event, ui) {
event.preventDefault();
$('.auto').val(ui.item.label);
}
});

Related

How Make a dependable dropdown list by taking values from Database

I want to make a dropdown list which is dependable on another dropdown list. Both dropdown list's values are retrieved from database. How can i do that?please help .
Also how can i pass the category name to database mysql query page (list.php).
I currently have this which list all subcategories..but i want to list only particular subcategory depending on category
<script>
$(document).ready(function(){
$.getJSON("getlist.php", function(return_data){
return_data.forEach(function(e,i){
$('#catn').append('<option value= "'+e.catname+'">'+e.catname+'</option>');
});
});
});
$(document).ready(function(){
$.getJSON("list2.php",{'catname':catname},function(return_data){
return_data.forEach(function(h,i){
$('#scatn').append('<option value= "'+h.subcatname+'">'+h.subcatname+'</option>');
});
});
});
list.php
<?php
$catname=$_GET['catname'];
$conn =mysqli_connect("localhost", "root", "", "project");
$sql = "SELECT * FROM catd where catname='$catname'";
$result = mysqli_query($conn, $sql);
$scat_arr = array();
while( $row = mysqli_fetch_array($result) )
{
$catid = $row['cid'];
$catname = $row['catname'];
$scat_arr[] = array("cid" => $catid, "catname" => $catname);
}
echo json_encode($scat_arr);
?>
You can use .change function in JS. While the first dropdown is changing it triggers the ajax with POST method to post to your file list.php(where your query runs).
jQuery(document).ready(function() {
$('#catname').change(function(){
var catname = $(this).val();
$.ajax({
url:list.php,
method:"POST",
data:{
catname:catname
},
dataType:"json",
success:function(data){
var $el = $("#subcatname");
$el.empty();
$el.append($("<option></option>")
.attr("value", '')
.attr("hidden",'')
.text('Select Sub Cat Name'));
$.each(data, function(index, value){
$el.append('<option
value="'+value.catid+'">'+value.catname+'</option>')
});
});
You must echo json_encode the output so that ajax recognize the returned value. And then you can append the values by casting it using append.
Hopes this helped.

Jquery autocomplete displaying more detail in drop down

I have a autocomplete function that works fine but where I want to extend the drop down details a bit. It looks like this:
Datafile (form-lookup.php):
if ($db)
{
$fetch = mysqli_query($db,"SELECT * FROM uni_labels where label_name like '%" . $_GET['term'] . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['label'] = htmlspecialchars_decode($row['label_name']);
$row_array['lookupid'] = $row['id'];
$row_array['address'] = $row['label_address'];
$row_array['number'] = $row['label_number'];
$row_array['postalcode'] = $row['label_postalCode'];
$row_array['country'] = $row['label_country'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysqli_close($db);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
My page that retreives the data looks like this:
$(function() {
$("#step1Name").autocomplete({
source: "/pages/form-lookup.php?country=dk",
minLength: 2,
select: function(event, ui)
{
$('#step1Name').val(ui.item.address);
$('#lookupid').val(ui.item.lookupid);
$('#vej').val(ui.item.address);
}
});
});
<input maxlength="100" type="text" required="required" class="form-control input-lg" name="step1Name" id="step1Name" />
Everyting works just great, but I would like for my drop down to show both $row_array['label'] and $row_array['address'], and when I select a value in the drop down, the input box will only output the $row_array['label'] value.
In the datafile I have tried to add the address to the label, like this:
$row_array['label'] = htmlspecialchars_decode($row['label_name'])." - ".$row['label_address'];
This displays the value fine in the drop down, but when selecting the choice, the input box of course contains too much data, where I only want it to display the label_name.
Can someone point me in the right direction?
Thanks in advance.
Add this to your autocomplete code:
select: function(event, ui) {
event.preventDefault();
var name = ui.item.value.split('-')[0];
$("#starter").val(name);
},
focus: function(event, ui) {
return false;
}
So your updated autocomplete code will be like that:
$("#step1Name").autocomplete({
source: "/pages/form-lookup.php?country=dk",
minLength: 2,
select: function(event, ui) {
event.preventDefault();
var name = ui.item.value.split('-')[0];
$("#starter").val(name);
return false;
},
focus: function(event, ui) {
return false;
}
});

Separate json encoded array result

The following php block searches and returns names and i want to select an item and at ajax be able to get other items in the row selected beside "name". How do i separate them with ajax?
<?php
require_once '../php/db_conx.php';
$req = "SELECT name "
."FROM profiles "
."WHERE name LIKE '%".$_REQUEST['term']."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
?>
Here's ajax.
$(function() {
$( "#SearchInput").autocomplete({
source: 'Search.php',
minLength: 1,
select: function(event, ui) {
$('#Name').append(ui.item.label);
}
});
});
You can use _renderItem method
_renderItem: function( ul, item ) {
$( "#selector" ).text( item.name );// let name is in json
}
Or you can get the name in select event also like,
select: function(event, ui) {
$('#Name').append(ui.item.label);
$( "#selector" ).text( item.name );// let name is in json
}
Try this:
I think you need to parse data from array.
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
Use the variable name you have used.
Read More on: http://msdn.microsoft.com/en-us/library/ie/cc836466(v=vs.94).aspx
Thanks

Grab Value of Second Term using jQuery UI Autocomplete

Thanks for the response, #ManselUK
Fixed this part with finding values(below)
But, when I SELECT a value, it doesnt set the value of the hidden element, why not?
I'm getting error: Uncaught TypeError: Cannot set property 'value' of null when I select a value from autocomplete..
Php code which is called upon entering 5 characters:
try{
$occupation = mysql_real_escape_string($_GET['term2']); //////
echo 'term 2 '. $occupation;
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth = $dbh->prepare(
'SELECT occupID, occupVal From Occupation WHERE occupVal = ?');
$sth->bindParam(1, $occupation);
$sth->execute();
$jsonArray = array();
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) {
$jsonArray[] = array(
'label' => $result['occupVal'],
'value' => $result['occupVal']."|".$result['occupID']);
}
print json_encode($jsonArray); // json encode that array
} // try
the catch{} block of code, will send errors to a file, but that file has no errors in it.
The HTML Form Input:
<label for="occup">What is your occupation? <br /></label>
<div class="ui-widget">
<input id="occup" type="text" name="term2" value="e.g. Carpenter, Developer, etc" onFocus="clearText(this)" /><br />
<input type="hidden" id="actualOccup" name="actualOccupval" value="" />
The JS that is called upon entering something:
<script type="text/javascript">
$(document).ready(function()
{
// Zipcode Field
$('input#zip').autocomplete({
dataType: "json",
source: "../src/php/registration/getFanLoc.php",
minLength: 4,
select: function(event, args){
event.preventDefault();
var joinedValues = args.item.value;
var id = joinedValues.split("|")[0];
var cityAndState= joinedValues.split("|")[1];
document.getElementById('actualZip').value = cityAndState ;
document.getElementById('zip').value = id;
}
});
// Occupation Field
$('input#occup').autocomplete({
source: function(request, response) {
$.getJSON("../src/php/registration/getFanOccupation.php", { term2: request.term }, response);
},
minLength: 5,
select: function(event, args){
event.preventDefault();
var joinedValues = args.item.value;
var id = joinedValues.split("|")[0];
var occupValAndId= joinedValues.split("|")[1];
$('#actualOccupval').val(occupValAndId);
$('#occup').val(id);
}
});
});
</script>
I've tried debugging:
- Check error log for this file. (no errors)
- Check the SELECT query , the value for occupVal in database is a VARCHAR, in SQL the value is found by doing occupVal = 'some val here'; does jQuery need these quotes?
- if I access getFanOccupation.php?term2=Computer Programmer directly it outputs: term 2 Computer Programmer[{"label":"Computer Programmer","value":"Computer Programmer|183"}]
- Which is RIGHT, the problem is if I get Computer Programmer value and paste directly in input, or even start to write it, it
Fixed JS: - this code works, was select wrong ID for occupation, that's why it wasn't showing the hidden forms field value
$(document).ready(function()
{
// Zipcode Field
$('input#zip').autocomplete({
dataType: "json",
source: "file1.php",
minLength: 4,
select: function(event, args){
event.preventDefault();
var joinedValues = args.item.value;
var id = joinedValues.split("|")[0];
var cityAndState= joinedValues.split("|")[1];
document.getElementById('actualZip').value = cityAndState ;
document.getElementById('zip').value = id;
}
});
// Occupation Field
$('input#occup').autocomplete({
source: function(request, response) {
$.getJSON("file.php", { term2: request.term }, response);
},
minLength: 5,
select: function(event, args){
event.preventDefault();
var joinedValues = args.item.value;
var id = joinedValues.split("|")[0];
var occupValAndId= joinedValues.split("|")[1];
$('#actualOccup').val(occupValAndId);
$('#occup').val(id);
}
});
});
Use this :
source: function(request, response) {
$.getJSON("../src/php/registration/getFanOccupation.php", { term2: request.term }, response);
}
on the second autocomplete. Docs for $.getJSON() here
From the docs :
A request object, with a single property called "term", which refers
to the value currently in the text input. For example, when the user
entered "new yo" in a city field, the Autocomplete term will equal
"new yo".
Full code :
$('input#occup').autocomplete({
source: function(request, response) {
$.getJSON("../src/php/registration/getFanOccupation.php", { term2: request.term }, response);
},
minLength: 4,
select: function(event, args){
event.preventDefault();
var joinedValues = args.item.value;
var id = joinedValues.split("|")[0];
var occupValAndId= joinedValues.split("|")[1];
$('#actualOccupval').val(occupValAndId);
$('#occup').val(id);
}
});
Note also changed document.getElementById('blah').value = to $('#blah').val() as your already using jQuery ... docs for the val() method here

getting jquery autocomplete to pass item to another field when selected

I've been working on this for a couple of hours and it should work but i'm missing something!
basically, i'm using jquery autocomplete with json source, with 2 values id and description.
Description should show up in suggestions and if item is selected and ID passed to a hidden field ( the field is not hidden currently for testing purposes)
here's my code:
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php",
minLength: 3,
formatItem: function(data, i, n, value) {
return value.split("|")[1];
}
});
$("#CurrentProv").result(function(event, data, formatted) {
if (data)
$("input#fid").val(data[0]);
});
});
//PHP valid json output
$term = $_GET['term'];
$sql = "SELECT * FROM db.table WHERE PName LIKE '%$term%'";
$res = mysql_query($sql, $conn) or die(mysql_error());
while ($row = mysql_fetch_array($res)) {
$searchArray['value'] = $row['PID'].'|'.$row['PName'];
$search[] = $searchArray;
}
echo json_encode($search);
I've searched and done various variations and still doesn't work!!! My brain is shutting down!!!!!!!!
First, switch to using the actual jQuery UI autocomplete.
You'll have to sort out how to format your items on the server side, or in your JSON callback, because formatItems is not supported anymore. Check out this guide for some help.
Now that you've done that, here's how it will look:
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php", //or you can use a callback here
minLength: 3,
change: function(event, ui) {
$("input#fid").val(ui.item.value);//or ui.item.desc perhaps
}
});
});
Working tweaked PHP code and JS as Ryley suggested:
$term = $_GET['term'];
$sql = "SELECT * FROM db.table WHERE PName LIKE '%$term%'";
$res = mysql_query($sql, $conn) or die(mysql_error());
while ($row = mysql_fetch_array($res)) {
$searchArray['value'] = $row['PID'];
$searchArray['id'] = $row['PName'];
$search[] = $searchArray;
}
echo json_encode($search);
$(function() {
$("#CurrentProv").autocomplete({
source: "inc/provider_term.php", //or you can use a callback here
minLength: 3,
change: function(event, ui) {
$("input#fid").val(ui.item.id);//or ui.item.desc perhaps
}
});

Categories