jQueryUI Autocomplete data from text/csv file with $.ajax - javascript

I've been trying to amend the example from http://jqueryui.com/autocomplete/#maxheight to work with input from a locally stored text/csv file looking like
ItemA
ItemB
ItemC
....
I am able to create an array from the data in the textfile and print it to console.log() but I'm not sure how to hand over this array to the autocomplete function. I've tried initializing the array a outside the function but when using it in autocomplete it will use the non-populated array a.
</style>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "john.txt",
dataType: "text",
success: function(data) {processData(data);}
});
});
var a = [];
function processData(myTxt) {
var myLines = myTxt.split(/\r\n|\n/);
for (var i=1; i<myLines.length; i++) {
a.push(myLines[i]);
}
console.log(a);
}
$( "#tags" ).autocomplete({
source: a
});
</script>
How do I pass the array correctly to autocomplete?

I think you are trying to add autocomplete source before the AJAX query is completed.
The query is done on $(document).ready() but the autocomplete source is set before it. So a still remains empty.
Try this:
var a = [];
function processData(myTxt) {
var myLines = myTxt.split(/\r\n|\n/);
for (var i=1; i<myLines.length; i++) {
a.push(myLines[i]);
}
console.log(a);
$( "#tags" ).autocomplete({
source: a
});
}

Related

Simple Jquery POST call not working

I got a simple POST call to a PHP file on my website. For some reason it's not working though. The console.log shows"undefined"
function check() {
var url = "../API/keychecker.php";
var spullen = $("keyval").val;
$.ajax({
type: "POST",
url: url,
data: {
key: spullen
},
success: function(data) {
console.log(data);
}
})
}
Here is the PHP file:
<?php
echo json_encode($_POST['key']);
?>
Your keyval call doesn't specify the type of element identifier. jQuery won't find the element you're looking for as you currently have it.
You must specify:
For classes:
$( ".keyval" ).val();
For ID
$( "#keyval" ).val();
For input name
$( "input[name=keyval]" ).val();
That should attach the value to the POST request.
var url = "API/keychecker.php";
var spullen = $( "keyval" ).val();

Pass a return value from php to js

I have 3 files main.php, action.js and ajax.php and i successfully changed the content on click of some divs from main.php to some of ajax.php with a ajax call in my javascript file. It looks like this:
var value = $(this).attr("id");
$.ajax({
type: 'get',
url: "ajax.php",
data: {
auto_value: value
},
success: function(response) {
$('.gridnr1, .textnr1').fadeOut(400, function(){
$('.textnr2, .gridnr2').fadeIn(400);
});
var newtextcaption = $(response).filter('#newtextcaption').html();
var box = $(response).filter('#box').html();
$('#textnr2').html(newtextcaption);
$('#gridnr2').html(box);
for (var i=0; i<VALUE_FROM_AJAXphp; i++) {
DO SOMETHING WITH i;
}
});
Now i need a return value from a function in ajax.php in my action.js because I want to iterate till this value (see the code above).
How to pass this value from the ajax.php to the action.js.
I am confused what do I need to get the value ajax?, json? or something else?
Thank you.
in the success function, response, is what you get back from the PHP. so sending JSON would be easiest, because then your response is just an object.
Lets say ajax.php returns this JSON
{
"newtextcaption": "whatever the text is",
"boxhtml": "whatever your box html is",
"AjaxValue": 4389489473289
}
then your success function should be
success: function(response) {
$('.gridnr1, .textnr1').fadeOut(400, function(){
$('.textnr2, .gridnr2').fadeIn(400);
});
var newtextcaption = response.newtextcaption;
var box = response.boxhtml;
$('#textnr2').html(newtextcaption);
$('#gridnr2').html(box);
for (var i=0; i<response.AjaxValue; i++) {
DO SOMETHING WITH i;
}

JQuery Autocomplete and AJAX combination

I'm trying to implement auto-complete on a textbox in php. The data from autocomplete is retrieved using a GET ajax call (which calls a certain api and returns json output).
The code for my ajax was as follows:
<script type="text/javascript">
$(function() {
$( "#tags" ).keyup(function() {
var query = document.getElementsByName('newartist')[0].value;
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
console.log("1. " + obj[0]);
console.log("2. " + obj[1]);
}
});
});
});
</script>
This code was working perfectly find, and the output was shown in the console correctly. Next I tried adding this ajax call as "source" to my autcomplete call as follows:
<script type="text/javascript">
$(function() {
var query = document.getElementsByName('newartist')[0].value;
$( "#tags" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
var outp = [];
outp.push(obj.sections[0].data[0].name);
outp.push(obj.sections[0].data[1].name);
console.log(obj.sections[0].data[0].name);
console.log(obj.sections[0].data[1].name);
response(outp);
}
});
}
});
});
</script>
Here, the code stopped working for some reasons, and any console.log commands I had stopped outputting the results.
One other method I found as answer to a similar question was to implement the following code:
<script type="text/javascript">
$(function() {
$( "#tags" ).keyup(function() {
var query = document.getElementsByName('newartist')[0].value;
$.ajax({
type: "GET",
url: "https://lab.anghami.com/rest/v1/SEARCHedge.php",
data: "output=jsonhp&q=" + query,
dataType: "html",
success: function (data) {
var obj = JSON.parse(data);
var artists = [];
artists.push(obj[0]);
artists.push(obj[1]);
test(obj);
}
});
});
});
function test(data){
console.log(data);
$("#tags").autocomplete({
source: data
});
}
</script>
This was a bit better as autocomplete was indeed suggesting results, but it was inconsistent as it sometimes outputted 1 result instead of 2 (my ajax call ALWAYS returns 2 results, and I made sure that it's always the case by using console.log), and sometimes the suggestions proposed by autocomplete were those of the previous AJAX call and not the current one (again, console showed new results but autocomplete suggested previous ones.
If you could point to the errors in both of these methods, it would be great.
Thanks!!
Code looking fine. Please mention the JSON output format.

how to return an integer value from a php file using ajax method of jquery?

I have written a php code to find the number of jpg files in a directory
and here is the code.
<?php
$directory = $_POST['address'];
$num_files = 0;
$files = glob($directory."*.jpg");
$num_files = count($files);
echo $num_files;
?>
And I am using jquery's ajax method to send to and receive data from the php file. The code is as following.
$(document).ready(function(){
$('.mainnav li ul li').click(function(){
var parent_id = $(this).parent().attr('id');
var index = $(this).index();
var address = "images/"+parent_id+"/"+index+"/";
/*finding the number of files in the address directory*/
var number_of_files;
$.ajax({
type:"POST",
url: "numberoffiles.php",
data:{address:address},
success: function(data){
number_of_files = data;/*Line label:A*/
alert(number_of_files);
}
});
alert(number_of_files+2); /*this line is just for testing*/
/*end of number of files*/
for(var i=0;i<number_of_files;i++)
$('.thumbnail').append('<img src="'+address+i+'.jpg"></img>');
});
});
I get the value of the "number_of_files" correctly in the alert window without any error but I just can't convert its data type into an integer.
I have tried different ways to convert the data obtained from the php file into an integer but nothing has worked for me.
Following are what I have tried.
number_of_files = parseInt(data);/*Line label:A*/
Using the above line of code I get the value of "number_of_files" in the alert box correctly but any arithmetic operation with the "number_of_files" results into a NAN.
For example alert(number_of_files+2); returns a NAN.
I have also tried the following method.
number_of_files = parseInt(data.data);/*Line label:A*/
This line of code returns a NAN.
I have tried +data and Number(data) too but they don't work either.
So please tell me how I can do it.
You problem is that $.ajax is an Asyncronous method, meaning that the success function will be executed but you don't know when, meaning also that the code after the ajax function call will be executed right away.
You have 2 solution :
Setting "async" to false in your Ajax options (not recommended)
Moving all your "post ajax code" inside the success function
As a side note, javascript variables types are dynamic, meaning the JS engine will convert your variable as needed.
Edit : An exemple of 2nd option :
$(document).ready(function(){
$('.mainnav li ul li').click(function(){
var parent_id = $(this).parent().attr('id');
var index = $(this).index();
var address = "images/"+parent_id+"/"+index+"/";
/*finding the number of files in the address directory*/
var number_of_files;
$.ajax({
type:"POST",
url: "numberoffiles.php",
data:{address:address},
success: function(data){
number_of_files = data;
alert(number_of_files);
for(var i=0;i<number_of_files;i++)
$('.thumbnail').append('<img src="'+address+i+'.jpg"></img>');
}
});
});
});
success: function(data){
number_of_files = data;
alert(number_of_files);
alert(Number(number_of_files)+2); /*this line is just for testing*/
for(var i=0;i<number_of_files;i++)
$('.thumbnail').append('<img src="'+address+i+'.jpg"></img>');
}
user parseInt() function to convert string to integer inside the success function, call use the number_of_files in the success function only.
success: function(data){
number_of_files = parseInt(data);
alert(number_of_files);
}
$(document).ready(function(){
$('.mainnav li ul li').click(function(){
var parent_id = $(this).parent().attr('id');
var index = $(this).index();
var address = "images/"+parent_id+"/"+index+"/";
/*finding the number of files in the address directory*/
$.ajax({
type:"POST",
url: "numberoffiles.php",
data:{address:address},
success: function(data){
number_of_files = data;
alert(number_of_files);
}
}).done(function(){ /*this line is just for testing*/
/*end of number of files*/
for(var i=0;i<number_of_files;i++)
$('.thumbnail').append('<img src="'+address+i+'.jpg"></img>');
});
});
});
//instead of write code out of ajax you can use .done method also for more you refer http://api.jquery.com/jquery.ajax/

JQuery Autocomplete not working thougth values required are retrieved

I have following codes to implement an autocomplete for a form field
$( "#manager" ).change(function() {
var rows;
var manager = $(this).val();
var grouplist = $.post("<?php echo base_url();?>groups/getgrouplist/?"+"manager_name="+manager);
$( "#groups" ).autocomplete({ source: grouplist });
});
This is post response.
[{"personnel_name":"nab_group_1_1"},{"personnel_name":"nab_group_1_2"},{"personnel_name":"nab_group_2_1"}]
obiviously its getting required values and is working.
But autoocmplete is not displaying any values.
I have put an alert on grouplist and it display object object.
Can someone please suggest me how i can fix this and whats wrong here.
Thanks in advance.
Check what autocomplete consumes. I think your object is being cast as a string hence Object Object. If you are passing JSON to autocomplete then ensure your backend gives JSON as a response.
try something like this
$.post("<?php echo base_url();?>groups/getgrouplist/?"+"manager_name="+manager,function(response){
var grouplist = jQuery.parseJSON(response);
$( "#groups" ).autocomplete({ source: grouplist });
});
your autcomplete should be like this
EDITED CODE
$.post("<?php echo base_url();?>groups/getgrouplist/?"+"manager_name="+manager,function(response){
var grouplist = jQuery.parseJSON(response);
var new_data_source = $.map( grouplist, function( item ) {
return {
label: item.nab_group_1_1,
value: item.personnel_name
}
});
$( "#groups" ).autocomplete({ source: new_data_source });
});
json should be like [{"id":"your_id","label":"your_label"}]
while your json is different so you have to create json on success

Categories