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);
}
})
}
Related
I'm using AJAX calls to get my carousal items whenever a search form is submitted by pressing Enter. I want to remove previous items and add new items to carousal when Enter is pressed.
It works well all the time except when Enter is pressed repeatedly, it doesn't remove old items just keep adding new items.
Removing items
function removeResult() {
var i = 0;
$("#result_section").slideUp(750, function () {
$('.result_item').each(function(){
$(".prof-carousel").trigger('remove.owl.carousel', [i++])
.trigger('refresh.owl.carousel');
});
});
}
Adding items
$("#index_search_btn").click(function (e) {
e.preventDefault();
removeResult();
var formData = new FormData();
formData.append('type', search_type);
formData.append('q', search_q);
$.ajax({
type: "POST",
contentType: false,
processData: false,
url: "/search",
data: formData,
success: function (response) {
$("#result_section").slideDown(750, function () {
$.each(response, function (index, prof) {
var item = '';
item += '<div class="item carousel_ostad_item result_item">'+ 'whatever...'+'</div>';
$('.my-carousel').owlCarousel().trigger('add.owl.carousel',[jQuery(item)]).trigger('refresh.owl.carousel');
});
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
}
});
});
Probably because the Ajax is async and more slow and happen something similar to:
Enter -> Remove (old el) -> Ajax call 1 -> Enter -> Remove (nothing) -> Ajax call 2 -> Ajax callback 1 ADD -> Ajax callback 2 ADD
I hope it's clear, I don't know how to rappresent this.
What you can do is remove old elements in success Ajax callback.
$("#index_search_btn").click(function (e) {
e.preventDefault();
// #### Remove this...
//removeResult();
var formData = new FormData();
formData.append('type', search_type);
formData.append('q', search_q);
$.ajax({
type: "POST",
contentType: false,
processData: false,
url: "/search",
data: formData,
success: function (response) {
// ... and move here. ####
removeResult();
$("#result_section").slideDown(750, function () {
$.each(response, function (index, prof) {
var item = '';
item += '<div class="item carousel_ostad_item result_item">'+ 'whatever...'+'</div>';
$('.my-carousel').owlCarousel().trigger('add.owl.carousel',[jQuery(item)]).trigger('refresh.owl.carousel');
});
});
}, error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
}
});
});
I did come up with a simple solution.
I disabled search button when it is pressed (so the form can't be submitted repeatedly) and enable it again after adding carousal items in success Ajax callback.
$("#index_search_btn").click(function (e) {
e.preventDefault();
///// disable search button /////
$("#index_search_btn").attr("disabled", true);
removeResult();
var formData = new FormData();
formData.append('type', search_type);
formData.append('q', search_q);
$.ajax({
type: "POST",
contentType: false,
processData: false,
url: "/search",
data: formData,
success: function (response) {
$("#result_section").slideDown(750, function () {
$.each(response, function (index, prof) {
var item = '';
item += '<div class="item carousel_ostad_item result_item">'+ 'whatever...'+'</div>';
$('.my-carousel').owlCarousel().trigger('add.owl.carousel',[jQuery(item)]).trigger('refresh.owl.carousel');
///// enable search button /////
$("#index_search_btn").removeAttr("disabled");
});
});
}, error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
}
});
});
Im getting the following error on my Ajax post back {"readyState":0,"status":0,"statusText":"error"}
on my first ajax call but the second one returns data I want.
My C# method (UserSelect) JsonResults shows the data when I put break point
My C# code :
public IActionResult OnPostAreaSelect(string Id)
{
//Generating list for Areas
Guid ModelId = new Guid(Id);
List<ModelArea> modelAreas = _context.ModelArea.Distinct()
.Where(w => w.ModelId == ModelId).OrderBy(o => o.AreaColumn.Name).Include(i => i.AreaColumn).ToList();
return new JsonResult(modelAreas);
}
public IActionResult OnPostUserSelect(string Id)
{
//Generating list for Users
Guid ModelId = new Guid(Id);
List<UserModel> userModels = _context.UserModel
.Where(w => w.ModelId == ModelId).OrderBy(o => o.User.FullName)
.Include(i => i.User)
.ToList();
return new JsonResult(userModels);
}
My JavaScript :
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
async: true,
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
crossDomain: true,
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
$.ajax({
type: "POST",
url: "./Create?handler=AreaSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
}
})
})
The second ajax call on my script works fine only the first one returns the error
How can I solve the error
When you work with EntityFramework (or other ORM) there may be problems with serialization because an entity could have some circular references. To avoid this problem a solution is to set serialization settings:
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
or:
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
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
});
}
});
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).
Load dropdown list based on another dropdown selected item
Here my js :
$("#Ownerstate").change(function () {
var procemessage = "<option value=`0`> Please wait...</option>";
$("#OwnerAgency").html(procemessage).show();
var url = "/Index/GetAgencyState/";
// Get state code
var Ownerstate = $("#Ownerstate :selected").val();
$.ajax({
url: url,
data: { statecode: Ownerstate },
cache: false,
type: "POST",
success: function (carData) {
if (carData.length > 1) {
$("#OwnerAgency").prop("disabled", false);
}
var select = $("#OwnerAgency");
select.html('');
$.each(carData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
Not getting load dropdownlist