I am trying to make auto complater working in wordpress.
Here is my php code
function autocompleteCallback() {
global $wpdb; // this is how you get access to the database
//$whatever = $_POST['search_string'];
$name=$_POST['search_string'];
// echo'hiii'. $name='a';
$employee=$wpdb->get_results("SELECT `user_login` FROM wp_users WHERE user_login LIKE '$name%' ");
foreach($employee as $key=> $value){
$myarr[]=array('val' => $value->user_login);
}
//wp_reset_query();
echo json_encode($myarr);
die(); // this is required to return a proper result
}
add_action('wp_ajax_autocompleteCallback', 'autocompleteCallback');
add_action('wp_ajax_nopriv_autocompleteCallback', 'autocompleteCallback');
Here is my jquery
$(function() {
//function log( message ) {
// $( "<div>" ).text( message ).prependTo( "#log" );
// $( "#log" ).scrollTop( 0 );
// }
//alert('huii');
$("#se").autocomplete({
//dataType: "json",
source: function( request, response ) {
$.ajax({
url: './wp-admin/admin-ajax.php',
dataType: "json",
data: {
action: 'autocompleteCallback',
search_string:'a',
// term: $(options.fieldName).val()
},
success: function( data ) {
//alert(data);
alert('huii');
response( $.map( data.results, function( item ) {
return {
alert('hi');
label: item.val,
///value: item.title,
//url: item.url
}
}));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}
});
},
minLength: 1,
//select: function( event, ui ) {
// log( ui.item ?
// "Selected: " + ui.item.value + " aka " + ui.item.id :
// "Nothing selected, input was " + this.value );
// }
// select: function( event, ui ) {
// log( ui.item ?
// "Selected: " + ui.item.value + " aka " + ui.item.id :
// "Nothing selected, input was " + this.value );
// }
});
});
However, I could make this work in normal html, php web site where I passe source as a string. I can't figure where I have done mistake when I use function for source tag.
html code
<input id ="se" type="text" name="test" width="20" />
Why you dont just use this awesome plugin: SearchAutocomplete
Related
AJAX function should return HTML inside the div checkout-wrap in the same page. Instead, it redirects to a blank page and prints the array
Code in Controller:
return ['success'=>1, 'msg'=> trans('app.payment_received_msg'), 'response' => $this->payment_success_html()];
What is printed:
{"success":1,"msg":"Success","response":" <div class=\"payment-received\">\n <h1> <i class=\"fa fa-check-circle-o\"><\/i> Thank You<\/h1>\n \n <a href=\"http:\/\/localhost\" class=\"btn btn-filled\">Home<\/a>\n <\/div>"}
I'm using Laravel.
Ajax Function
$.ajax({
url : '{{route('pg_submit')}}',
type: "POST",
data: form,
success : function (data) {
if (data.success == 1){
$('.checkout-wrap').html(data.response);
toastr.success(data.msg, '#lang('app.success')', toastr_options);
}
},
error : function ( jqXhr, json, errorThrown ) {
var errors = jqXhr.responseJSON;
var errorsHtml= '';
$.each( errors, function( key, value ) {
errorsHtml += '<li>' + value[0] + '</li>';
});
toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
}
});
Route pg_submit
Route::post('checkout/pg', ['as' => 'pg_submit','uses' => 'CampaignsController#pgRedirect']);
Maybe you have action & method attribute on your form like
<form action="/checkout/pg" method="post">
You can remove the attributes and give the id or class to your from like this
<form id="pg_submit">
Than you can add or modify your script like this
$('#pg_submit').submit(function (e) {
e.preventDefault();
$.ajax({
url : '{{route('pg_submit')}}',
type: "POST",
data: form,
success : function (data) {
if (data.success == 1){
$('.checkout-wrap').html(data.response);
toastr.success(data.msg, '#lang('app.success')', toastr_options);
}
},
error : function ( jqXhr, json, errorThrown ) {
var errors = jqXhr.responseJSON;
var errorsHtml= '';
$.each( errors, function( key, value ) {
errorsHtml += '<li>' + value[0] + '</li>';
});
toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
}
});
});
I have the following jQuery code for the autocomplete,
$( "#text" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: 'GET',
url: 'server.php',
dataType: 'json',
data: {
input: request.term
},
success: function(data) {
response( $.map(data, function(item) {
return {
label: item.Symbol + " - " + item.Name + " ( " + item.Exchange + " )"
}
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
var symbol = ui.item.label.split(' ');
setTimeout(function() {
$('#text').val(symbol[0]);
},0);
}
});
Whenever a user enters a key in the textbox, an AJAX call is made to a PHP file. This PHP file will retrieve data from an API and update the suggestions list for the autocomplete feature?
I've got the following code in the PHP side,
<?php
if(!empty($_GET['term'])) {
$term = $_GET['term'];
$url = "http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=".$term;
$j_response = file_get_contents($url);
$j_response = json_decode($j_response);
print json_encode($j_response);
}
?>
For some reason, the autocomplete isn't working for me- what am I doing wrong here?
In the PHP, you are trying to use $_GET['term'], but in the JavaScript your variable is called input. Change the data object to use term not input:
data: {
term: request.term
},
I'm using this jquery plugin : JQuery Autocomplete. Problem I'm getting json data but it's not appearing on the autocomplete list.
The JQuery code:
$( "#student-id" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/ajax_admin.php?auto_student=" + $( "#student-id" ).val(),
dataType:"json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.students, function( item ) {
return {
label: item.id +" , "+ item.name,
value: item.id
}
}));
}
});
},
minLength: 2,
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
The PHP Script is :
public function load_ajax_student_list($val)
{
$val = "%".$val."%";
$stmt = $this->conn->prepare("select * from student where studentAiubId like :value limit 0,5");
$stmt->bindValue(':value', $val);
$stmt->execute();
if($stmt->rowCount() < 1)
echo "";
else
{
$result = $stmt->fetchAll();
$output = array();
foreach($result as $row)
{
if($row['mname']=="")
$name = $row['fname']." ".$row['lname'];
else
$name = $row['fname']." ".$row['mname']." ".$row['lname'];
$data["name"] = $name;
$data["id"] = $row['studentAiubId'];
$output["students"][] = $data;
}
echo json_encode($output);
}
}
If the call goes like this: ajax/ajax_admin.php?auto_student=10
The produced data from PHP script is :
{
"students": [
{"name":"Moh Mamun Sardar","id":"10-15987-1"},
{"name":"Rehan Ahmed","id":"10-12451-2"},
{"name":"Abid Hassan","id":"10-15412-1"},
{"name":"Abir Islam","id":"10-11245-1"}
]
}
But Nothing showing on autocomplete. What I'm doing wrong?
try something like this
$.map( data.students, function(item ) {
return {
label: item.name,
value: item.id
});
it is minlength not minLength see casing
You have forgotten the "appendTo" property. In this propery you have to specify the selector of the element you wish the information to be appended to like this
appendTo: '.class' or appendTo: '#id'
You have to add this property to the initialization of the autocomplete as a sibling of source and etc ...
I have been coding around with Google Geocoding until I found out that the Geocoding API may only be used in conjunction with a Google map. That is inconvenient because I don't need to display a map. So I switched to Geonames which is awesome!
I get the latitude and longitude of an address and add them to my database.
The code below is Jquery for a text input where users add their city/town and an auto-complete appears presuming the city they are typing. It works great but I also want to add the latitude and longitude of their city in 2 hidden form fields for sending to the database.
How is it possible to retrieve those coordinates from Geonames?
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).attr( "scrollTop", 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
The lat & lng are being returned; see this test request:
http://api.geonames.org/searchJSON?style=full&maxRows=12&name_startsWith=romse&username=demo
It is in the structure below so you just need to access it:
{ "geonames" : [ {
"adminCode1" : "ENG",
<SNIP>
"geonameId" : 2639189,
"lat" : 50.989057046475203,
"lng" : -1.4998912811279297
I need an example of how to code a jQuery autocomplete to populate product_id while showing the product_name calling an ajax page "remote.php"
<input name="product_name" id="product_name" type="text" value="" />
<input name="product_id" id="product_id" type="hidden" value="" />
remote.php:
$partial = addslashes($_POST['partial_search']);
$myDataRows = array();
$result = mysql_query ("SELECT product_id, product_name FROM products
WHERE product_name like "%$partial%");
while ($row = mysql_fetch_row($result)) {
array_push($myDataRows, $row);
}
$ret = json_encode ($myDataRows);
echo $ret;
I'm not sure how to code the jQuery autocomplete and if I need to change remote.php
thanks
ADDED LATER:
I worked out another solution:
<script type="text/javascript">
function nqi_search (type, id_name, text_name)
{
$( "#"+text_name ).autocomplete({
source: "remote.php?&t="+type,
minLength: 1,
select: function( event, ui ) {
$( "#"+id_name ).val(ui.item.id );
}
});
}
</script>
<script type="text/javascript">
jQuery(document).ready(function() {
nqi_search ("product_search", "product_id", "product_name");
// also you can have many on one page with:
nqi_search ("vendor_search", "vendor_id", "vendor_name");
});
</script>
There's one problem. it doesn't seem to work if the nqi_search function is put into a .js file. I have no idea why?
This is how I do it:
Note, I've coded a special feature where the json can flag an item as a message instead and in this way you can put messages in the list (eg I put a "Addition X items not shown" for long lists). To use the message feature, but the text in the label field and a true boolean for the message field.
To use this on the page I just have
setupAutocomplete(<id of textbox>,<path to service>);
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data) {
var msg;
if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
error: function(msg) {
$('#error').html(msg.responseText)
}
});
// remove this to get rid of custom message handling
$.widget("custom.redcomplete", $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var self = this;
$.each(items, function(index, item) {
if (item.message)
ul.append("<li class='ui-menu-item special-red'> " + item.label + "</li>");
else
self._renderItem(ul, item)
});
}
function setupAutocomplete(inID, inURL) {
var myTB = $("[id$='_" + inID + "']");
// change redcomplete to autocomplete to get rid of message handling
myTB.redcomplete({
source: function(request, response) {
$.ajax({
url: inURL,
data: "{'filter': '" + request.term + "'}",
success: function(data) {
response($.map(data, function(item) {
return {
label: item.text,
value: item.id,
// remove this line and the , above to get rid of message handling
message: item.message
};
}));
}
})
},
delay: 500,
minLength: 3,
focus: function(event, ui) {
myTB.val(ui.item.label);
return false;
},
select: function(event, ui) {
// action for the select here.
return false;
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});