I have input which on change should send it is value to ajax and get response back. Ajax is working correct and enters to success,but does not working click function inside it if i do not do changes or click. If i click immediately after response it works, but if i do not do changes in 4-5 seconds it something like close the session. How can i avoid this timing?
here is my example of ajax
$('#unvan_search').on('keyup change', function() {
var unvan = $(this).val();
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
},
error: function(x, t, m) {
alert("error");
}
});
});
This binding here:
$("#unvan_select_div ul").on("click", '.get_street', function() { ... }
There’s no need to declare it in the success callback. This kind of delegate bindings is there for that purpose: being able to handle events on elements created at a later stage
It may work if you structure it like this.
var ret = false;
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
ret = true;
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
return;
},
error: function(x, t, m) {
alert("error");
}
});
});
if(ret) {
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
}
Related
Error in devtools:
[Violation] Added synchronous DOM mutation listener to a 'DOMNodeInserted' event. Consider using MutationObserver to make the page more responsive
What's the matter?
$(document).ready(function() {
$('#ajax-service').keyup(function() {
$.ajax({
data: $(this).serialize(),
url: "{% url 'ajax_request' %}",
success: function(response) {
console.log(response);
if (response.is_exist) {
console.log("TYT");
let list = ''
for (var i in response.is_taken) {
list = list + '<span name="' + (response.is_taken[i]) + '" id="' + (i) + '">' + (response.is_taken[i]) + '</span> '
}
//console.log("i: "+i);
//let elem_input = document.querySelector("ajax-service")
//let elem = document.querySelector("#service"+i);
//console.log("response: "+response.is_taken[i]);
//console.log("elem: "+elem);
$('#ajax-service-list').remove();
$('#ajax-service').after('<div id="ajax-service-list" name="ajax-service-list">' + (list) + '</div>')
} else {
$('#ajax-service-list').remove();
$('#ajax-service').after('<div id="ajax-service-list" name="ajax-service-list"><span class="badge rounded-pill bg-warning text-dark" id="ajax-service-list">Нет совпадений</span></div>')
}
},
error: function(response) {
console.log(response.responseJSON.errors)
}
});
return false;
});
})
upd:
how can I do for this function below to generate an incremental index in the table? Names are being generated right.
I thought of an incremental variable (a), something like that.
function sortear()
{
var a = 1;
$.ajax({
url: 'prize',
type: 'POST',
dataType: 'json',
data: 'employees=' + $('#employees').val() + "&sorted=" + sorteados,
beforeSend: function() {
$('#loading').modal();
},
success: function(data) {
$('#loading').modal('hide');
if (data == null) {
window.alert('Todos os nomes foram sorteados');
$('#button').attr('disabled', 'disabled');
return;
}
$('#employee').html(data.name);
$('#myModal').modal();
$('#sorted tbody').append('<tr><td>' + a + '</td><td>' + data.name + '</td></tr>');
sorteados.push(data.name);
a++;
},
error: function() {
}
});
}
You can get the length of <tr> and sum 1:
/*...*/
// store the element in a variable to reuse it
const $sortedTbody = $('#sorted tbody');
// in the first iteration lenght will be 0, so it will print 1, then 2, etc
$sortedTbody.append('<tr><td>' + ($sortedTbody.children().length + 1) + '</td><td>' + data.name + '</td></tr>');
/*...*/
I would like once the user selects a different item in the drop box list which was taken from a mysql database, that specific data to that field be displayed.
Currently, I am able to get the value of the item in the drop down box but I am unable to use it.
<h3>Drop down Menu</h3>
<select id="dmenu">
<option selected="selected" id="opt">Choose your station</option>
</select>
<div id="optionT"></div>
$(document).ready(() => {
window.onload = ajaxCallback;
function ajaxCallback(data) {
var data;
var myOptions;
var output;
$.ajax({
url: 'http://localhost:5000/alldata',
type: 'GET',
datatype: 'json',
success: (data) => {
//$.each(data, function (index, value) {
var output = [];
$.each(data, function(key, value) {
output.push('<option value="' + key + '">' + value.Station +
'</option>');
});
$('#dmenu').html(output.join(''));
}
})
}
});
$('#dmenu').on('change', function() {
//alert( this.value );
//alert($(this).find(":selected").value());
function stationData(data) {
var stationName = $(this);
alert(stationName.val());
//var stationName = $(this).value();
//var stationName = $(this).find(":selected").value()
$.ajax({
url: 'http://localhost:5000/alldata',
method: 'POST',
data: {
station: stationName
},
success: (data) => {
$.each(data, function(i) {
data[i]
//console.log(i);
var station_loopOp = '';
//console.log(JSON.stringify(data[i].Station));
station_loopOp += '<li>ID: ' + JSON.stringify(data[i].ID) +
'</li>' +
'<li>Station: ' + JSON.stringify(data[i].Station) +
'</li>' + '<li>Address:
'+JSON.stringify(data[i].Address) +
'</li>' + '<li>' +
Sales: JSON.stringify(data[i].Monthly_CStore_Sales) +
'</li>' + '<li>Operator: ' +
JSON.stringify(data[i].Operator) + '</li>' +
'<li>Top SKU: ' + JSON.stringify(data[i].Top_SKU) +
'</li>' +
'</<li>' + '<br/>');
$('#optionT').html(station_loopOp);
}
});
}
});
You are just defining the function stationData(data){....} inside the callback function but not calling it anywhere inside of it .
Add this line into your function : stationData(<your-data>);
I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.
In my MVC project, I have passed a list of users to my view, and inside this view I iterate through the list and create an anchor tag for each user. Would it be possible to add a delay after each anchor tag is created? Here is my jquery:
DeskFunction.prototype.init = function() {
var self = this;
var element;
this.allData = #Html.Raw(#JsonConvert.SerializeObject(Model.AllDeskData));
for (var i = 0; i < this.allData.length; i++) {
element = $("<a href='#' class='deskBtn tooltip fancybox' title='" + this.allData[i].Name + "' data-name='" + this.allData[i].UserName + "' data-department='" + this.allData[i].DepartmentName + "'></a>");
$(element).css({
"top": this.allData[i].DeskYCoord,
"left": this.allData[i].DeskXCoord
}).appendTo(".map").show('normal').delay(3000);
$(element).on('click', function() {
var user = $(this).attr("data-name");
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: { user: user },
success: function(data) {
$(".user-data .name").text(data.displayName);
}
});
});
}
$('.tooltip').tooltipster();
$('.search-user').keyup(function() {
self.search();
});
};
I would like the first tag to be created and added to the map, then a delay of a second, after that the next anchor tag would be added, is this possible? Any help would be appreciated
you can try below code. inside setTimeout write all code that you want to do under the loop. It will get called after 1 sec
for (var i = 0; i < this.allData.length; i++) {
(function(i, self ){
setTimeout(function(){
// ALL LOOP CODE HERE
// use self.allData
}, 1000);
}(i, self ));
}
You could place your code in a setTimeout.
DeskFunction.prototype.init = function() {
var self = this;
var element;
this.allData = #Html.Raw(#JsonConvert.SerializeObject(Model.AllDeskData));
for (var i = 0; i < this.allData.length; i++) {
element = $("<a href='#' class='deskBtn tooltip fancybox' title='" + this.allData[i].Name + "' data-name='" + this.allData[i].UserName + "' data-department='" + this.allData[i].DepartmentName + "'></a>");
$(element).css({
"top": this.allData[i].DeskYCoord,
"left": this.allData[i].DeskXCoord
}).appendTo(".map").show('normal');
setTimeout(function(){
$(element).on('click', function() {
var user = $(self).attr("data-name");
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: { user: user },
success: function(data) {
$(".user-data .name").text(data.displayName);
}
});
});
}, 3000);
}
$('.tooltip').tooltipster();
$('.search-user').keyup(function() {
self.search();
});
};
With timeouts incrementing and passing all data through a function call to a local scope the following could should do:
for(var i in this.allData) {
// create local function scope saving i and data from being altered by next iterations
(function(i, data) {
setTimeout(function() {
// place your code here, using data (and i)
}, i*1000);
})(i, this.allData[i]);
}
For each element of this.allData this.allData[i] is passed to the local function as data, along with each i. These are used in the inner scope for setting timeouts in intervalls of 1 sec and creating the anchor links.
You actually want an asynchronous loop:
DeskFunction.prototype.init = function() {
this.allData = #Html.Raw(#JsonConvert.SerializeObject(Model.AllDeskData));
var self = this,
allData = this.allData,
delay = 1000;
var appendDeleteLink = function appendDeleteLink(i) {
if (i >= allData.length) {
return;
}
var element = $("<a href='#' class='deskBtn tooltip fancybox' title='" + allData[i].Name + "' data-name='" + allData[i].UserName + "' data-department='" + allData[i].DepartmentName + "'></a>");
$(element).css({
"top": allData[i].DeskYCoord,
"left": allData[i].DeskXCoord
}).appendTo(".map").show('normal').delay(3000);
$(element).on('click', function() {
var user = $(this).attr("data-name");
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: { user: user },
success: function(data) {
$(".user-data .name").text(data.displayName);
}
});
});
(function(a) {
setTimeout(function() {
appendDeleteLink(a);
}, delay);
})(++i);
};
appendDeleteLink(0);
$('.tooltip').tooltipster();
$('.search-user').keyup(function() {
self.search();
});
};