Running image loading with jQuery Ajax .done() method - javascript

I am trying to create a simple loading animated indicator in this demo. In my jQuery Ajax call I am trying to use new methods and style of Ajax request as:
var req = $.ajax({
type: "POST",
url: "datapro.php"
});
req.done(function(data) {
//do something
)};
Now my question is if the .ajaxStart() and .ajaxComplete() are compatible with new versions of jQuery? If so, how I can call them in req object? Is it possible to call them like req.ajaxStart() and req.ajaxComplete()?
If so, where to call them? I am guessing to use the req.ajaxComplete() at very end of request after .done() but I am confused where to use the req.ajaxStart().
<script>
$(document).ready(function(){
$(document).ajaxStart(function(){
$("#wait").css("display","block");
});
$(document).ajaxComplete(function(){
$("#wait").css("display","none");
});
$("button").click(function(){
$("#txt").load("demo_ajax_load.asp");
});
});
</script>

Use this:
$.ajax({
beforeSend:function(){
$("#wait").css("display","block");
},
type: "POST",
url: "url",
success: function(data) {
//do something here using data
},
complete:function(){
$("#wait").css("display","none");
}
});

Try this:
$("#wait").css("display","block");
$.ajax({
type: "POST",
url: "datapro.php",
success: function(data) {
$("#wait").css("display","none");
}
});
DEMO
A excellent work for loading pictures
jQuery.fn.extend({
loadImage:function(appendTo,callback){
return this.each(function() {
$("#wait").css("display", "block");
$(this).load(function(){
callback();
$("#wait").css("display", "none");
}).appendTo($(appendTo));
});
}
});
$(document).ready(function () {
$("button").click(function () {
var img="<img src='http://oi50.tinypic.com/16a4do9.jpg'>";
$(img).loadImage("body",function(){
alert("load");
});
});
});
DEMO

Depending on which AJAX function you are going for, you must use the specified completed function in order to accomplish what you are trying to do. Those two AJAX functions, which you are talking about are meant to be triggered on any AJAX requests which are made within the document, thus not really reliable if you have multiple requests and you only want to bind it to one request.
In your case it would look something like below, where we use your load function and then use the completed function on when AJAX request has been completed. Keep in mind show and hide functions are handy for display: block and display: none CSS property settings respectively, I included them in the below example.
<script>
$(function(){
$("#wait").show();
$("#txt").load("demo_ajax_load.php", function(response, status, jqxhr){
// AJAX request has been completed
$("#wait").hide();
switch (status) {
case 'error':
// Miscellaneous error occurred (use jqxhr.status and jqxhr.statusText for details)
break;
case 'timeout':
// Connection timed out
break;
case 'notmodified':
// Target URL resource has not changed since last visit
break;
case 'success':
// All went well
break;
case 'parsererror':
// JSON parser stumbled across to an error
break;
default:
// jQuery error strings have changed since last time
break;
}
});
});
</script>
You can use either of these to make a POST request, so either one is okay in your case. You should not be using the POST method for requests that contain no actual data, GET method is better for that.
Whichever one of these examples you may use, you should be using a plain object for your data. Otherwise you should use the above example, or instead of using post function you would use the get function.
<script>
$(function(){
$("#wait").show();
var jqxhr = $.post("demo_ajax_load.php");
jqxhr.done(function(response){
// AJAX request was a success
$("#txt").html(response);
});
jqxhr.fail(function(response){
// AJAX request was a failure
});
jqxhr.always(function(response){
// AJAX request was completed
$("#wait").hide();
});
});
</script>
Hopefully this helped you out.

Related

jquery doesn't work after an ajax call (response in a pop up window)

I've a jsp page with a form and some jquery code. Jquery code works perfectly, but if I return that page in a popup window by using an ajax call, the jquery code doesn't work any more.
I tried also to use delegation, that is:
$('select[name=myElementName]').on("change", function() {
// some code
});
or
$(document).on("change", 'select[name=myElementName]', function() {
// some code
});
instead of
$('select[name=myElementName]').change(function() {
// some code
});
Ajax call:
var preview = function () {
$.ajax({
type: "POST",
url: myAction.do,
data: "id=" + myid,
success: function (response) {
// some code
var x=window.open('', '_blank', 'titlebar=no,scrollbars=yes,menubar=no,height='+height+',width='+width+',resizable=yes,toolbar=no,location=no,location=0,status=no,left='+left+',top='+top+'');
x.document.open();
x.focus();
x.document.write(response);
return false;
},
error: function () {
return false;
},
});
};
EDIT
On Firefox 26.0 and Chrome 32.0.x, I resolved by using
x.document.close();
after
x.document.write(replace);
Instead, on IE, all the .js included scripts are ignored (for example the jquery-ui-1.9.1.js).
EDIT 2
I resolved with
<body onload="myload()">
and in my jsp I've myload() definition in which I call the scripts.
It is because you are creating new DOM structure but it doesn't have the event handlers attached. The easiest way is to run the event handler in the ajax callback:
$.ajax({
...
success: function (response) {
// some code
var x=window.open('', '_blank', 'titlebar=no,scrollbars=yes,menubar=no,height='+height+',width='+width+',resizable=yes,toolbar=no,location=no,location=0,status=no,left='+left+',top='+top+'');
x.document.open();
x.focus();
x.document.write(response);
// now, place the event handler here
$('select[name=myElementName]', x.document.body).change(function() {
// some code
});
}
});
Don't use document.write it completely overwrites whatever is on the page at the time of writing and leads to race conditions (e.g. the external scripts might have already been loaded, but they also might not, leading to unknown order of the write and script loads). Also, I believe documnt.write is putting serialized text into the document, not DOM objects so it may not trigger events.
Instead, you can open the new window and then manipulate the DOM objects there directly (assuming it's on the same server as your main page):
//Open a new window for the success info
var newWindow = window.open(newUrl);
//Now grab some element
var someItem = newWindow.document.getElementById( "someId");
//Manipulate dom either by "someItem.innerHTML" or "someItem.appendChild(...)"
If you are calling an AJAX server routine and putting the entire response w/o processing it on the client in to a new window, why not opening the window directly with the URL of that AJAX routine and skipping all stuff:
....
var x=window.open(myAction.do + "?id=" + myid,
'_blank',
'titlebar=no,scrollbars=yes,menubar=no,height='+height+',width='+width+',resizable=yes,toolbar=no,location=no,location=0,status=no,left='+left+',top='+top+'');
....
The only diff here is, that the request is a GET and not a POST request, but the data is just one id, which is acceptable, probably?
I had a similar problem in on of my projects. I solved it by writing a success method after the ajax call.
{
$.ajax({
type: "POST",
url: "/abc/",
data:{<data>},
async:false,
dataType:'json',
success: function(response)
{
success=1;
Id=response;
return;
}
});
if (success)
{
#your code here
var a='/xyz/?Id='+Id
window.open(a,'_blank');
window.location.href='/registration/'
}
return false;}
instead of using document.write, try fetching your success data(records arrived in success function) in a hidden DIV and clone it into your popup that should work

Ajax with Jquery - Callback not executing

I have tried so many things, cannot figure this out, I am using this code, and I know that the start is working, because the script it connects to sticks some info in the db, but the callback never runs.
<script type="text/javascript">
$(document).ready(function() {
$(document.body).on('click', "#reply_submit", function() {
var formData = $('#reply').serialize();
$.post("newpost.php",formData, function(data){
alert("hi");
}, "json");
});
});
My form's id is "reply" and the button I am using to submit it is "reply-submit", just to make sure those things are clear.
It also doesn't work if I remove that last "json" thing btw.
If you read the docs for jQuery.post(), it says this about the callback:
success(data, textStatus, jqXHR)
A callback function that is executed if the request succeeds.
If it's not getting called, it means that request did not succeed. There is probably an error in newpost.php (sometime after the data insert, but before it would normally exit).
You can also catch error conditions by using the long-form jQuery.ajax() instead of the post shorthand:
$.ajax({
url: 'newpost.php',
data: formData,
type: 'post',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
alert('success');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error!');
}
});
When you click, the form is also being submitted the standard way. Modify your click handler like this:
$(document).on('click', "#reply_submit", function(e) {
e.preventDefault(); // prevent the default submit event
var formData = $('#reply').serialize();
// ...
});
Although I think document.body should be a valid node to wrap in jQuery, I've also modified it to the more commonly used document.
On that note, if the form is never destroyed by an Ajax event or other DOM modification, you could bind to #reply instead of document (or body).
I'm simply assuming that you want to submit a form without reloading the whole page.
Based on that assumption, following code will serve the purpose.
$(document).ready(function(){
//on form submit event
$('form#reply').submit(function(){
$.post('newpost.php',$(this).serialize(),function(){
alert("Message or do something with the response data if you are expecting one");
});
//prevent default action
return false;
});
});
Please ignore the post if this is not the functionality you are looking for in your project.

Detect if and when any jQuery AJAX calls are made

I have a toolbar that exists on all my webpages that makes requests to a server side XML file regularly.
Some of the web pages also make requests to the same XML file, but more frequently. Ideally I would like to, where possible, combine this easily into a single request. Where the toolbar uses the same request that the page made (as the page refresh rate is greater than that of the toolbar)
Is there any way to tell if any jQuery AJAX calls have been made to a certain resources and, if so, be notified on success?
Update:
Based on Darin Dimitrov's answer I have tried the following:
$.ajaxSetup({
success: function(){ console.log("woop"); }
});
This never fires, I presume because the success handler is being overwritten when I make my other AJAX calls.
You could use the $.ajaxSetup() to subscribe for the common events.
Subscribe to all ajax events at the document level;
$(document).bind("ajaxSend", function(){
alert('ajax fired');
});
In your AJAX add response callback, something like this:
$.ajax({
type: "POST",
url: "mypage.php",
data: "name=John&location=Boston",
success: function(data){
alert(data);
}
});
and on your php page where you process AJAX request add some echo statement:
echo "POSTed OK!";
If you post is a success you'll get an alert confirmation.
You can also get a confirmation if it failes but modifying the code slightly:
success: function(result) {
if (result==1) {
alert('Success');
} else {
alert('Failed');
}
}
Good luck!

Simple ajax call seems to be blocking

Really simple question. I trying to test a Restful webservice that I am developing, and have this simple ajax call (using jquery):
<script type="text/javascript">
$(document).ready(function() {
var url = '/index.php/gettest/reallyLongRequest';
$.ajax({
url: url,
dataType:'text',
success:function(data) { $('#result').html(data);},
error:function(xhr,err,e) { alert ("Error: " + err);}
});
});
</script>
This runs when the page loads. As it's running, the page is blocking; i.e., (I can see the hourglass next to the mouse pointer) no other user actions can be handled. (Btw, this particular get request--intentionally--takes a very long time to return).
Why is this? A(asynchronous)JAX right? Obviously I am making a beginners mistake. Any ideas, please?
When I attempt this using plain javascript (no library) it works as expected. Does this have something to do with Jquery's handling of the xhr onreadystatechange?
Thank you for looking.
EDIT: multiple people have suggested setting async: true, which as it happens, is the default in jquery, and as such has no effect.
EDIT: As previously mentioned, if I use plain javascript and start this with a timer, e.g., window.setInterval(function() { startLongPoll(); }, 5000)
It updates as expected, without appearing to block. Ideas, anyone?
Here is an example of what I did to solve the problem:
jQuery(document).ready(function() {
setTimeout(function () {
$.getJSON("veryLongRequest", function(json) {
alert("JSON Result: " + json[0].id);});
}, 500); // You may need to adjust this to a longer delay.
});
Note: I am using the short-hand jquery method, "getJSON" which is a wrapper for the ajax call with datatype set to "json". However, this solution will work for all ajax requests.
Referenced:
Stop the browser "throbber of doom" while loading comet/server push iframe
I think that this should default to true, but try adding async: true to your ajax json parameter.
Does the code below work as expected?
<script type="text/javascript">
//$(document).ready(function() {
var url = '/index.php/gettest/reallyLongRequest';
$.ajax({
url: url,
dataType:'text',
success:function(data) { $('#result').html(data);},
error:function(xhr,err,e) { alert ("Error: " + err);}
});
//});
</script>
May want to try and Add async:true
<script type="text/javascript">
$(document).ready(function() {
var url = '/index.php/gettest/reallyLongRequest';
$.ajax({
url: url,
async:true,
dataType:'text',
success:function(data) { $('#result').html(data);},
error:function(xhr,err,e) { alert ("Error: " + err);}
});
});
</script>

Executing JavaScript after Ajax-call

I want to execute javascript for creating calendar using "calendarDateInput.js". Is it possible to execute javascript after an ajax call page using ajax tabs ?
I am not using any of the ajax libraries, only direct ajax call.
Here I want to call the function in an ajax returned page like DateInput("smsDate",true, "YYYY-MM-DD");
Usually this is done by Callback functions. If you use libraries like jquery they usually provide hooks for callbacks.
check out jQuery.ajax() for doing the ajax call and then onsucess you can run additional javascript code...
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.post/
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
I hope this is what you were asking for... otherwise please add some additional information to your question...
if you would not like to work with libraries like jquery ....
you have to check for the request status of you ajax call....
req = new XMLHttpRequest();
and then you have to check the response for following values
// IF completed
if (req.readyState == 4) {
// Server HTTP Code
if (req.status == 200) {
but jquery did all the work for you...
yes.
for non jQuery:
var httpRequest = new XMLHttpRequest(); //your AJAX object
httpRequest.onreadystatechange = AJAXhandler; //your ajax handler function
function AJAXhandler() {
if (httpRequest.readyState === 4) { //if success
//process..
//"YOU CAN CALL OTHER FUNCTIONS HERE"
}
}
When using jQuery or normal javascript, callbacks are THE way things like this are handled. For example, using jQuery:
$.ajax({
type: 'POST',
url: 'PathTOMyUrl.html',
success: function(data)
{
// This Callback will be invoked on successful call
},
error: function(data)
{
// This callback will be invoked on an error
}
});
The callbacks can then contain code you find useful. In normal javascript, you would attach to the onreadystatechanged event on your AjaxRequest. You can find more information here.

Categories