Jquery - auto complete with clickable links - php

I have implemented search module with jqueryUI autocomplete in which search suggestions are rendered with their category.
Now i want to make those suggestions clickable,I've already tried select function but its not working,now i stuck in it
My Jquery Code is
$( function() {
$.widget("custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var that = this,
currentCategory = "";
$.each(items, function(index, item) {
if (item.category != currentCategory) {
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
}
that._renderItemData(ul, item);
});
}
});
$( "#search" ).catcomplete({
source : function(request,response){
var term = $("#search").val();
$.ajax({
type : "GET",
url : "ajax/auto_search.php",
dataType : "json",
data : {term : term},
success : function(data)
{
console.log(data);
response($.map(data.list, function(item) {
return {
value: item.content_title,
label: item.content_title,
category: item.category_name,
url : item.url
}
}))
},
select: function( event, ui ) {
//main problem is with item.content_title unable to get its value
window.location.href = 'search.php?mode=content_type&query='+item.content_title;
}
});
}
});
});
php code is
<?php
include '../includes/dbconfig.php';
header('Content-Type: application/json');
$searchTerm = $_GET['term'];
$sql = "SELECT distinct content_title, c.content_title,p.category_name,c.content_url from content_ref_table c inner join category_ref_table p on p.category_id = c.category_id where c.content_title LIKE '%".$searchTerm."%' ORDER BY c.content_title ASC LIMIT 0,10";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
$data_array = array();
while($row = mysqli_fetch_array($result))
{
$data_array['list'][] = array("content_title" => $row['content_title'], "category_name" => $row['category_name'],"url" => $row['content_url'] );
}
echo json_encode($data_array);
?>
**EDIT: how Can I store the item.content_title in a global variable?i think if i'm able to store the item.content_title in variable then it can solve my problem **

Related

Having trouble getting variable to pass to jquery

I have a save feature on my website so that the user can save an item. On the first click it updates and saves fine because it went through the PHP file, but what I am having trouble with is getting the ajax to update the link when clicked the second time since the link is created in the jquery code for updating it with AJAX. (passing the proper ID's is the problem) It should update the heart to red or green and add or remove the word 'Save'. I need to get the proper id updated on the second, third, etc. click.
Here is the jquery code:
I have 2 functions. saveLink and deleteLink.
This is my javascript file:
$(document).on("click", '.del-button', function () {
var savId = $(this).attr('data-sav-id');
deleteLink(savId);
});
$(document).on("click", '.sav-button', function () {
var delId = $(this).attr('data-del-id');
saveLink(delId);
});
function saveLink( saveID ){
var id = saveID;
$.ajax({
method: "POST",
url: "saveLink.php",
dataType: "json",
data: {
'id' : id,
},
success: function(returnID){
var returnID = $.trim(returnID);
if(returnID){
$('#showSaved' + id).html('<span id="removeSaved('+ id +');"><i class="fa fa-heart" style="color:#d52917;"></i></span>');
}
}
});
}
function deleteLink( deleteID ){
var deletedID = deleteID;
$.ajax({
method: "POST",
url: "deleteLink.php",
dataType: "json",
data: {
'deletedID' : deletedID,
},
success: function(deleteIDFunc){
var deleteIDFunc = $.trim(deleteIDFunc);
if(deleteIDFunc){
$('#removeSaved' + deletedID).html('<span id="showSaved('+ deletedID +');">Save <i class="fa fa-heart"></i></span>');
}
else {
alert('Your saved post was not removed. Please try again');
}
}
});
}
Here is the PHP code that handles the initial click:
$query = "SELECT
count(replies.reply_topic) as replyCount,
topics.topic_id,
topics.topic_subject,
topics.topic_date,
topics.topic_cat,
topics.topic_creator,
topics.topic_likes,
users.user_id,
users.username,
profile.profile_id,
profile.profile_pictureMain,
profile.profile_users,
savelink.saveLink_id,
savelink.saveUser_id,
savelink.link_id
FROM
topics
LEFT JOIN
users
ON
topics.topic_creator = users.user_id
LEFT JOIN
replies
ON
replies.reply_topic = topics.topic_id
LEFT JOIN
profile
ON
profile.profile_users = users.user_id
LEFT JOIN
savelink
ON
savelink.link_id = topics.topic_id
GROUP BY
topics.topic_id
ORDER BY
topics.topic_date DESC
LIMIT ?, ?
";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $start, PDO::PARAM_INT);
$stmt->bindParam(2, $limit, PDO::PARAM_INT);
$stmt->execute();
$returnAmt = $stmt->fetchAll();
if($stmt->rowCount() > 0){
$returnValues = "";
foreach($returnAmt as $row){
$returnValues .=
if(isset($_SESSION['user_session']) && $row['saveUser_id'] == $_SESSION['user_session']){
$returnValues .= '<span id="removeSaved'.$row['saveLink_id'].'"><i class="fa fa-heart" style="color:#d52917;"></i></span>';
}
else if(isset($_SESSION['user_session'])){
$returnValues .= '<span id="showSaved'.$row['topic_id'].'">Save <i class="fa fa-heart"></i></span>';
}
else{
$returnValues .= '</i>';
}
$returnValues .= '</div></div></span></div>
}
echo $returnValues;
Here is the html code for displaying the results:
<div role="tabpanel" class="tab-pane active" id="Top">
<div id="rowDisplayResults">
<!--Display results here-->
</div>
</div>
This is what I would like the save feature to look like. A red heart when saved and green when not.
Should I be adding another variable to the save and delete link functions to pass the proper ID's after the second click?
Any help would be much appreciated. thanks.
Change your code like this. Also change the html for this logic
$(document).on("click", '.del-button', function () {
var savId = $(this).attr('data-sav-id');
deleteLink(savId);
});
$(document).on("click", '.sav-button', function () {
var delId = $(this).attr('data-del-id');
saveLink(delId);
});
function saveLink( saveID ){
var id = saveID;
$.ajax({
method: "POST",
url: "saveLink.php",
dataType: "json",
data: {
'id' : id,
},
success: function(returnID){
var returnID = $.trim(returnID);
if(returnID){
$('#showSaved' + id).html('<span id="removeSaved('+ id +');"><a href="javascript:void();" class="del-button pull-right"'+
' data-sav-id=' + returnID + '"><i class="fa fa-heart" style="color:#d52917;"></i></a></span>');
//onclick="deleteLink('+ returnID +');
}
}
});
}
function deleteLink(deleteID) {
var deletedID = deleteID;
$.ajax({
method: "POST",
url: "deleteLink.php",
dataType: "json",
data: {
'deletedID': deletedID,
},
success: function (deleteIDFunc) {
var deleteIDFunc = $.trim(deleteIDFunc);
if (deleteIDFunc) {
$('#removeSaved' + deletedID).html('<span id="showSaved(' + deletedID + ');"><a href="javascript:void();" '+
'class="pull-right sav-button" data-del-id=' + deleteIDFunc + '">Save <i class="fa fa-heart"></i></a></span>');
}
//onclick="saveLink(' + deleteIDFunc + ');
else {
alert('Your saved post was not removed. Please try again');
}
}
});
}

jquery select2: error in getting data from php-mysql

I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.

Codeigniter loading ajax request

Trying to add some ajax functionality within a voting system and it's not working. I'm wanting to send a post request to the database and update the count value. Problem I'm running into is that I can't seem to get the ajax request tow work within the MVC.
I do want to retain the MVC structure.
The jquery code is:
<script>
$( document ).ready(function() {
$( "#vote li a" ).each(function( index ) {
$(this).click(function(){
$.ajax = ajax();
var id = $(this).attr('data-scenario-id');
var value = $(this).attr('data-value');
$.ajax({
url: "ajax-vote.php",
cache: false,
data: { id: id, value: value }
})
.done(function( html ) {
$(this).html( html );
});
return false;
});
});
});
and the php code currently residing in ajax-vote.php is:
$id = isset($_GET['id']) ? $_GET['id'] : null;
$value = isset($_GET['value']) ? $_GET['value'] : null;
$query = $this->db->query('SELECT count FROM total_counts WHERE scenario_id = ' . $id . ' AND interaction_id = ' . $value);
$row = $query->row();
$count = $row->name;
$count++;
$query = $this->db->query('UPDATE total_counts SET count = ' . $count);
$query = $this->db->query('SELECT count FROM total_counts WHERE scenario_id = ' . $id . ' AND interaction_id = ' . $value);
$row = $query->row();
$count = $row->name;
switch ($value) {
case 1:
$text = 'OK '. $count;
break;
case 2:
$text = 'NOT OK'. $count;
break;
case 3:
$text = 'ABUSE'. $count;
break;
}
echo ''. $text .'';
Thanks in advance.
If you are working with codeigniter than you than you have to give controller path in the url. I am assuming your controller name is ajax-vote.php than your ajax code would be
$( document ).ready(function() {
$( "#vote li a" ).each(function( index ) {
$(this).click(function(){
$.ajax = ajax();
var id = $(this).attr('data-scenario-id');
var value = $(this).attr('data-value');
$.ajax({
url: "<?php echo base_url(); ?>ajax-vote",
cache: false,
data: { id: id, value: value }
})
.done(function( html ) {
$(this).html( html );
});
return false;
});
});
});
You must put your code into a controller, not in a simple php file! Then you can pass to javascript the codeigniters site_url path like this:
<script> var site_url = '<?php echo site_url()?>';</script>
You must do this in your header view.
then later in your ajax call you can use this variable to build the path:
$.ajax({
url: site_url + "ajaxcontroller/vote",
cache: false,
data: { id: id, value: value }
})
.done(function( html ) {
$(this).html( html );
});
now you have php and javascript separated.
Of course you have to do an AjaxController extending CI_Controller, and put your code inside a function called "ajax" (or whatever you want, just make sure to use the same name what you used in the js call)

order by name in select box is not working in google chrome and IE

I have a function which is returning the list of city names associated to city_id ordered by city name.
I want to show them in a select box. In Firefox (23.0.1) it is working fine even with order. But in case of IE (10) and chrome (29.0.1547.66 m) the order is not correct. I am using PHP and zend framework. My code:
$cities = $countryCityModel->getCities($country);
print json_encode(array('status'=>'Success',
'data'=>$cities)
);
public function getCities($countryId){
if(!$countryId)
return false;
$mdb = $this->getOldDbAdapter();
$sql = $mdb->select()
->from('cities', array('city_id','city'))
->where('country_id = ?', $countryId)
->order("city");
return $mdb->fetchPairs($sql);
}
$.ajax({
url : baseUrl + '/lead/index/get-cities',
dataType : 'json',
data : {
country:country_id
},
beforeSend : function(){
$("#holder_popup").show();
},
complete: function(){
$("#holder_popup").hide();
},
success : function(res) {
var sbuOptions = "<option value=''>--SELECT--</option>"
if(res.status == 'Success'){
for(i in res.data){
sbuOptions += "<option value='"+i+"'>"+res.data[i]+"</option>";
}
$("#city").html(sbuOptions);
}else{
$("#city").html(sbuOptions);
alert(res.msg);
}
},
error : function(jqXHR, exception) {
}
});
The returned value is like the following:
{
"status":"Success",
"data":{
"53029":"DURRES",
"53331":"ELBASAN",
"40239":"FIER",
"16235":"KAMEZ",
"42191":"KAVAJE",
"41375":"KUKES",
"53581":"PESHKOPI",
"57686":"SHIJAK",
"56756":"SHKODER",
"4496":"TIRANA",
"41342":"VLORE",
"19454":"VORE"
}
}
Please help me, how to resolve this issue?
can you update your code to this
public function getCities($countryId)
{
$resultArrary = array();
if($countryId)
{
$mdb = $this->getOldDbAdapter();
$sql = $mdb->select()
->from('cities', array('city_id','city'))
->where('country_id = ?', $countryId)
->order("city");
$result = $mdb->fetchAll($sql);
foreach($result as $key => $city )
{
$resultArrary[$key]['id'] = $city['city_id'];
$resultArrary[$key]['city'] = $city['city'];
}
}
return $resultArrary;
}
for(i in res.data)
{
cityData = res.data[i];
sbuOptions += "<option value='"+cityData.id+"'>"+cityData.city+"</option>";
}
Seems like chrome is auto sorting the json object with the index.
REF:
Chrome and IE sorts JSON Object automatically, how to disable this?
https://code.google.com/p/chromium/issues/detail?id=37404
You are missing ASC or DESC at line 12
->order("city ASC");

select2 to redirect on click

I am using the select 2 plugin to search for users. Everything is up an running an my jsons end up with: [{"id":"1","text":"Alex Fagard (afagard) ID: 1"}] .etc.
I am using the following code to build the select 2 interface:
$(document).ready(function(){
$('#username-search').select2({
minimumInputLength: 2,
select: function(event, ui) {
AutoCompleteSelectHandler(event, ui)
},
ajax: {
url: "classes/search.class.php?sType=users",
dataType: 'json',
data: function (term, page) {
return {
term: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
});
However I am stuck on how to make it so that when the admin selects a user (aka clicks on their dropdown area) the page redirects to userview.php?id=1 where 1 is the id from the JSON array.
Search function if anyone is interested:
public function searchUsers($term = '') {
if (isset($term)) {
$term = parent::secure($term);
$params = array( ':searchQ' => $term . '%' );
$sql = "SELECT distinct username as suggest, user_id, name
FROM login_users
WHERE username LIKE :searchQ
OR name LIKE :searchQ
OR user_id LIKE :searchQ
ORDER BY username
LIMIT 0, 5";
$stmt = parent::query($sql, $params);
if ( $stmt->rowCount() > 0 ) {
while($suggest = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'id' => $suggest['user_id'],
'text' => $suggest['name'] . ' (' . $suggest['suggest'] . ')' . ' ID: ' . $suggest['user_id'],
);
}
} else {
$data[] = array('id'=>'0', 'text'=>'No results found!');
}
echo json_encode($data);
flush();
}
}
$searchParam = new Search();
if (isset($_GET['term'])) {
// we secure the term before running the search and querying the database
$term = $_GET['term'];
switch (isset($_GET['sType']) ? $_GET['sType'] : NULL) {
case 'users':
$searchParam->searchUsers($term);
break;
case 'levels':
$searchParam->searchLevels($term);
break;
}
}
Version 4.0 +
Events are now in format: select2:selecting (instead of select2-selecting)
$("#search").on("select2:selecting", function(e) {
window.location.href = 'user_edit.php?id=' + e.val;
});
Came across the same question a year after posting this and googled something and ended up here forgetting I ever posted it in the first place.
Well found a solution:
<script>
$(document).ready(function () {
$("#search").select2({
ajax: {
url: "users.php",
dataType: 'json',
data: function (term) {
return {
term: term,
};
},
results: function (data) {
return {results: data};
}
}
});
$("#search").on("select2:selecting", function(e) {
window.location.href = 'user_edit.php?id=' + e.val;
});
});
</script>
Event name is select2:selecting

Categories