Loading using ajax request - onEachFeature leaflet - multiple requests - leaflet

Hi I am trying to find out how to add a loading in a ajax call, but there is one issue, in the example below the loader hide on the first request, but I need to hide it only when the last request is made.
onEachFeature/geoJson runs multiple markers on my map, each marker has a unique data, so ajax runs one time for each marker.
function onEachFeature(feature, layer) {
if (feature.properties && feature.properties.name) {
function getImage(value) {
function applyImage(result, resultB) {
//do something...
}
$.ajax({
url: "libs/php/getImage.php",
type: 'POST',
dataType: 'json',
data: {
id: value,
},
success: function (result) {
$("#iframeloading").show();
let valueA = result.A;
let valueB = result.B
applyImage(valueA, valueB)
},
error: function () {
console.log('error');
},
complete: function() {
hide goes here but there's no effect...
}
})
};
getImage(feature.properties.wikidata)

It works in my code, just put it before ajax calls, it will apply to every ajax call:
$(document).ajaxStart(function(){
$("#iframeloading").show();
});
$(document).ajaxStop(function(){
$("#iframeloading").hide();
});

Related

Store the user searchword in mysql

I working on a little snippet, a live search with MySQL.
Now i think it could be nice to store/save which searchword the user, did the search on.
Example:
User search on
My new book
Then i want to store that to my databse.
The problem is with my script right now, where i trig the ajax on keyup. Then it will store.
M My My N My Ne My New .... and so on..
and so on, how can i come around this and only store the hole line ..?
$(function() {
$("#searchword").keyup(function(){
var text = $(this).val();
if (text != ' ') {
$('#result').html(" ");
$.ajax({
type: 'post',
url: 'livesearch.php',
data: { 'search': text },
success: function(dataReturn) {
$('#result').html(dataReturn);
}
});
}
});
});
I've created a storeText(txt,time) function that will take your text as first param and time to wait before sending ajax as second param. You can change the second parameter as per your need. Add your ajax call in the function below my comment and you're good to go.
$(function() {
$("#searchword").keyup(function(){
var text = $(this).val();
if (text != ' ') {
//THIS IS WHERE YOU CAN MODIFY THE TIME
storeText(text,1000);
$('#result').html(" ");
$.ajax({
type: 'post',
url: 'livesearch.php',
data: { 'search': text },
success: function(dataReturn) {
$('#result').html(dataReturn);
}
});
}
});
});
var timer;
function storeText(txt,time){
clearTimeout(timer);
timer = setTimeout(function(){
//ADD YOUR SAVE QUERY AJAX HERE
},time);
}
Here's a JSFiddle to see it in action: https://jsfiddle.net/3n2L2v6g/
Try typing anything in the text box, it waits 1000ms before executing the code where your ajax would be.

Delete form data for subsequent ajax calls

I have a link that opens a dialog modal asking for a date. When they click submit, javascript takes the form data, generates an ajax call, and returns the response. This works no problem. However if I immediately click the same link again and submit a new date in the form, I get the results from my first ajax POST.
Essentially, subsequent ajax calls are using the original POST data and nothing new. Code has alerts for troubleshooting. Im assuming im setting some var thats not getting reset, but thought this event handler was canceled with the "off", then re-added immediately after and the vars would be in scope to that function alone.
<script>
//Modal submit
$(document).off('click', '#SubmitAllChecks');
$(document).on('click', '#SubmitAllChecks', function(e) {
e.preventDefault();
var form = $('#AllChecks');
var url = form.attr('action');
var method = form.attr('method');
var data = form.serializeArray();
$.each(data, function(k,v) {
alert(v.name + ' : ' + v.value);
});
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
beforeSend: function() {
//add load indicator
window.erpui.startload();
},
success: function(data) {
alert('xhr complete');
$.each(data, function() {
alert(this.value + ' data');
if (this.value == 'error' && this.msg != '') {
window.erpui.endload();
window.erpui.notify.error(this.msg);
window.erpui.notify.commit();
}
else if (this.value == 'success') {
window.erpui.endload();
window.erpui.notify.success(this.msg);
window.erpui.notify.commit();
$('.ui-dialog').remove();
//window.location.href="{% url all_checks %}";
//window.location.reload();
}
});
},
error: function() {
alert('error');
//remove load indicator
window.erpui.endload();
}
});
});
</script>

Select2 with AJAX and Initial Local Data

So I'm trying to get the select2 plugin to work with a Backbone.js / CakePHP app. The idea is that this select2 holds email addresses for contacting people as tasks become completed, but the form is editable. What I want to do is (1) load / display all the already saved email addresses for the task being edited, and (2) I want to still have the select2 perform AJAX searches to list recognized emails.
I keep having this issue where I can either show initial data, OR have the AJAX search feature.
My current code for my select2 box is a Backbone.View, and it looks like:
define([
'backbone',
'jquery',
'jquery.select2'
],
function(Backbone, $, select2) {
var notificationSelector = Backbone.View.extend({
notifications: undefined,
events: {
'change' : 'select2ContactsChanged'
},
initialize: function(attrs) {
this.collection.on('add remove reset', this.render(), this);
this.select2ContactsChanged();
},
render: function() {
var contacts = ["abc#def.com", "joe#banana.com"];
$('.notification-selector').attr('value', contacts);
if(this.select2Control == undefined)
{
// Do Search() + query here
this.select2Control = this.$el.select2({
width: '200px',
placeholder: '#email',
tags: [],
minimumInputLength: 3,
// initSelection: function(element, callback) {
// return $.ajax({
// type: "GET",
// url: "/notifications/fetch/",
// dataType: 'json',
// data: { id: (element.val()) },
// success: function(data) {
// }
// }).done(function(data) {
// console.log(data);
// });
// },
});
}
else
{
// Do Search() + query here
this.select2Control = this.$el.select2({
width: '200px',
placeholder: '#email',
tags: [],
minimumInputLength: 3,
ajax: {
url: '/notifications/search/',
dataType: 'json',
data: function(term, page) {
return {
SearchTerm: term
};
},
results: function(data, page) {
return {
results: data
};
}
}
});
}
},
select2ContactsChanged: function() {
var contacts = this.select2Control.val().split(',');
this.collection.reset(contacts);
}
});
return notificationSelector;
});
I read a response by the creator of Select2 to someone else (https://github.com/ivaynberg/select2/issues/392) in which he says to use a 'custom query' to achieve what seems to be what I want. I'm having trouble finding relevant examples or making enough sense of the docs to figure out what he means.
Can anyone spot what I'm doing wrong / missing?
Thanks for your time!
EDIT
I forgot to mention -- the DOM element this is attached to is <input type="hidden" multiple="true" class="notification-selector select2-result-selectable"></input>
Ok, I finally figured out the solution.
I was misunderstanding $.ajax() -- I did not really think about it actually being an asynchronous call. My code to check for the data being returned from the call was running before the AJAX actually finished, so I was always getting undefined.
I assigned a variable to the AJAX call, and set "async: false", and it worked perfectly.
fetchSetNotifications: function() {
var addresses = $.ajax({
method: 'GET',
dataType: 'json',
context: $('#notifications'),
url: '/Notifications/fetch/',
async: false,
alert(addresses);
}
The jqXHR object I get in 'addresses' then contains the response data I want in the "responseText" attribute.

Calling an ashx handler with jquery causes form action to post back to it

I'm calling an ashx handler with jquery ajax:
$.ajax({ type: "GET",
url: "handlers/getpage.ashx?page=" + pageName,
dataType: "html",
success: function (response) {
$('.hidden-slide-panel').append(response);
});
However when this hidden-slide-panel div gets populated, when I click on anything inside it, the form action value has been set now to getpage.ashx, rather than the calling pages form action. Is there a way to force it to use the calling pages action?
Use the "data" property for ajax():
http://api.jquery.com/jQuery.ajax/
Example:
$.ajax({ type: "GET",
url: "whatever.ashx",
data: { page: pageName },
success: function(data) { alert(data); }
});
Sounds like you just need to set the form back to its original value if it's changing:
document.forms[0].action = 'whatever';
// or
document.YourFormNameHere.action = 'whatever';

Maintaing page number of MVC 2 pagination on refresh

I'm using MVC 2 Pagination (not the jquery one) and my partial page gets refreshed in every 5 second.
I want to maintain my page number on refresh. Can you please suggest me how that can be done.
Here is the code for the page refresh in every 5 sec
setInterval(function () {
$.ajax(
{
type: "GET",
url: '<%=Url.Action("divtobeupdated", "DefaultController") %>',
data: {},
dataType: "text",
success: function (result) { $("#FileListContainer").html(result); }
}
)
}, 5000);
you can try 2 solution:
1) you pass the number of the page to the server and you pass it back to the view(no so good because you hace to change many code)
2) set a javascript global variable and you set it in the setInterval, like this:
var numOfPage;
setInterval(function () {
numOfPage = getNumofPage();
$.ajax(
{
type: "GET",
url: '<%=Url.Action("divtobeupdated", "DefaultController") %>',
data: {},
dataType: "text",
success: function (result) {
//heare you can use numOfPage
$("#FileListContainer").html(result);
}
}
)
}, 5000);
I hope understund good your question.
Marco