Jquery mobile autocomplete implementation with local json - ajax

I am trying to implement the jquery mobile autocomplete functionality, because i have a list of around 3000 items.
I have a json that has this structure:
[{"v1":" abcd","v2":"http://www.url.nl","v3":0487,"v4":"street12","v5":"H"},
{"v1":" qq","v2":"http://www.url.nl","v3":0297,"v4":"street14","v5":"A"},
{"v1":" zz","v2":"http://www.url.nl","v3":0117,"v4":"street55","v5":"A"}]
I am using this example: http://jquerymobile.com/demos/1.3.0-rc.1/docs/demos/widgets/autocomplete/autocomplete-remote.html
but i can not get this to work with my json file.
$( document ).on( "pageinit", "#myPage", function() {
$( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
I have the feeling that it has to with the ajax call and my json file, but I haven't found the solution yet.

Related

Tabulation added to returned ajax call data

my problem is that whenever I do an ajax call and console.log the returned data, there is a tabulation in front of my returned data. Is this normal? If so, is there a way to strip the tabulation from the data variable? My code is below.
function search_rhymes_get_rhyme_content() {
echo 'Test';
die();
}
$.ajax( {
url: rhymes_ajax_obj.ajaxurl,
data: {
'action': 'search_rhymes_get_rhyme_content'
},
success: function( data ) {
console.log( 'Test:' + data );
},
error: function( error ) {
console.log( error );
}
} );
Thanks
I got it working. Output: https://ibb.co/QQHGgXV
I added the following line before my console.log:
data = data.trim();
Here's the updated code with the solution:
function search_rhymes_get_rhyme_content() {
echo 'Test';
die();
}
$.ajax( {
url: rhymes_ajax_obj.ajaxurl,
data: {
'action': 'search_rhymes_get_rhyme_content'
},
success: function( data ) {
console.log( 'Test1:' + data );
data = data.trim();
console.log( 'Test2:' + data );
},
error: function( error ) {
console.log( error );
}
} );

Load more posts with AJAX and also add pagination in URL

On load more button, posts load without page load using AJAX, but wanted to implement Wordpress pagination on load more along with URL changing. Suggestions are welcome.
/* Category/tag page Masonry Grid */
var $mgrid = $( '.post-grid' ).masonry();
$mgrid.masonry( {
itemSelector: '.post-outer',
} );
/* ------------------ Load More Posts Category/tag page ------------------ */
$( document ).on( 'click', '#post-button', function(e) {
e.preventDefault();
var offset = $( this ).attr( 'data-value' );
var cat = $( this ).attr( 'data-cat' ); //load more button attribute
var tag = $( this ).attr( 'data-tag' ); //load more button attribute
var page = $( this ).attr( 'data-page' ); //load more button attribute
var $content;
$.ajax( {
type: "post",
async: false,
dataType: "json",
url: localizeObj.ajaxurl, //localize script in functions.php
data: {
action: 'fetch_posts', //ajax load more function in functions.php
offset: offset,
cat: cat,
tag: tag,
page: page,
search_term: localizeObj.search_term,
current_page: localizeObj.current_page
},
beforeSend: function() {
},
success: function(response) {
/* Adding page numbers on ajax load more */
var pathname = window.location.pathname;
if ( response.success == 'yes' ) {
$content = $(response.posts);
$( '.post-masonry-grid' ).append( $content ).masonry( 'appended', $content );
page = parseInt(page) + 1;
offset = parseInt(offset) + 6;
$('.post-grid-outer').each( function() {
$('.post-grid-outer').addClass(offset);
});
$( '#post-grid-button' ).attr( 'data-value', offset );
$( '#post-grid-button' ).attr( 'data-page', page );
var page_num = '';
if(page <= 2) {
var page_num = 'page/'+ page;
} else {
var page_num = page;
}
window.history.pushState("URL", "Title", page_num); // Add page numbers to URL
} else {
$( '#post-button' ).hide();
}
},
complete : function() {
}
} );
} );

Not resolved promises with File objects after POST form requests

I'm using fetch Web API to retrieve file content from a couple of URLs and send it to a form. However, when sent to the backend from a form POST ajax request, instead of having the actual File Objects there, I'm retrieving Promise objects (which cannot be handled at the backend).
What is wrong in the code below that prevents infile and mapfile variables when sent to $.ajax to have a File object?
let formData = new FormData();
let exampleb2pPromise = fetch( fileHash["infile"].fileURL).then(function(response) {
fileHash["infile"].blob = response.blob();
return fileHash;
}).then(function(fileHash) {
let infile = new File( [ fileHash["infile"].blob ], fileHash["infile"].filename, { type: fileHash["infile"].filetype } );
return infile;
});
let exampleCSVPromise = fetch(fileHash["mapfile"].fileURL).then(function(response) { ...
Promise.all([exampleb2pPromise, exampleCSVPromise]).then(function(values) {
let infile = values[0];
let mapfile = values[1];
if ( infile && mapfile ) ) {
console.log( infile );
formData.append( "infile", infile, "input.tsv" );
if ( mapfile ) {
console.log( mapfile );
formData.append( "mapfile", mapfile, "mapfile.txt" );
}
}
return formData;
}).then( function( formData ) {
let exec = "/submit";
console.log( formData );
$.ajax({
url : exec,
type: "POST",
data : formData,
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR){
if ( data && data.session ) {
...
}
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
// TODO: To be handled
}
});
});
response.blob() returns a Promise - you'd need to rewrite your code something like
let exampleb2pPromise = fetch( fileHash["infile"].fileURL).then(function(response) {
return response.blob();
}).then(function(blob) {
fileHash["infile"].blob = blob;
return fileHash;
}).then(function(fileHash) {
let infile = new File( [ fileHash["infile"].blob ], fileHash["infile"].filename, { type: fileHash["infile"].filetype } );
return infile;
});
Although, it's far easier to write it like:
let exampleb2pPromise = fetch( fileHash.infile.fileURL)
.then(response => response.blob())
.then(blob => new File(fileHash.infile.blob = blob, fileHash.infile.filename, { type: fileHash.infile.filetype } ));

Uncaught TypeError: this.source is not a function

I want to prelaod all the customers and give it to the autocomplete whenever needed. I have this error caught up. The group search is global across the application.
<script>
$(document).ready(function() {
var customers = $.ajax({
url: "http://localhost:8081/customers/all",
type: 'GET',
dataType: 'json',
success: function (data) {
$.map(data, function (v, i) {
return {
number: v.number,
name : v.name,
};
});
}
});
$("#customer-search").autocomplete({
minLength: 0,
source: customers,
select: function( event, ui ) {
$( "#group-search" ).val(ui.item.name);
$("#group-search-form").submit();
return false;
},
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.name + " " + item.number + "</div>" )
.appendTo( ul );
};
});
</script>
Initialize autocomplete after ajax request complete, like below:
Try this:
$(document).ready(function() {
var customers = [];
$.ajax({
url: "http://localhost:8081/customers/all",
type: 'GET',
dataType: 'json',
success: function (data) {
$.map(data, function (v, i) {
return {
number: v.number,
name : v.name,
};
});
$("#customer-search").autocomplete({
minLength: 0,
source: customers,
select: function( event, ui ) {
$( "#group-search" ).val(ui.item.name);
$("#group-search-form").submit();
return false;
},
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.name + " " + item.number + "</div>" )
.appendTo( ul );
};
}
});
});

Cakephp 2.1 and Jquery UI autocomplete

Mission:
Implement autocomplete of departments(saved in departments table) in employee form field called department.
A user enters a few spellings of department name
That brings up list of the names matching departments
The user select one and that's it.
Platforms
CakePhp 2.1
Jquery UI Autocomplete(part of Jquery UI library version 1.8.18)
Database Model
Emplyee (id, first_name,last_name,department_id)
department(id,name)
so in my add.ctp file ajax call is something like
$( "#auto_complete" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/employees/showDepartment",
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
alert("success--");
response( $.map( data, function( item ) {
//alert(item);
return {
label: item.name,
value: item.id
}
}));
}
});
},
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" );
}
});
i have a action in my EmployeeController called show_depatment()
public function getAddress() {
$this->autoRender = false;// I do not want to make view against this action.
$this->log($this->params->query['name_startsWith'] , 'debug');
$str = $this->params->query['name_startsWith'];
$this->log($str, 'debug');
$this->layout = 'ajax';
$departments = $this->Employee->Department->find('all', array( 'recursive' => -1,
'conditions'=>array('Department.name LIKE'=>$str.'%'),
'fields'=>array('name', 'id')));
//$this->set('departments',$departments);
$this->log($departments, 'debug');
echo json_encode($departments);
}
I dont want show_department action to have any view so i have made $this->autoRender = false;
but it is not working as expected.
when i debug the response using firebug in response and HTLM section it shows
[{"Department":{"name":"Accounting","id":"4"}}] // when i type "acc" in input field
Question
How to make it to display in form field.
echo json_encode($departments); is it right method of sending response in json format?
when i alert in sucess part of ajax call (alert(item);) it gives error as "undefined"
i'm friend of fat Model and skinny Controller so my Controller action looks like this
public function getAddress()
{
if($this->RequestHandler->isAjax()) {
Configure::write('debug', 0);
$this->layout = 'ajax';
$this->autoRender = false;
echo json_encode($this->Employee->Department->getAddress($this->params['url']['term']));
exit;
}
}
and my Department model method:
public function getAddress($str)
{
$rs = array();
$search = $this->find('all', array(
'recursive' => -1,
'conditions'=>array('Department.name LIKE'=>$str.'%'),
'fields'=>array('name', 'id')
));
if (!empty($search))
{
//the jquery ui autocomplete requires object with label/value so we need to traverse the query results and create required array
foreach ($search as $key => $val)
{
$rs[] = array('label' => $val['Department']['name'],
'value' => $val['Department']['id']);
}
}
return $rs;
}
and finaly my view entry is like this:
$( "#auto_complete" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "/employees/showDepartment", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
}
});
hope this helps.

Resources