Executing JavaScript after Ajax-call - javascript

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.

Related

Error when storing JSON after an ajax request (jQuery)

I'm quite new to JavaScript/jQuery so please bear with. I have been trying to store the resulting JSON after an ajax request so I can use the login info from it later in my program. I get an error stating that "Data" is undefined. Here is the problematic code:
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(){
var SessionData = Data();
(FunctionThatParsesJSON);
}
})
}
I have checked the URL manually and it works fine (including) being wrapped in the "Data" function. From what I have found online, this may be something to do with ajax been asynchronous. Can anyone suggest a way of storing the JSON so that I can use it later?
Try something like the following;
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(data){
functionToProcessData(data)
})
}
When making your ajax call, you can handle the response given by assigning a parameter to the function. In the case above, I have passed the 'data' parameter to the success function allowing me to then use it in further functions (as demonstrated by 'functionToProcessData(data)'.
The response from ajax call is captured in success handler, in this case 'data'.
Check below code:
success: function(data){
var SessionData = data.VariableName;
// Here goes the remaining code.
}
})
Since people ask about explanation, thus putting few words:
When we do $.ajax, javascript does the async ajax call to the URL to fetch the data from server. We can provide callback function to the "success" property of the $.ajax. When your ajax request completed successfully, it will invoke registered success callback function. The first parameter to this function will be data came from server as response to your request.
success: function ( data ) {
console.log( data );
},
Hope this helps.
Internally everything uses promises. You can explore more on promises:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Apparently you are using JSONP, so your code should look like this:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp",
success: function (data){
(no need to parse data);
}
});
Another option:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp"
})
.done(function (data){
(no need to parse data);
});
See the documentation and examples for more details.
success: function (data, textStatus, jqXHR){
these are the arguments which get passed to the success function. data would be the json returned.

Running image loading with jQuery Ajax .done() method

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.

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

cancel ajax() success

I'm using dynamic pagination.
I need to cancel the success event in jQuery ajax before starting another.
I've set a variable equal to $.ajax(), and before doing so, I call abort no matter what.
The problem is that success still fires.
The answer for Ajax: How to prevent jQuery from calling the success event after executing xmlHttpRequest.abort(); is wrong, or at least it doesn't work for me because if I fire abort right after the ajax nothing ever happens.
I just want the success of the ajax variable not to fire if another one is about to start.
Code Snippet:
if(updatePageAJAX){
updatePageAJAX.abort();
}
updatePageAJAX = $.ajax({
});
I can provide more detail if you like, but updatePageAJAX works. I couldn't tell you if abort works. I put an alert in the if to see if it fires; it does.
If I put abort right after setting updatePageAJAX = $.ajax, nothing ever happens.
Have you tried saving your xhr object in a variable so that you can check in the success callback if it is the right xhr object?
For example:
$(function() {
var xhr = null;
$('.link').click(function() {
var page = $(this).text();
if(xhr != null) {
xhr.abort();
}
xhr = $.ajax({
type: 'GET',
url: 'index.php',
data: 'js=true&page=' + page,
success: function(data, responseCode, jqxhr) {
if(xhr == jqxhr) {
$('#page').text(data);
xhr = null;
}
}
});
});
});
This way, the success callback won't execute if this is not the right request.

How do I use JS to execute a heavy PHP function after the page loads in order to speed things up?

I've got a web page that displays some content. The query itself is pretty slow (4000 ms).
I don't want my users to have to wait for the query to run before the rest of the page loads though.
Is there a way I can stick some code before and after the tag in my HTML template that will "delay" that function from executing until after everything else has rendered?
e.g.:
<javascript code that tells the page not to render what comes next until very last>
<?php my_heavy_php_function(); ?>
</javascript>
As I can understand from your question, you should go for AJAX: you first load the page without the heavy content, and when the page is ready you do an AJAX call to a webservice to fetch and display the data, while showing a "Processing, please wait" message to the user.
symbolic write:
document.onload = ajax call
Using Ajax
Using the jQuery Ajax request method you can post the email data to a script (submit.php). The $(function(){ }); executes when the dom is ready. Also, you might need to use the 'timeout' option if you are going to be executing an long query.
note - I would suggest utilizing the ajax Response Object to make sure the script executed successfully.
$(function() {
$.ajax({
type: 'POST',
url: 'submit.php',
timeout: 10000,
error: function()
{
alert("Request Failed");
},
success: function(response)
{
//response being what your php script echos.
}
});
});
Although, jQuery is by no means required do do an ajax request, I would highly recommend using some kind of framework to help ensure x-browse support.
If you are using a large dataset I would highly recommend using json to encode your repsonses. It makes parsing quite easy. Here's an example with jQuery $.getJSON() API and likewise how you can encode it with PHP
Either optimizing the query or doing an AJAX call. Here is a plain JS way of doing AJAX, I found this script in a Google search and modified to use a callback function so you can parse the data or do other things other than just load the content straight to a HTML element:
the ajax function: The Original function I found unmodified
function ajaxRequest(Url, callback) {
var AJAX;
try {
AJAX = new XMLHttpRequest();
}
catch (e) {
try {
AJAX = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX.");
return false;
}
}
}
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4) {
if (AJAX.status == 200) {
callback(AJAX.responseText);
}
else {
alert("Error: " + AJAX.statusText + " " + AJAX.status);
}
}
}
AJAX.open("get", Url, true);
AJAX.send(null);
}
Usage of it:
<div> some normal content </div>
<div id="loadlater">loading data...</div>
<div> more content that loads before the data</div>
<script>
ajaxRequest('/echo/html/', function( response) {
document.getElementById('loadlater').innerHTML = response;;
});
</script>
Working example here: JSFiddle

Categories