Previously I used onchange event to call javascript method(in this method used AJAX call to pass selected option to server). But this leads to multiple AJAX call to server on multiple options selection. Is there a way to call javascript method after making multiple selection in select box so that I can prevent multiple AJAX calls to server.
here it will abort in process ajax request and will consider only last request..
$(document).ready(function(){
$("#searchInput").onchange(function(){
ajaxSelect( $("#searchInput").val() );
});
});
var request;
function ajaxSelect(selectedKey) {
/* if request is in-process, kill it */
if(request) {
request.abort();
};
request = $.ajax({
type: "get",
url: "http://example.com/ajaxRequestHandler/",
data: "action=selectmulti&selectedKey=" + selectedKey
}).done(function() {
/* process response */
/* response received, reset variable */
request = null;
});
}
one way could be to define following event clearly.
after making multiple selection in select box
You can think of using other events like onblur or onmouseout on select box to send ajax request if that suits your need.
Related
I have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
$(document).ajaxComplete(function(){
$('a.report_video').click(function() {
var idbutton = $(this).attr('id');
var idreport = idbutton.replace('report_video_', '');
//I'm still not using these variables, can they be used to pass the input data to ajax?
var videourl = $("#video_url_" + idreport).val();
var videoid = $("#video_id_" + idreport).val();
var videoserver = $("#server").val();
///////////
$.ajax({
type : 'POST',
url : 'https://example.com/script/script.php',
data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
//For example, data: $("#server").serialize()
//Work fine, this input is stored locally.
beforeSend: function(){
$('#video_report_' + idreport).html('<img src="'+pluginUrl+'./assets/img/loading.svg" />');
}
}).done(function(data) {
$('#video_report_' + idreport).html(data);
});
return false;
});
});
Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),
I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
$.ajax({
type: "POST",
url: 'someURL',
data: someData
}).done(function(firstCallData) {
// This OPTIONAL method fires when the AJAC call succeeded
// You can also put another AJAX call in here with the data returned from the first call
$.ajax({
type: "POST",
url: 'someURL',
data: firstCallData
}).done(function(data) {
// Do something with second AJAX call with data
}).fail(function(data) {
// Second AJAX call failed, handle error
});
}).fail(function(data) {
// This OPTIONAL method fires when the first response failed
}).always(function(data) {
// This OPTIONAL method fires regardless if the first call succeeded or failed.
});
});
I am using jQuery.post a lot in my project and every time the browser sends a post request, I want to show a preloader while the request is in process and then stop the preloader when i get the reply form the server:
var params = {'action':'get_customer_info', 'customerID':4};
preloader.start();
$.post('ajax/url', params, function(response){
preloader.stop();
responseHandler(response);
});
Instead of adding the preloader.start() and preloader.stop() lines every time I call jQuery's post, I'd like to bind/trigger events on before the jQuery.post as well on the success/fail handlers.
I know how to bind and trigger events in general, but I'm not sure how I would do this with the $.post and handlers.
How do I do this?
You could set up the global ajax events, that way the preloader shows on every ajax request
$(document).ajaxSend(function() {
preloader.start();
}).ajaxComplete(function() {
preloader.stop();
});
Or you could create your own post function
function post(url, params) {
preloader.start();
return $.post('ajax/url', params, function(response){
preloader.stop();
});
}
To be used like
post('ajax/url', params).done(function(response) {
responseHandler(response);
});
I have an onclick event for a radio button that calls a function which launches period AJAX calls to some url
Example in MVC cshtml view
<script>
function onClick(selectedRowId) {
GetData("/home/GetData/" + selectedRowId);
};
</script>
Ajax call
function GetData(url) {
$.ajax({
url: url,
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
success: onSuccess,
error: onError,
complete: function (xhr, status) {
setTimeout(function () {
GetData(url);
}, 10000);
}
});
}
When a different radio button is selected I need to call the onClick method with the selected radio button id and this again initiates a call to the url with the different id.
However, I would like the previous AJAX function call to terminate since the AJAX onSuccess method updates an html element with the data retrieved for that specific selected Id.
Any way to signal the previous call to terminate before launching new one ?
One way to solve this could be
a) Not make id as a paramter to the url call then
b) in the onClick method send a call to Server to set the Id variable (this makes the server aware that all data must be returned for that Id)
c) Then ensure that ajax function is called only once and server will change data returned based on Id information conveyed to it in (a)
Not sure if the server round trip is worth it here for every button click.
The best I can think is each time onClick fired, it needs to cache the selectedRowIndex which you are only interested in the latest selected one. As you mention, the server need to return that ID back. That way on your onSuccess function, you only need to process returns that matched ID and ignore any other.
I don't think you can literally stops previous ajax. You don't have access to the previous ajax object any more. Just ignore previous responses.
I have the below JavaScript code that iterates through a list of textfields on a page. It takes the text in the textfield as a price, sends it to the server via an AJAX GET, and gets the parsed double back from the server. If any of the returned prices are less than an existing price, the form shouldn't submit.
The problem is that the form is submitting before all the AJAX requests are finished because of the non-blocking immediate response nature of the Ajax calls. I need to set up a wait() function (or a callback when all the Ajax methods are complete) but don't know how to do that with jQuery.
Any suggestions?
// .submitForm is a simple button type="button", not type="submit"
$(".submitForm").click(function(e){
var submittable = validatePrices();
if (submittable) {
$("#myForm").submit();
}
});
function validatePrices() {
var submittable = true;
$(".productPrice").each(function(){
var $el = $(this);
$.ajax({
type: "POST",
url: "/get_price.jsp",
async: false,
dataType: "html",
data: "price=" + $el.val(),
success: function(data)
{
var price = new Number(data.split("|")[1]);
var minPrice = new Number($el.data("min-price"));
if (price < minPrice)
{
$el.addClass("error");
$(".dynamicMessage").show().addClass("error").append("<p>ERROR</p>");
submittable = false;
}
}
});
return submittable;
});
}
You're already using synchronous AJAX (a really bad idea for your user experience), so that's not the problem. The problem is that you need to cancel the default action in the "submit" handler:
$(".submitForm").click(function(e){
var submittable = validatePrices();
e.preventDefault(); // this line
if (submittable) {
$("#myForm").submit();
}
});
Using a synchronous HTTP request back to your server for each separate field is going to make your site terribly slow. You're going to have to check the parameters at the server again when you submit the form anyway, so it'd be much better to just check then and return an error.
edit — now that the situation is clearer, I think that the way to proceed is to stop doing the AJAX validation checks completely. Why? Well, even if you perform those tests, you still need to make essentially the same validity tests when the form is actually submitted. You can't rely on the JavaScript validation code actually running, as in any other form validation scenario. If you're doing the validation at form submission time anyway, it'll save on a bunch of HTTP requests to just do it all at the same time.
You're not canceling the form submission. You have to work strictly with the ajax callbacks (if you would like to use them asynchronously, which would be nice).
$(".submitForm").click(function(e){
e.preventDefault();
validatePrices().done(function () { /* ajax success function here */
if (submittable) {
$("#myform").trigger('submit');
}
}
});
function validatePrices() {
var checks = [];
$(".productPrice").each(function(){
var $el = $(this);
checks.push($.ajax({
/* snip */
});
return $.when.apply(null, checks);
}
Often times I find myself designing apps that make AJAX calls to the server, outside APIs, HTTP requests, etc. The problem is, while this async calls are happening, the user still has the ability to click on items that make the same AJAX call or interrupt the flow of the app, etc. I've experimented with various hacks to prevent this, but I'm wondering what the most accepted way of doing this is?
To make this more concrete, let's say I have a button element that makes an AJAX call and a form element that alters some of the data my app uses for the AJAX call. What is the best way to design the button and form functions so that they do not work while button's AJAX call is in process?
The best way to accomplish what you want is to lead the AJAX calls trough a function so you can check within that function if a request is active. Here's an example assuming you're using JQuery:
active_ajax_call = false;
function get_ajax(url, senddata) {
if(active_ajax_call == false) {
active_ajax_call = true;
$.ajax({
type: "POST",
url: url,
data: senddata
}).done(function (data) {
active_ajax_call = false;
console.log(data);
});
}
}
get_ajax("some_url", {name: "John", location: "Amsterdam"});
And ofcourse present the website user a nice ajax loader or something so they know data is being pulled.
In the handler for the button, disable the button (visually and functionally), then do the AJAX call. Returning from the AJAX call, reenable the button.
This is, how the major sites do it (e.g. PayPal).