I have object "game" and when i call create game, its use jquery ajax... everything works ok, but when i want to call from ajax success function addLoadEvent it doesnt call it, when i try call this function from createGame (commented part of code here) its works... do you know why i cant call it from ajax success? i try console log from success and it was print in console so ajax works well. Thank everybody for help
var game=new ttt_game();
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function ttt_game () {
this.createGame = createGame;
function createGame(){
/*addLoadEvent(function(){
document.getElementById('player1_n').textContent=player1+':';
document.getElementById('player2_n').textContent=player2+':';
document.getElementById('turn').textContent='Čaká sa na príchod súpera.';
});*/
$.ajax({
type: "POST",
url: "process.php",
data: {'function': 'create','game_id': game_id,'player1': player1},
dataType: "json",
success: function(data){
addLoadEvent(function(){
document.getElementById('player1_n').textContent=player1+':';
document.getElementById('player2_n').textContent=player2+':';
document.getElementById('turn').textContent='Čaká sa na príchod súpera.';
});
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
}
game.createGame();
it looks like on addLoadEvent, you are adding a window.onload handler, this works when you call from createGame when when it is called the window.onload is not yet fired but when you are calling it from the success handler the onload event might have already fired because the ajax is processed asynchronously
Related
In the below code I am making an API call to my backend node.js app using setTimeout() which calls my AJAX at every 5 seconds. Inside my AJAX success I am displaying divContent1 & divContent2 based on certain condition which should execute at least once. After that only divContent2 should be visible at each setTimeout() calls.
index.html
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "http://localhost:8070/api/route1",
type: 'POST',
dataType:'json',
success: function(res) {
//Some Task
}
});
$("#myButton").click(function(){
const route2 = function() {
$.ajax({
url: "http://localhost:8070/api/route2",
type: "POST",
dataType: "json",
data: { var1: val1 },
success: function (res) {
// Various tasks
if(res.flag){
$("#divContent1").hide();
$("#divContent2").show();
}
else{
$("#divContent1").show();
}
//Functions that handle div content data
},
beforeSend: function() {
$("#divContent1").hide();
$("#divContent2").hide();
},
complete: function() {
setTimeout(route2,5000);
},
});
};
$(function(){
route2();
})
});
});
</script>
The setTimeout() calls the entire route2 function which handles all the display and insertion of div content. However, the ask is to only display divContent2 from the second call.
Looking for a solution for this
The setTimeout() calls the entire route2 function which handles all
the display and insertion of div content. However, the ask is to only
display divContent2 from the second call.
You're calling route2 recursively with setTimeout(route2,5000); under complete. So this will run infinitely as complete occur each time an ajax call is completed (wether success or error). So what you can do is to create a timer and clear it after the second execution, something like this:
var ctr = 0, timer =0;
const route2 = function() {
$.ajax({
...
success: function (res) {
//Write you logic based on ctr
}
complete: function() {
if(ctr>0){
clearTimeout(timer)
}else{
timer = setTimeout(route2,5000);
ctr = ctr+ 1;
}
},
});
};
Will an external variable be enough? Just define it in the outer context and set/check it to choose the behavior:
// before declaring button click handler
var requestDoneAtLeastOnce = false;
// ...
// somewhere in success handler
success: function (res) {
if (!requestDoneAtLeastOnce) {
requestDoneAtLeastOnce = true;
// do something that belongs only to handling the first response
}
else {
// this is at least the second request, the other set of commands belongs here
}
}
Basically, I have a page in which I include a javascript file. in the js file
i have 2 functions called function a() and function b(). Inside Function "A" I called the popup to be loaded. After the child popup is loaded I have a function called interactive which makes an ajax call. if the result is true I need to close the child page and then call the function "B" in the main page.Below is the sample code. The problem is I am not able the refer the function "B" in the child page and make a call to the main page.
function a() {
var strWindowFeatures = "location=yes,scrollbars=yes,status=yes";
var URL = path of the url
var win = window.open(URL, "_blank", strWindowFeatures);
}
function b() {
calling a
function to relaod the page. //
}
function InterActive(encodeText) {
url: url
cache: false,
async: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
dataType: 'json',
success: function (data) {
if (data === true) {
alert('record updated');
window.close();
// i need to call the function b() in the child page..
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR);
alert(textStatus);
alert(errorThrown);
}
});
You can do it in such a way that the window you open receives an onbeforeunload event that calls your reload function in the parent window.
An example would be the following
function reloader() {
if (!reloader.id) {
reloader.id = 0;
}
document.querySelector('#reloadCount').innerHTML = ++reloader.id;
}
function openWindow() {
var win = window.open('about:blank', 'blank', 'width=640,height=480');
win.document.write('<html><head><body><h1>Reloads on close</h1></body></html>');
win.addEventListener('beforeunload', function() {
reloader();
return true;
});
}
Which you can test on jsfiddle here (window.open is not allowed in the stacksnippets)
I think you need to add function b() in child page so it's easily access,So please check with this.
I'm trying to call an ajax before user leaving a page, this what i have done so far. But it doesn't even hit the ajax page.
This is what i have done so far.
window.onbeforeunload = closeIt();
function closeIt()
{
var key="save-draft";
$.ajax({
url: "app/ajax_handler.php",
type:"GET",
data:{key:key},
success: function(data) {
return data;
}
});
}
I Have tried this one also both failed in my case.
$( window ).unload(function() {});
The only way I think is to let the user know that it's a process on background with a confirm message, that will block the exit until user click on Accept or you've got the response.
Something like that:
window.onbeforeunload = closeIt();
function closeIt()
{
/*var key="save-draft";
$.ajax({
url: "app/ajax_handler.php",
type:"GET",
data:{key:key},
success: function(data) {
return data;
}
});*/
setTimeout(function() {
return confirm("There is a process that isn't finished yet, you will lose some data. Are you sure you want to exit?");
}, 1000);
}
I have an upload button that when clicking calls an ajax function to upload document. Once that function runs I call another ajax function to refresh a table on screen displaying all my documents. I have been looking at this question - Wait until all jQuery Ajax requests are done?
which would seem to be what I need. However I am un-sure how to implement for my current code. I have:
$("#UploadButton").on('click', function () {
doUpload(); // My First AJAX function
refreshTable(); // My Second AJAX Function
});
My doUpload AJAX function is as below:
function doUpload() {
$.ajax({
url: 'myupload url',
type: 'POST',
data: new FormData($('#uploadForm')[0]),
processData: false,
contentType: false,
success: function () {
$.growlUI('Document Uploaded Sucessfully');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
}
});
}
My refreshTable ajax function then is:
function refreshTable() {
$.ajax({
url: 'url to get all files',
type: 'GET',
data: $('#searchForm').serialize(),
success: function (data) { populateTable(data); },
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status + " " + thrownError); }
});
return false;
}
If I upload a document with current solution the success function of refreshTable seems to get hit too quickly and it doesn't have the find the most recent file uploaded. I had tried to add the call to refreshTable() in the success function of my doUpload with a setTimeout of 5 seconds and sometimes this was working and refreshing the table but other times it wasn't uploading the table.
I then changed the click handler on the button to the below to attempt to have the functionality the other StackOverflow answer I linked to above has but this isn't working either
$("#UploadButton").on('click', function () {
$.when(doUpload()).done(function() {
refreshTable();
});
});
You can use callback mechanism.
function doUpload(callback) {
$.ajax({ //some parameters
success: function (data) {
//do some work here
callback();
}
);
}
Then you can call the function chain as:
doUpload(refreshTable);
EDIT : #qamyoncu answers is better than mine.
In AJAX, calls are done async. that's why you don't get what you want.
Here is a tricky solution to avoid the problem you have:
function doUpload(init) {
var res = null;
var _init = init || false;
if (!_init) {
_init = true;
$.ajax({
/// ajax call for doUpload()...
});
}
if (res == null) {
setTimeout(function(){ doUpload(_init); }, 100);
} else {
refreshTable();
}
}
Here is the scenario:
I am sending ajax request when user click on anchor tag to fecht & update instagram media status.
But it take sometime to retrieve the response, in that time user clicked N number of time on that anchor tag.
So each time it sends the request, I am don't want such behaviour ..
Is there any easy way to handle such situation?
Currently I am adding the class when user clicked on it, and using that I am deciding user has click on anchor tag or not??
Please let me know, if it is correct way or not..
Here is fiddle URL (Not clicked on link at least 2+ times, it send 2+ request which is i don't want )
http://jsfiddle.net/bkvaiude/mxb8x/
thanks
You should use should remove the click event and then set it up again when the ajax call is complete:
Instead of setting it in the success call as the others do; you should use the complete callback to set it. To make sure if the server returns an error it is still binding the click event again.
http://jsfiddle.net/eWwZt/
(function (){
console.log("bhushan");
var ajaxCall = function(e){
$("#test").off("click");
console.log("click");
e.preventDefault();
var is_liked_url = "https://api.instagram.com/v1/media/popular?client_id= b52e0c281e584212be37a59ec77b28d6";
$.ajax({
method: "GET",
url: is_liked_url,
dataType: "jsonp",
success: function(data) {
console.log("data...");
},
complete: function(){
$("#test").on("click", ajaxCall);
}
});
}
$("#test").on("click", ajaxCall);
})();
Put a flag to check if ajax call completed or not this way:
(function (){
var RequestInProgress = false;
console.log("bhushan");
$("#test").on("click", function(e){
e.preventDefault();
if(!RequestInProgress) // if request not in progress send
{
RequestInProgress = true;
var is_liked_url = "https://api.instagram.com/v1/media/popular?client_id= b52e0c281e584212be37a59ec77b28d6";
$.ajax({
method: "GET",
url: is_liked_url,
dataType: "jsonp",
success: function(data) {
console.log("data...");
RequestInProgress = false;
}
});
}
});
})();
UPDATED FIDDLE
You can use .off() to unbind click to element.
(function () {
console.log("bhushan");
var Myfunction = function (e) {
$("#test").off("click"); //Unbind click
e.preventDefault();
var is_liked_url = "https://api.instagram.com/v1/media/popular?client_id= b52e0c281e584212be37a59ec77b28d6";
$.ajax({
method: "GET",
url: is_liked_url,
dataType: "jsonp",
success: function (data) {
console.log("data...");
$("#test").on("click", Myfunction);
}
});
};
$("#test").on("click", Myfunction);
})();
DEMO
try this
var gettingData =false;
$('selector').click(function() {
gettingData = false;
if (!gettingData) {
gettingData =true;
$.ajax(//do ajax logic)
.success(
gettingData = false;
//parse data)
.error(
gettingData = false;
//display some error
);
} else {
return false;
}
});