I'm attempting to utilize a loading gif for an ajax call on a page of mine. I'm using jQuery's ajax method. My method looks like this:
$.ajax({
type:'POST',
data:{action:'yadayada',data:stuffToSend},
cache: true,
dataType: 'json',
async:false,
beforeSend:function(){
var options={
height:'100px',
duration:1,
width:'100px',
}
new ajaxLoader($("#search-right"), options);
},
url: "/wp-admin/admin-ajax.php",
success: function(value) {
//do stuff
}
}
The image shows, but not until AFTER the ajax success function is finished.
The ajaxLoader function is not the guilty party, as I have tried multiple methods of loading images; all exhibit the same behavior.
I've tried loading the images on the click handler that calls the ajax function, before calling the ajax function. Same results (so it's not the beforeSend function). My question is this: why is the loading image not 'loading' until after the ajax success?
Doh! The async:false was the guilty party! Changing to async:true solved it.
Related
I need to load HTML in a div.
$("#content").load("content.html");
$("#myText").html("Prasath");
After that I need to update some text in a div(id='myText') which is available in "content.html". "content.html" contains huge data, so it takes some time to load. Before that this line is executed:
$("#myText").html("Prasath");
How to load HTML content synchronously from JavaScript/jQuery ?
I don't want to do this from call back option in load.
You can't load it synchronously but you can quite easily do the next task in the load() callback. For example:
$("#content").load("content.html", function() {
$("#myText").html("Prasath");
});
$("#content").load("content.html", function(data){
// this will execute after load is fired.
});
Use a callback.
EDIT: If you really want to make synchronous request, you can use the following code. However, you'll get a warning in console as I mentioned in the comment earlier:
var data = $.ajax({
type: "GET",
url: "content.html",
async: false
}).responseText;
// this code waits for the above ajax request.
Please have a look on the JQuery documentation about load().
You can pass callback function to load()
For example:
$("#content").load("content.html", function(){
$("#myText").html("Prasath");
});
EDIT: There is no way to make load() to load content synchronously. A workaround solution is that you can define a Jquery function that use ajax() to send synchronous request to target url and then set the response content to destinate div.
$(function(){
$.fn.extend({
syncLoad: function (url) {
var result = $.ajax({
url: url,
async: false,
type: "GET"
}).responseText;
$(this).html(result);
}
});
$("#content").syncLoad("/echo/js/?js=hello%20world!");
});
JS Fiddle: https://jsfiddle.net/1v8fmb8b/
I've got 3-4 ajax calls that will be made at some point.
For one of those calls I'd like to trigger a function on the ajaxSend event which is global. This specific ajax call is not necesserily the first or last one in the sequence. It seems that if I attach the ajaxSend event to the $(document), my function will fire every other time that an ajaxSend event occurs. Here's what my code looks like:
//ajax call one
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
//ajax call two <- let's say I'd like to fire ajaxSpecificFunc() here
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
//ajax call three
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
function ajaxSpecificFunc(){
$(document).on("ajaxSend", function() {
//Some code that should only happen on ajaxSend but for only one ajax call
});
}
EDIT: I am aware of global:false property for ajax, but do not wish to use it, as this would mean I would have to modify every new ajax call in the future to have ajaxSpecificFunc() continue to fire for the one specific ajax call
You can add beforeSend in jQuery.ajax():
$.ajax({
type: "POST",
url: myUrl,
data: myData,
beforeSend: ajaxSpecificFunc
});
As noted by A.Wolff, this way if we call this function it will bind the ajaxsend for each call. Instead you can remove it and just do the specific ones like:
function ajaxSpecificFunc(jqXHR, settings){
// you can work with the jqXhr and settings
}
If you can't bind the handler directly to the ajax call, and want to use the global handlers only then you can check the setting object to see whether the ajax call is your targeted on and if so then call your stuff
$(document).ajaxSend(function(event, jqXHR, settings) {
console.log('send', settings);
if (settings.url == 'myurl') {
//then do your stuff
}
})
Note: But this might become an overkill, and you should try to do it specific to your ajax call
i am using ajax request to get the data, and also i use loading to start and stop ajax. if the data is not empty the loading work perfeclty, but if the data is empty, the ajax cannot stop the loading. i use ajaxStart and ajaxStop to do it.
this is my js code:
<script>
$(function() {
$("#searchgrowh").click(function() {
$('#result').html("");
$('.loading').ajaxStart(function(){$(this).show();});//this method for ajax start
$('.loading').ajaxStop(function(){$(this).hide();});//this method for ajax stop
$('.loading').ajaxError(function(){$(this).hide();});
$.ajax({
type: "POST",
url: "<?php echo base_url();?>internal/trending/ajaxsubmit/",
data: $('#form').serialize(),
success: function(html){
$("#result").prepend(html);
},
});
return false;
});
});
</script>
please see
.ajaxStart and .ajaxStop not firing
also i've had luck with
ajaxSuccess
and
ajaxComplete
Here's a question which has proved very difficult to find an answer online for.
Let's say a user runs an ajax function onclick to fill the contents of a div.
But, what if the ajax output is php, and for that onclick, i want other divs on the page to change in a manner that is dependent on the contents of div1?
This means I need to wait for div1 to actually change so i can use the ajax output of the php calculations to adjust div2 accordingly.
After some testing i've found out that i cant add a call to a second ajax function at the end of the first because it seems to run before the div content from the first ajax call actually changes.
So how can i trigger an ajax call onchange of the contents of a div?
All ajax calls take a callback to run when the call completes, put your logic in there.
You could use Jquery
$('#div1').change(function(){
doAjax( $(this).html() );
});
Or in the callback of the ajax
$.ajax({
url: 'http://yoururl.com',
type: 'post',
data: { key: value },
success: function( data ){
doAjax( data );
}
});
If you are aware of jquery, this is what you should try:
$.ajax({
traditional: true,
type: "post",
url: '<your_url>',
beforeSend: function () {
//your logic to perform operation before ajax request
},
data: {
//data to send
},
success: function(response) {
//your logic to perform operation after ajax request
//here make another ajax request
}
});
I have a little question. say i have a js function
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
$("#div_"+id).html(html);
} });
window.open('File_download.php?file_id='+id, '_blank' );
});
as you can see window.open call is after $.ajax call
Does it guaratee that $.ajax call will get executed every time before the page reloads and if no then
shouldn't we declare window.open in success function?
In my opinion when there is slow response from server the page will reload first and it may happen that $.ajax call will be interrupted by window.open function
but i get a downvote for the same reason here stackoverflow.com/questions/12908138/how-to-get-the-id-or-name-of-related-file/
And Thanks for making my belief stronger
In your example, the window.open function will always (!) be called before the success callback function given to the ajax call. Ajax traffic is always asynchronous, whereas the window.open function resides in the synchronous JS <script> tag.
Since JavaScript is single-threaded, all synchronous statements will always be executed before any asynchronous functionality like ajax setTimeout animate etc.
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html) { // asynchronous functionality
$("#div_"+id).html(html);
}
});
// within synchronous script statements
window.open('File_download.php', '_blank' );
Yes, Ajax is asynchronous so you will open that window right after you started the XHR process. To download the processed data, open the new window from the success callback. Yet I'm not sure what you mean by "before the page reloads" - there is no code which does that.
Also I don't know how your server behaves, the file_download.php seems to be independent from your ajax call. Shouldn't you pass the download_number you received via ajax in there?