Materialize autocomplete : Why AJAX called before entering any character? - ajax

I'm using autocomplete with materialize and i'm retrieving the data with ajax call, it works fine but when i want to call ajax only after entering caracters(using onkeyup event), the drop down list will not be showing correctly !!!!
Before i forget please help me to show a "NOT FOUND" in the drop down list if no data founded (because my else condition doesn't work). here is my code and thanks a lot in advance :
$(document).ready(function() {
var contents = $('#autocomplete-input')[0];
contents.onkeyup = function (e) {
$.ajax({
type: 'GET',
url: Routing.generate('crm_search_lead', {"search":
$(this).val()}),
success: function (response) {
var contacts = {};
if (true === response.success) {
var result = response.result;
for (var i = 0; i < result.length; i++) {
var lastName = result[i].lastName ?
result[i].lastName : '';
var firstName = result[i].firstName ?
result[i].firstName : '';
contacts[lastName + " " + firstName] = null;
}
$('input.autocomplete').autocomplete({
data: contacts,
minLength: 2,
});
} else {
$('input.autocomplete').autocomplete({
data: {
"NOT FOUND": null
}
});
}
}
});
}
});

Hi people :) i resolve it by changing onkeyup() with focus() and it's totally logical because with onkeyup() the droplist will appear and disappear very quickly on every key entered.

Related

How to pass all loop value and pass to ajax?

Why it returns only the last number of my database? I wanted to return all value inside the div. Help me.
Ajax
$.ajax({
url : 'Test.php',
method : 'post',
data : {id: id},
success : function(response)
{
var x = $.parseJSON(response);
for (var a in b)
{
$('#allValue').html(b[a]);
}
}
});
PHP
if(isset($_POST['id']))
{
$query = mysqli_query($conn, "SELECT * FROM tbl_reservation");
while ($row = mysqli_fetch_array ($query))
{
$result[] = array($row['ID_reservation']);
}
echo json_encode($result);
}
By doing
$("#element").html("TEST");
The HTML method removes any existing content and replaces it with "TEST". If you want to append text you could first get the HTML value, but better yet:
var x = $.parseJSON(response);
var text = "";
for (var a in b)
{
text += b[a];
}
$('#allValue').html(text);

Dragula not sending AJAX request

I am using the following code to sort the rows of a table based on Ids. I am using Dragula for drag and drop functionality. The Sorted Ids is presented in the variable sortedIDs. The alert present within if(sortedIDs) is showing an alert, but no request is being sent using AJAX.
var container = document.getElementById('tb');
var rows = container.children;
var nodeListForEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
var sortableTable = dragula([container]);
var pingu='';
sortableTable.on('dragend', function() {
nodeListForEach(rows, function (index, row) {
//alert(row.id);
pingu=pingu+','+row.id;
//alert(pingu);
// row.lastElementChild.textContent = index + 1;
// row.dataset.rowPosition = index + 1;
});
var sortedIDs=pingu;
pingu='';
// alert (sortedIDs);
if (sortedIDs) {
alert(sortedIDs);
$.ajax({
type: 'GET',
url: '<?php echo $site_url . 'index.php/API/p2376ghDSPOLWYBdhBT'?>',
data: 'lmqSPOEhyVt87H6tBYSfdreg=' + sortedIDs + '&hjhqweuty87685gh87GCfsc6HF=' + sbds98JWUDGHKJ98yujg,
success: function (tata) {
alert (tata);
if (tata == '1') {
$("#success").show();
$('#success').delay(2000).fadeOut('slow');
} else {
$("#failure").show();
$('#failure').delay(5000).fadeOut('slow');
}
}
});
} else {
//$('#ms').html('<option value="">Select Q level first</option>');
}
});
And when i am adding
error : function(jqXHR, textStatus, errorThrown){
}
for showing AJAX error, it starts throwing the alert too.
Any sort of help would be deeply appreciated.
Thanks
I solved the problem. I forgot to retrieve the value of an attribute and send it to the API.
var sbds98JWUDGHKJ98yujg = $('#p2JMopns3hfBubNNHJeer').val();

HighStocks not updating URL

I posted this question AJAX URL update as I thought the problem with my code was with AJAX but I think this could be an issue with HighStocks.
I have an external .js file with these functions:
//uses AJAX call to retrieve data and then creates the chart with the data
function createChart(ticker) {
$.ajax({
type: 'post',
url: 'http://...' + ticker + '....com',
success: function (data, status) {
//chart is rendered in here
}
//gets the user inputted ticker symbol from a HTML input box
// and passes to chart function
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
My HTML file just has a simple form with an input box and a button that when clicked calls the getTicker function. For some reason the chart is not being created and the AJAX call doesnt seem to work.
Is this something with HighStocks maybe? Any suggestions would be appreciated.
UPDATE Thank you for the suggestions, I have attempted to use JSONP but the chart still does not load. Can anybody see what I am doing wrong?
var closePrices = new Array();
var dateArray = new Array();
var timeStampArray = new Array();
var timeClose = new Array();
function jsonCallback(data, ticker) {
console.log( data );
//Put all the closing prices into an array and convert to floats
for(var i=0; i < data.query.results.quote.length; i++)
{
closePrices[i] = parseFloat( data.query.results.quote[i].Close );
}
//displays the values in the closePrices array
console.log( closePrices );
//Put all the dates into an array
for(var i=0; i < data.query.results.quote.length; i++)
{
dateArray[i] = data.query.results.quote[i].date;
}
//Convert all the dates into JS Timestamps
for(var i=0; i < dateArray.length; i++)
{
timeStampArray[i] = new Date( dateArray[i] ).getTime();
}
for(var i=0; i<data.query.results.quote.length; i++)
{
timeClose.push( [timeStampArray[i], closePrices[i]] );
}
timeClose = timeClose.reverse();
console.log ( timeClose );
//displays the dateArray
console.log( dateArray );
console.log( timeStampArray );
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : ticker + ' Stock Price'
},
series : [{
name : ticker,
data: timeClose,
tooltip: {
valueDecimals: 2
}
}]
});
}
function createChart() {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + ticker +'%22%20and%20startDate%20%3D%20%222013-01-01%22%20and%20endDate%20%3D%20%222013-02-25%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
//Ajax call retrieves the data from Yahoo! Finance API
$.ajax( url, {
dataType: "jsonp",
success: function(data, status){
console.log(status);
jsonCallback(data, ticker);
},
error: function( jqXHR, status, error ) {
console.log( 'Error: ' + error );
}
});
}
//Function to get ticker symbol from input box.
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
Thanks to Jeffrey Blake and Pawel Fus for your suggestions. Using JSONP I was able to get my program functioning correctly :)

Conditionally pause Javascript to wait for ajax

The variable ajaxdata is modified within the success function, if that hasn't been done yet, I would like to wait 2 seconds, then continue without it.
The use case is for a jqueryui autocomplete field. The autocomplete source is an ajax request, but if the user types quickly, and exits the field before the list loads, the field remains unset. Using the 'change' event on the autocomplete I check if the user entered a valid option without selecting it, but this doesn't work if the source hasn't loaded when the change event fires. So I would like to put a delay in the change function which waits, if the source (stored in the variable 'ajaxdata') is empty.
code:
input.autocomplete({
source: function (request, response){
$.ajax(
{
type: "GET",
url: "/some/url",
dataType: "json",
success: function(data){
response($.map(data,function(item){
return{
label: item.label,
value: item.value
}
}));
ajaxdata = data;
}
}
);
// ajaxopts = ajaxsource(request,response,ajaxurl,xtraqry)
},
change: function(event, ui) {
if (!ui.item) {
// user didn't select an option, but what they typed may still match
var enteredString = $(this).val();
var stringMatch = false;
if (ajaxdata.length==0){
/// THIS IS WHERE I NEED A 2 SECOND DELAY
}
var opts = ajaxdata;
for (var i=0; i < opts.length; i++){
if(opts[i].label.toLowerCase() == enteredString.toLowerCase()){
$(this).val(opts[i].label);// corrects any incorrect case
stringMatch = true;
break;
}
}
}
},
});
Edit:
To be more specific about the problem: This delay needs to be conditional. Meaning that if the data is already loaded (either because it came from a static source, or from an earlier ajax call) I do not want to have a delay.
If I'm understanding you properly, I think you just want to check and see if ajaxdata has been populated; but if it hasn't, only wait two more seconds and then just proceed without it.
Try this:
change: function(event, ui) {
if (!ui.item) {
// user didn't select an option, but what they typed may still match
if (ajaxdata.length==0){
/// THIS IS WHERE I NEED A 2 SECOND DELAY
//pass in 'this' so that you can use it
setTimeout(function() {correctCase(this);}, 2000);
}
}
}
. . . . .
function correctCase(inThis){
//I'm not sure what this variable does. do you really need it???
var stringMatch = false;
var enteredString = $(inThis).val();
//you still want to be sure that ajaxdata is not empty here
if (ajaxdata.length==0){
var opts = ajaxdata;
for (var i=0; i < opts.length; i++){
if(opts[i].label.toLowerCase() == enteredString.toLowerCase()){
$(inThis).val(opts[i].label); // corrects any incorrect case
stringMatch = true; //this variable doesn't seem to do anything after this???
break;
}
}
}
}
I'm not really sure what it is you're trying to do, but I'm pretty sure something like this would be a better way of doing it :
input.autocomplete({
source: function(request, response) {
return $.ajax({
type: "GET",
url: "/some/url",
dataType: "json"
});
},
change: function(event, ui) {
if (!ui.item) {
// user didn't select an option, but what they typed may still match
var enteredString = this.value;
var stringMatch = false;
//make sure ajax is complete
this.source().done(function(data) {
var opts = $.map(data, function(item) {
return {
label: item.label,
value: item.value
}
});
for (var i = 0; i < opts.length; i++) {
if (opts[i].label.toLowerCase() == enteredString.toLowerCase()) {
$(this).val(opts[i].label); // corrects any incorrect case
stringMatch = true;
}
}
});
}
}
});​
By default, JavaScript is asynchronous whenever it encounters an async function, it queued that function for later.
But if you want a pause js(ajax call or anything) for you can do it use promises
Case 1: output hello(will not wait for setTimeout)
https://jsfiddle.net/shashankgpt270/h0vr53qy/
//async
function myFunction() {
let result1='hello'
//promise =new Promise((resolve,reject)=>{
setTimeout(function(){
resolve("done");
result1="done1";
}, 3000);
//});
//result = await promise
alert(result1);
}
myFunction();
case 2: output done1(will wait for setTimeout)
https://jsfiddle.net/shashankgpt270/1o79fudt/
async function myFunction() {
let result1='hello'
promise =new Promise((resolve,reject)=>{
setTimeout(function(){
resolve("done");
result1="done1";
}, 3000);
});
result = await promise
alert(result1);
}
myFunction();

listview('refresh') not working

In my application listView('refresh') doesn't work. Here is my code
I create listView dynamically
var str = "<ul data-role='listview' data-inset='true' id='mylist'>";
for(var i = 0; i<data.length; i++ ){
str += "<li>"+data[i].note.text+"</li>";
}
str += "</ul>"
$('#content').append(str);
function addnote(){
var note_text = $('#note_text').val();
var note_lat = $('#lat').val();
var note_lng = $('#lng').val();
$.ajax({
type: "POST",
beforeSend: function (jqXHR) {
jqXHR.setRequestHeader(KEY1, _key1);
jqXHR.setRequestHeader(KEY2, _key2);
},
url:SERVER_URL+"api/addNotes/",
data: {type: 'text',note_text: note_text, note_lat: note_lat , note_lng: note_lng},
success: function(data, textStatus, jqXHR) {
if (data.status == "ok"){
$.mobile.changePage("file:///android_asset/www/index.html?"+_key1+"|"+_key2+"|");
}
else{
alert("Something wrong");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error=" + errorThrown);
},
complete: function() {
$('#mylist').listview('refresh');
}
});
}
I read many reports and forums there said I have to call listview('refresh') in ajax's complete function. But in my code it doesn't work, could anyone tell me what is the problem here?
Refresh is for when you are adding elements to an existing, enhanced listview. If you are creating the entire listview dynamically you need to trigger a "create" on the parent div.
So if you had <div id="container><ul></ul></div>, you would need to call $("#container").trigger("create").
You probably want to see your data after adding some values. If you want to do this listview.refresh doesn't help you after adding some values you have to call you data again, i.e you have to call getNote() again.
I think it helps.
Try this for you complete function instead
complete: function() {
$('#mylist').listview();
}
As someone else mentions the refresh method is for when you are adding listitems to a listview that JQM has already created.
First of all , You must understand how does the refresh work, it will just refresh the listview's css when you add a new LI so that the new LI will have a right css,
function createItem(tx,results){
var len = results.rows.length;
console.log("lisitem len "+len);
for(var i = 0;i<len;i++){
var content = results.rows.item(i).content;
var id = results.rows.item(i).id;
var string = '<li>'+content+' ['+results.rows.item(i).date+']</li>';
$("#all_list").append(string);
};
freshList("all_list");
}
freshList("all_list"); it will refresh the listview ,if you don't do it, all of the LI will display like below.
<li> 测试成功 [2013-10-02]</li>
the LI doesn't have a css description
that's why your ajax operation doesn't work

Resources