I am working on a website in the codeigniter framework. I am stuck at a point where I need to implement the auto complete feature. I have tried a lot but I am not able to find proper solution so far. Here is what my actual requirements are.
There is a page on website that has few search filters. When a person lands on this page all the users of the website are shown on that page. Here the real game starts. There is a filter or an input box that filters out the results on the basis of their first or last name.
Say I have a database in which i have 3 users.
Ahmad Nawaz
John Azaar
Monica Finlay
When a person starts typing "Ah" in that search box I want that the sugesstions start to appear showing him "Ahmad"... Please tell me how to do that? I have searched a lot out there but i could not find a proper answer in reference to codeignitor. this is what my code looks like at the moment...
<input type="text" placeholder="Persons Name" name="individual_name" id="individual_name">
<script>
$(function() {
$( "#individual_name" ).autocomplete({
source: ('autocomplete_individual_name'),
select: function () {
testing()
}
});
});
</script>
just under the input I wrote the script....It goes to my mentioned controller. Here is what the controller looks like...
$individual_name = $this->input->post('individual_name');
$where = "first_name LIKE '".$individual_name."%' OR last_name LIKE '".$individual_name."%'";
$users_array = $this->user_profile_model->findByCondition($where);
First Problem
$individual_name is not getting populated.
Second Problem
When I receive the results in users_array, what should I do next? How to pass it back to show suggestions??
Third Problem
I use to call a filter function onkeyup(). Now when a person selects through the suggestion how to call the filter?
P.S->Also kindly let me know how can i reply to the person who replies me on this question...I have used # sign with user but it seems they dont get my reply thats why they never returned....
Any help would be highly highly appreciable...
Thanks and waiting
Ahmad
Try something like this, You may need to change the code slightly to suit you,
In your script part:
$("#individual_name").autocomplete({
source : base_url+"controller_name/suggest_names",
minLength : 1,
select: function( event, ui ) {
alert('id :'+ui.item.value) ;
//document.location.href = base_url+"controller_name/search?keyword="+ui.item.value; do something or redirect
},
success : function(resp){
//alert("auto");
},
error : function(){
alert("Oops, that didn't work. Please try again.");
}
});
In your controller:
function suggest_names(){
print_r ( $this->model_name->suggest_names($_REQUEST['term']) );
}
In your model part:
function suggest_names($term){
$data = array();
$term = strtolower( addslashes( trim( urldecode($term) ) ) );
$temp = $this->db->select('name as label, id as value')->like('name', $term, 'LEFT')->get('table_name')->result_array();
$data = json_encode($temp);
//echo "<pre>";print_r($data);echo "</pre>";die;
return $data;
}
Let me know if you face any problem. Hope it works for you.
Related
Please, explain to me how to run snippet CookieList with ajax?
I tried next:
1. Created snippet ajaxCookieList:
<?php
if (isset($_POST["action"])) {
$values = $modx->runSnippet('addToCookieLIst',array(
'value' => $_POST['action']
));
$output = $modx->runSnippet('pdoResources',[
'parents' => 6,
'resources' => $values,
'tpl' => 'popup.favorites.item',
'includeTVs' => 'header.bgImage,franchise.logo,franchise.price,title,subtitle',
'prepareTVs' => '1',
'hideContainers' => '1'
]);
return $output;
}
Then i created chunk with this code:
<script>
jQuery(function($){
$('a.franchise-pin, a.franchise-favorite-add').click(function(e){
var value = $(this).data('value');
$.post(document.location.href, {action: value}, function(data) {
$('#favorites').html(data);
$('#favorites').modal('show');
});
e.preventDefault();
});
});
</script>
But response is all page..
What is wrong?
What I usually do in such cases:
I place a snippet call ([[!ajaxCookieList]]) on a service page
accessible via URL like /page-with-snippet/
In JS (ajax) I use that URL to which I send parameters
The snippet has to get the parameters I send. So, I really call it like this: [[!ajaxCookieList? &action=[[!#POST.action]]]]
Access to parameters in snippets is possible like this: $option = $modx->getOption('action', $scriptProperties, 'default_value', true);
I do my stuff in the snippet
But in your case, I think, everything can be simpler. You use one of the pdoTools snippets and if I am not mistaken, you can just place pdoResources snippet call on a page (/page-with-snippet/) like this:
[[pdoResources?
&parents=`6`
&resources=`[[!addToCookieLIst? &value=`[[!#POST.action]]` ]]` // your snippet should return comma-separated list of resources` ids that you pass then to pdoResources
&tpl=`popup.favorites.item`
&includeTVs=`header.bgImage,franchise.logo,franchise.price,title,subtitle`
&prepareTVs=`1`
&hideContainers=`1`
]]
and now you can send parameters to this page (/page-with-snippet/) via AJAX and get the results if there are any. I hope I didn't mess anything - you had better check it again, but you get the idea at least :) BTW, check this article on modx.com that teaches how to write a good snippet.
Also another minor issue: as it has been pointed out here, the use of window.location is preferable to document.location.
Here is another solution I did. I used pdoResources. Hope that you will understand my code and customize it for yourselves.
Create snippet ajaxCookieList
Paste JS-code in your custom.js file
Simple markup for resources. Insert it in the chunk:
Add to wish list
Remove from wish list
Thas all:)
I have two different Facebook leads ad campaigns (A and B) connected to the same F.B page, I've connected it to a webhook following this guide using Facebook ads PHP sdk, and pass the leads to my C.R.M, everything works fine, the problem is that I can't tell if the lead came from form A or B.
I've tried to pull the from name like this:
$input = json_decode(file_get_contents('php://input'), true);
if($input)
{
$form_id = $input['entry'][0]['changes'][0]['value']['form_id'];
$form = AdsWebhookHandler::getFormName($form_id);
}
From the AdsWebhookHandlerclass:
public static function getFormName($form_id)
{
$form = new LeadgenForm($form_id);
if(!$form) return $form_id;
return $form->read();
}
But the form always returns empty ({}) for some reason.
Does anybody know how can I pull the form name? or even better - is it possible to pass custom hidden fields in the form?
Thank you all for an answer :)
O.K so I figure out how to get the form name, all I needed to do is use the getData() function included in the Facebook PHP SDK, my code looks like this now:
public function getFormName($form_id)
{
$form = new LeadgenForm($form_id,null,$this->fb_instance);
if(!$form) return $form_id;
$data = $form->read()->getData();
return isset($data['name']) ? $data['name'] : $form_id;
}
Hope it'll help someone in the future :)
I am trying to add custom button on top of post type page like this image
Is there any filter or action I can use to add custom button there?
Thanks
I found a way to get it done but I am not very happy with this procedure. Please add your answer if you find better way. Mean while, this might be of help.
add_action('admin_head-edit.php','addCustomImportButton');
I only need this on edit page, so I am using admin_head-edit.php action, but you can use admin_head or some other (not very specific requirement)
/**
* Adds "Import" button on module list page
*/
public function addCustomImportButton()
{
global $current_screen;
// Not our post type, exit earlier
// You can remove this if condition if you don't have any specific post type to restrict to.
if ('module' != $current_screen->post_type) {
return;
}
?>
<script type="text/javascript">
jQuery(document).ready( function($)
{
jQuery(jQuery(".wrap h2")[0]).append("<a id='doc_popup' class='add-new-h2'>Import</a>");
});
</script>
<?php
}
Digging into WordPress core code i did not find any hook or any filter for that buttonm you can also see that code from line no 281 to line number 288 . But you can add your button here according to this filter.
add_filter('views_edit-post','my_filter');
add_filter('views_edit-page','my_filter');
function my_filter($views){
$views['import'] = 'Import';
return $views;
}
Hope it helps you.
If you are using the class WP_Lists_table (and you should) then this is the right way to do it:
add_action('manage_posts_extra_tablenav', 'add_extra_button');
function add_extra_button($where)
{
global $post_type_object;
if ($post_type_object->name === 'shop_order') {
// Do something
}
}
The accepted answer is sadly still the only one that works.
But as the admin heading changed since it was answered, the correct script should now be :
jQuery(jQuery(".wrap .page-title-action")[0]).after('Import');
Unfortunately there is no hook called after showing the "Add New" button.
The closest possible place to add anything without using javascript is below the title and "Add new" like this:
In my example I added a button to my custom post type "Event" using the hook "edit_form_top":
add_action('edit_form_top', 'add_custom_button');
function add_custom_button($id){
if ($post->post_type != 'event') return false;
echo('<button>Custom button</button>');
}
The answer of Touqeer Shafi got me in the right direction, I needed to add a button at the top of my table view for a custom post type (book), I only had to change the post part in the views_edit-post to make it work:
add_action('views_edit-book', function($id) {
echo('Another new book');
});
Now in 2022 with WP 5.9.1, I combined answers from Geza Gog and Tameroski, and it works great:
add_action('edit_form_top', 'my_import_button');
function my_import_button(){
?>
<script type="text/javascript">
jQuery(document).ready( function($)
{
jQuery(jQuery(".wrap .page-title-action")[0]).after('Import');
});
</script>
<?php
}
I am using CakePhp 2.2.1 and I am having some problems to implement what I just asked in the title, I found several tutorials but most of them are for cakephp 1.3 and the others are not what I want to do. I have a "events" table which contains a "player_id" thus a Player has many Events and an Event belongs to a Player.
In my Event add form I proceed as the cookbook says and I get a dropdown list of players to choose from, however what I want is to just write the names of the players and select the one I want from the autocomplete results. Also these players must be from the team that I select before that. Any ideas?
Thanks in advance.
Special thanks to Andrew for pointing out this api.jqueryui.com/autocomplete. However there is not a real guide to use this one. So i found this post, which explains what Abhishek's second link says but I could understand it better. So here is my solution if anyone is interested:
1 - Download from the autocomplete page the .js you need. Save it in app/webroot/js
2 - Either in your app/View/Layouts/default.ctp or in the view you want to use the autocomplete add:
echo $this->Html->script('jquery-1.9.1.js');
echo $this->Html->script('jquery-ui-1.10.3.custom.js');
echo $this->fetch('script');
3 - In your view add (mine was add_goal.ctp):
<script>
$(document).ready(function(){
var myselect = document.getElementById("EventTeam"); //I needed to know which team I was looking players from.
var team = myselect.options[myselect.selectedIndex].value; //"EventTeam" was a dropdown list so I had to get the selected value this way.
$("#EventPlayer").autocomplete({
source: "/events/autoComplete/" + team,
minLength: 2, //This is the min ammount of chars before autocomplete kicks in
autoFocus: true
});
$("input:submit").button();
$("#EventPlayerId").autocomplete({
select: function(event, ui) {
selected_id = ui.item.id;
$('#EventAddGoalForm').append('<input id="EventPlayerId" type="hidden" name="data[Event][player_id]" value="' + selected_id + '" />');
}
});
$("#EventPlayerId").autocomplete({
open: function(event, ui) {
$('#EventPlayerId').remove();
}
});
});
</script>
4 - In your Controller (mina was EventController.php):
public function autoComplete($team = null){
Configure::write('debug', 0);
$this->autoRender=false;
$this->layout = 'ajax';
$query = $_GET['term'];
$players = $this->Event->Player->find('all', array(
'conditions' => array('Player.team_id' => $team, 'Player.name LIKE' => '%' . $query . '%'),
'fields' => array('name', 'id')));
$i=0;
foreach($players as $player){
$response[$i]['id']=$player['Player']['id'];
$response[$i]['label']=$player['Player']['name'];
$response[$i]['value']=$player['Player']['name'];
$i++;
}
echo json_encode($response);
}
visit below link ,this might help you as the ajax helper is no more in cake2.X versions core all related functionality moved to JS helper class.(here third one link for AJAX helper for contributed by user may help you)
http://bakery.cakephp.org/articles/matt_1/2011/08/07/yet_another_jquery_autocomplete_helper_2
or
http://nuts-and-bolts-of-cakephp.com/2013/08/27/cakephp-and-jquery-auto-complete-revisited/
or
http://bakery.cakephp.org/articles/jozek000/2011/11/23/ajax_helper_with_jquery_for_cakephp_2_x
You need to use ajax because your autocomplete-results depends on the team you have selected.
Something like this in jquery:
var team = $('#teamdropdown').find(":selected").text();
$.ajax({
type: "POST",
url: 'http://domain.com/playersdata',
data: {'team':team},
success: function(data){
console.log(data);
//put data in for example in li list for autocomplete or in an array for the autocomplete plugin
},
});
And in cake on playersdata page (Controller or model) something like this.
if( $this->request->is('ajax') ) {
$arr_players = $this->Players->find('all', array('conditions'=>array('team'=>$this->request->data('team')))); //pr($this->request->data) to get all the ajax response
echo json_encode($arr_players);
}
Also set headers to a json respons and $this->layout = null; to remove the layout tpl.
Another solution would be to use json_encode in your php and pass it to js-code like
<script>var players = <?php echo json_encode($array_players_with_teams); ?>; </script>
This solution is only interesting for a small amount of data, if you have a big database with teams and players I wouldn't recommend this, because why load all this data if you only need just a bit of it...
I didn't test the code but it should help you to go on...
Good luck!
I want to be able to edit the title of an article which is duplicated in a field called "url" which is updated in real time when the user types in the title field...how do I go about this?
Thanks
You could use jQuery. Have a look at the Manual.
$(function()
{
$('#field1').keyPress(function()
{
$('#field2').val($(this).val());
});
});
Working demo: http://jsfiddle.net/Wcp3D/
$("document").ready(function ($) {
$("input").bind('keyup', function() { $("lable").text($(this).val()) } );
});
<input type='text'/>
<label></label>
do you mean something like this?
I don't have my environment configured here at work, but it should be something like that:
$("#url").change(function() {
document.title = $(this).value();
});
Add a function to the change-event of field one, and update field two in that function:
$('#field1').change( function( ) {
$('#field2').value( $(this).value( ) );
}