Can anyone suggest why this isn't loading the autocomplete data? If i hardcode the URL in the ajax call, it works, but not with my code to alter the url source?
I'm unsure why it wouldn't work. If you want to look at the page as a whole, the hardcoded version is:here
var starterSearchData;
$(function() {
var destination;
elementVal = $("input[name=radio]"); //note returns array of radio button elements
if (elementVal[0].checked){
destination= "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php",
}
if (elementVal[0].checked){
destination= "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/italian.php",
}
//Starter Autocomplete (Spanish)
var starterSearchData;
$(function() {
$.ajax({
url: destination,
dataType: "jsonp",
async: false,
success: function(data) {
starterSearchData = $.map(data, function(item) {
if (item.course == "starter")
return item.name;
return item.price;
});
EnableAutoComplete();
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
function EnableAutoComplete() {
$("#starter").autocomplete({
source: starterSearchData,
minLength: 2,
delay: 010
});
}
});
Radio button:
<div id="radio">
<input type="radio" id="radio1" name="radio"><label for="radio1">Spanish</label>
<input type="radio" id="radio3" name="radio"><label for="radio3">Italian</label>
</div>
You have syntax errors at some places in your code. This will work:
var starterSearchData;
$(function() {
var destination,
elementVal = $("input[name=radio]");
if (elementVal[0].checked) {
destination = "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php";
}
if (elementVal[1].checked){
destination= "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/italian.php";
}
$.ajax({
url: destination,
dataType: "jsonp",
async: false,
success: function(data) {
starterSearchData = $.map(data, function(item) {
if (item.course == "starter")
return item.name;
return item.price;
});
EnableAutoComplete();
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
function EnableAutoComplete() {
$("#starter").autocomplete({
source: starterSearchData,
minLength: 2,
delay: 010
});
}
});
Related
I have a dropdown and when I select an option I run one ajax call, on pc is working as expected but on iPhone is not triggering the ajax, it goes to the function and I know this because I added alerts.
When i click 13,14,15 is not working. At 9,10,11,12 is working.
<div class="row" id="type">
Selected type: #Html.DropDownListFor(model => model.GymType, listItems, new { id = "GymType", onchange = "getBookTime();" })
</div>
<div id="timesList" style="display:none;margin:auto">
Selecte time: <select id="states_ddl" name="states_ddl" class="cs3 input-small" > </select>
</div>
function getBookTime(e) {
var selectedtype = $('#GymType').val();
alert(selectedtype);
var selectedDate = $('#date').text();
$.ajax({
type: "GET",
async: false, //This makes the JQuery below wait until $.ajax() call is finished
cache: false,
headers: { "cache-control": "no-cache" },
url: '/Home/GetBookTime/',
data: { date: selectedDate, type: selectedtype },
success: function (data) {
if (data.message != undefined) {
alert(data.message);
$('#error').show();
document.getElementById("errormsg").innerHTML = data.message;
}
else {
alert(data);
$('#error').hide();
$("#timesList").show();
var options = $("#states_ddl");
options.empty();
$.each(data, function (index, item) {
options.append($("<option />").val(item).text(item));
});
}
$("#submitbtn").show();
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
})
}
I am attempting to do an AJAX call with the Select2 jquery plugin. The query seems to be working, but the issue occurs when .results() is called on the options object:
Uncaught TypeError: options.results is not a function
Here is my HTML:
<input class="form-control" type="number" value="2125" name="topic_relation[source_topic_id]" id="topic_relation_source_topic_id" />
Here is my JS:
$(document).ready(function() {
$('#topic_relation_source_topic_id').select2({
minimumInputLength: 3,
ajax: {
url: "<%= grab_topics_path %>",
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
q: term, //search term
page_limit: 30, // page size
page: page, // page number
};
},
processResults: function (data, page) {
var more = (page * 30) < data.total;
return {results: data.topics, more: more};
}
},
formatResult: topicFormatResult,
formatSelection: formatRepoSelection,
escapeMarkup: function (m) { return m; }
});
function topicFormatResult(topic) {
return topic.name
}
function formatRepoSelection(topic) {
return '<option value="'+ topic.id +'">' + topic.name + '</option>'
}
});
Here is the returned JSON:
{"total":2, "topics":[{"id":305,"name":"Educational Assessment, Testing, And Measurement"},{"id":3080,"name":"Inspectors, Testers, Sorters, Samplers, And Weighers"}]}
Here is the code which is failing:
function ajax(options) {
var timeout, // current scheduled but not yet executed request
handler = null,
quietMillis = options.quietMillis || 100,
ajaxUrl = options.url,
self = this;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
var data = options.data, // ajax data function
url = ajaxUrl, // ajax url string or function
transport = options.transport || $.fn.select2.ajaxDefaults.transport,
// deprecated - to be removed in 4.0 - use params instead
deprecated = {
type: options.type || 'GET', // set type of request (GET or POST)
cache: options.cache || false,
jsonpCallback: options.jsonpCallback||undefined,
dataType: options.dataType||"json"
},
params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
data = data ? data.call(self, query.term, query.page, query.context) : null;
url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
if (handler && typeof handler.abort === "function") { handler.abort(); }
if (options.params) {
if ($.isFunction(options.params)) {
$.extend(params, options.params.call(self));
} else {
$.extend(params, options.params);
}
}
$.extend(params, {
url: url,
dataType: options.dataType,
data: data,
success: function (data) {
========> var results = options.results(data, query.page, query); <==========
query.callback(results);
},
error: function(jqXHR, textStatus, errorThrown){
var results = {
hasError: true,
jqXHR: jqXHR,
textStatus: textStatus,
errorThrown: errorThrown
};
query.callback(results);
}
});
handler = transport.call(self, params);
}, quietMillis);
};
}
Since the plugin calls results(), you should also declare results: function (data, page) instead of processResults: function (data, page).
I am running match() to loop through an array or stop ID's. For each stop ID I am calling a function which loops through another array of route ID's and through the response of the AJAX call to find a match.
If it finds a match between the routeID and the RouteID in the array then it adds the result to another array in each loop.
My problem is that I can't find a way to determine when the functions called by the match() loop are complete.
The reason I need to do this, is that I need to make sure that the jpFromStops array is complete and ready to be processed by another function.
What is the best way to do this?
function match() {
// Array length is 5
for(i=0; i < fromStopsAr.length; i++) {
getFromRoutesStopId(fromStopsAr[i]);
}
console.log("Match Array Output: " + jpFromStops.toString());
}
function getFromRoutesStopId(id) {
jpFromStops=[];
tempAr = [];
jQuery.ajax({
type: "GET",
url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
$.each( matchRoutes, function(index, value) {
$.each(data.response, function(key, data) {
if(data.route_short_name.toString() == value) {
jpFromStops[jpFromStops.length] = id + ":" + value;
}
});
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There is a problem");
}
});
}
Console log Output:
Match Array Output:
jp-main.js (line 177)
2
115
jp-main.js (line 199)
2
113
jp-main.js (line 199)
2
087
You can use a counter...sort of like:
var count = 0;
function getFromRoutesStopId(id) {
jpFromStops=[];
tempAr = [];
jQuery.ajax({
type: "GET",
url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
count++;
if(count == fromStopsAr.length){your code or function call}
$.each( matchRoutes, function(index, value) {
$.each(data.response, function(key, data) {
if(data.route_short_name.toString() == value) {
jpFromStops[jpFromStops.length] = id + ":" + value;
}
});
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
count++;
if(count == fromStopsAr.length){your code or function call}
alert("There is a problem");
}
});
}
You can return promise and use $.when
function match() {
var promises = [];
// Array length is 5
for(i=0; i < fromStopsAr.length; i++) {
promises.push(getFromRoutesStopId(fromStopsAr[i]));
}
$.when.apply($, promises).then(function() {
console.log("Match Array Output: " + jpFromStops.toString());
});
}
function getFromRoutesStopId(id) {
jpFromStops=[];
tempAr = [];
return jQuery.ajax({
type: "GET",
url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
$.each( matchRoutes, function(index, value) {
$.each(data.response, function(key, data) {
if(data.route_short_name.toString() == value) {
jpFromStops[jpFromStops.length] = id + ":" + value;
}
});
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There is a problem");
}
});
}
When dealing with ajax calls, you need wait until each of them has finished the execution.
Follow this pattern:
var jobs = [11, 12, 14, 15];
function doTheJob() {
if (jobs.length === 0) {
alert('All jobs are done now.');
complete();
return;
}
var job_Id = jobs.pop();
$.ajax({
url: "/DoTheJob",
complete: function () {
doTheJob();
}
});
};
I'm sorry similar post is already there in the community, But i'm finding it strange. Its working fine but it affected my other views and not allowing other view pages to populate any dialogue boxes..
I tried to fix it by wrapping it in function() like this
$('#_auto').autocomplete(function(){
But, with this i'm not getting jason values in the _auto textfield and getting unexpected token error with following line.
can anyone help me to solve this please.
source: function(request,response){
this is my code:
$(function () {
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
var sval = $('#_auto').val();
//alert(sval);
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': sval,
},
dataType: 'json',
success: function (data) {
console.log(data);
var dta = [];
orgdetails = [];
//response(data.d);
for (var i in data) {
dta.push(data[i].name);
orgdetails[data[i].name] = data[i].id;
}
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
});
Many Thanks
I think the for loop should be
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
Fiddle.
Another observation, You can get the current searched term using request.term rather than $('#_auto').val()
Complete code:
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': request.term,
},
dataType: 'json',
success: function (data) {
console.log(data);
orgdetails = {};
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
I want to create a function to simplify configuration of jQuery UI AutoComplete. Here is my function code:
(function($) {
$.fn.myAutocomplete = function() {
var cache = {};
var dataUrl = args.dataUrl;
var dataSend = args.dataItem;
$.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
$.ajax({
url: dataUrl,
dataType: "json",
type: "POST",
data: dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
}
}) (jQuery);
but when I'm using this function like:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
It's give me an error:
Uncaught ReferenceError: request is not defined
Perhaps the error is referring to request.term in
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
Sorry for the trouble, I'm not adept at using jquery. Here's the final working code.
(function($) {
$.fn.myAutocomplete = function(opt) {
var cache = {};
this.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
opt.dataSend.term = request.term;
$.ajax({
url: opt.dataUrl,
dataType: "json",
type: "POST",
data: opt.dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
return this;
}
}) (jQuery);
To use this function just write code like this:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { category: $("input#category").val() }
});
Thanks Jeffery To for sharing with me to solve this problem.. ^_^