Continue running script once jquery ajax call is successful - javascript

I have a click function that has a popup window that I need to open once the ajax call is successful. I have tried setting async: false. I tried putting the popup in the ajax call but that makes the popup blocked by the browser. And my last attempt was to set a timeout until the ajax call completes and each with no luck. Any suggestions???
var currentStatus = "false";
var success = "false";
function waitForSuccess(){
if (success == "false"){
var t = setTimeout("waitForSuccess()", 300);
}
else{
stopTimer(t);
return "true";
}
}
function stopTimer(t){
clearTimeout(t);
}
function checkReps(clicked){
$.ajax({
cache: false,
url: "chat_new_files/chat_new.php",
success: function(data){
success = "true";
}
});
$('#chatT').live('click', function (event) {
success = "false";
checkReps("true");
var changed = waitForSuccess();
if(changed == "true"){
BG.startChatWithIssueId('0', true); //THIS IS THE POPUP
}
});
I am thinking that my logic for this last attempt with the setTimeout is messed up. So any ideas on how to fix this or a brand new idea? Thanks!

Open the popup in the success: function for the ajax call. That is the only place that you both know that the ajax call has completely successfully and that you have access to the data that is returned from the ajax call.
Do not use timers to try to guess when the ajax function is done.

You are over-complicating things:
$('#chatT').live('click',function(){
$.ajax({
cache: false,
url: "chat_new_files/chat_new.php",
success: function(data){
BG.startChatWithIssueId('0', true);
}
});
});
As far as the browser popup blocker issue, a simple work-around is to create a div which acts as a popup container, like <div id="popup"></div>. Inside that div you can add an iframe with the url being the same of what your oldskool popup was. Initially, give that div the CSS #popup { display:none; position:relative; z-index:99999; /* etc...*/ } Then in your click event, you simply show() or fadeIn() that div.
Example, check out Colorbox - on the demo page, click the link that reads "Outside Webpage (Iframe)"

Use a callback that you can call in success of $.ajax(). Then open you popup window in the callback.
function checkReps(clicked){
$.ajax({
cache: false,
url: "chat_new_files/chat_new.php",
success: function(data){
success = "true";
openPopup();
}
});

Browsers tend to block popups that aren't originated from an event handler because those popups tend not to be user-initiated (duh). To get around this, you have 2 choices:
launch the popup immedately and have its content be filler, probably
including some sort of http://ajaxload.info spinner gif
avoid opening a new window, and instead put your content in a 'modal' div that you
show and hide as required.

Related

JQuery not opening the already opened window when clicked twice

I am relatively new to JQuery. I have an anchor tag in JSP which when clicked calls a function and it in turn calls an action class. If the result is success, it has to open a window. It works fine for the first time. But when i click on the anchored url for the 2nd time, control goes to action class but it doesnt pop up the already opened window. It doesnt even open a new window. Please suggest how to resolve it ?I need to pop up the already opened window.. I am sure it is due to jquery ajax call because the functionality works fine with out using ajax jquery. But i need to use it in my scenario
Sample code:
Open W3Schools
function func1() {
$.ajax({
url: "abc.do",
success: function(response){
window.open("https://www.w3schools.com","MyWindow","left=10,top=20,width=1200,height=700,scrollbars=1,resizable=1, status=1, modal=yes");
},
error: function(e){
alert('Error: ' , e);
}
}); }
Probably your browser detects a pop-up and blocks it without telling your program. How are you calling your function? Usually repeated window.open calls will only work in an event listener like
button.addEventListener("click", ()=>{
func1();
});
So if you have it in a loop or a similar thing, there's not much you can do about pop-up protection.
Try passing an empty name to your window instead of MyWindow, like this:
function func1() {
$.ajax({
url: "abc.do",
success: function(response){ window.open("https://www.w3schools.com","","left=10,top=20,width=1200,height=700,scrollbars=1,resizable=1, status=1, modal=yes");
},
error: function(e){
alert('Error: ' , e);
}
}); }

jQuery stop load() if another load() is initiated on the same container

I have a dynamic website with a lot of AJAX and jQuery loading in different modules to different containers.
For the purpose of my question, consider that I have 3 buttons and one container. Clicking button A loads a.php into the container using jQuery
$('.container').load('a.php');
Now consider that module b.php is a module that takes about 3-4 seconds to load because it's grabbing content from another website and parsing it.
When I click button B to load module b.php, but then quickly click button A again to load module a.php, my problem occurs: module a.php quickly loads in the container, but the loading of module b.php was still in progress, therefore, after another second or 2-3, module b.php loads into the container, even though the user last clicked button A.
So here's my question: how can I stop the loading of module b.php if a user clicks another button.
Note: as a work-around I've thought of disabling the buttons until the loading of each module has completed. It does prevent the issue, but it's not the desired end result.
EDIT: So I've seen this: Aborting jQuery().load() and yes, I can get it working using AJAX. Thanks to everyone who suggested this. I'm hoping to find an answer that actually works with load() but haven't found one that works yet.
By using beforeSend, You can abort first ajax request before sending next ajax request , see example
<button onclick="onClickBtnA()">A</button>
<button onclick="onClickBtnB()">B</button>
In your jQuery
var currentRequest = null;
function onClickBtnA(){
currentRequest = $.ajax({
url: 'AJAX_URL_1',
beforeSend : function() {
if(currentRequest != null) {
currentRequest.abort();
}
},
success: function(data) {
//do something
}
});
}
function onClickBtnB(){
currentRequest = $.ajax({
url: 'AJAX_URL_2',
beforeSend : function() {
if(currentRequest != null) {
currentRequest.abort();
}
},
success: function(data) {
//do something
}
});
}
Make a global variable and abort it every time you load data
<button>Get External Content</button>
var xhrPrevoius; // use this global var and assign it for your previously
// loaded ajax when you making ajax request
var xhrThis;
$("button").click(function(){
$("#div1").load("demo_test.txt", function(responseTxt, statusTxt,
xhrThis){
if(statusTxt == "success")
// do you work here
xhrPrevoius.abort(); // abort here the previously loaded ajax
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
If you want to stick with using load, rather than doing an ajax request as has been suggested, you could load into a hidden div, then use load's callback option to decide whether or not to copy from the hidden div into a visible component.

While using strutst html tags, how can I call onclick event on submit button?

I have parent page where there is an element. Onclick of that element popup window comes. On popup window there is one textbox and submit button. Now I want to refresh parent page when submit button on popup window clicked.
I have solution to refresh parent page:
window.onload = function()
{
window.opener.location.reload();
}
I have added this script in popup jsp page. So whenever I click on element on parent page, popup window comes and parent page gets refreshed(want to skip this), then I add some text in textbox on popup and submit the data, since it is submit button popup again reloads and parent page gets refreshed(which is expected to happen). Since I am using window.onload on popup page, it gets refreshed twice, I want to skip first refresh.
So I decided to perform refresh on click of submit button.
Popup page JSP code:
<td align="center">
<html:submit styleId="btn_add" property="submitButton" onclick="formConfirmOff();" value="Add" />
</td>
Another solution I was trying to skip first refresh:
document.getElementById("btn_add").onclick = function(){
window.opener.location.reload();
}
But using above script it gives me error that cannot set property onclick of null
so it may be because script is getting executed before DOM loads. so I added script in
window.onload = function(){
document.getElementById("btn_add").onclick = function(){
window.opener.location.reload();
}
}
But when did this shows Confirm Navigation dialog with options Leave this page and stay on this page.
What may be the issue. Does the order of function passed to onclick matters ?
I simply want to refresh parent page when data is added on popup child page using submit button.
EDIT:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST", //chose your request type method POST or GET
url: "/webapp/addSpeedDataAction.do", // your struts action url
data: $(this).serialize(),
success: function() {
window.opener.location.reload(); // callback code here
}
})
})
});
Sometimes this code works but sometimes not.
Means when popup opens I submit the data on popup. Then on success parent window gets refreshed. But still I can not see updates on parent page.
what may be the issue ?
You will need to do this manually using AJAX call to your server and on successful execution you will refresh your parent page.
Below is example of using JQuery Ajax :
<script type="text/javascript">
$(document).ready(function() {
$("#form_selector").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST", //chose your request type method POST or GET
url: "Your_Action", // your struts action url
data: $(this).serialize(),
success: function() {
window.opener.location.reload(); // callback code here
}
})
})
});
</script>
Here is JavaScript version :
var url = "/webfdms/addSpeedDataAction.do";
xmlHttp.open("GET", theUrl, true);
xmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlHttp.overrideMimeType("application/octet-stream");
xmlHttp.responseType = "blob";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == xmlHttp.DONE) {
if (xmlHttp.status == 200) {
window.opener.location.reload();
}
}
};
xmlHttp.send();

Popup blocker issue in Firefox in Ajax call under success

I am having an issue with popup blockers. I want to open a window for my users only after I receive some data from server, in other words I need it on success.
Issue is that popup blocker will stop the window in the success section as it thinks that script is currently executing. I am using jQuery 1.7.1.min and I have tried using (as you can see below)
async:false, but for some reason that doesn't work. The only workaround that I was able to do is to open a fake window and when the response comes back
overwrite the fake window. It works in Chrome but it gives problems in Firefox. Need some help.
function mypopup() {
$j.ajax({
type: 'POST',
url: "/my/phppage",
data: mydata,
async: false,
success: function (response) {
window.open(response, 'Dialogue Message', 'width=650,height=550,left=50,top=50,location=no,status=yes,scrollbars=yes,resizable=yes');
}
});
window.open("openfakewindow", 'Dialogue Message', 'width=650,height=550,left=50,top=50,location=no,status=yes,scrollbars=yes,resizable=yes');
}
The issue is Firefox only allows popups if it is created from a user generated event, for example a click event.
You can get around this by opening a blank window before the Ajax call, keep a reference to it and then set the URL after the ajax call is complete.
Why don't you use a dialogue box that is essentially a element that you identify and then open?
$(document).ready(function () {
$("#divAccountDialog").dialog(
{
modal: true,
autoOpen: false,
width: 700,
buttons: { Cancel: function () { $(this).dialog("close"); } }
}
);
});
someotherfunction () {
$('#divAccountDialog').dialog('open');

Delay page unload after submitting form

Is it possible to delay the moment when the unload method is called on a web page?
I have N pages and each page contains a form. I don't want users to click on a submit button so I simulated a click on the hidden submit button via javascript. This is activated everytime the user change page:
window.onbeforeunload = function() {
document.getElementById('submit_id').click();
}
This doesn't work but if I put an alert after .click ()
window.onbeforeunload = function() {
document.getElementById('submit_id').click();
alert("submitting form");
}
everything works like a charm. This because the alert gives the form the time to actually submit its data; without the alert the page unloads before the form has been submitted and therefore the changes are not saved.
I tried to put a dummy setTimeout after .click()
window.onbeforeunload = function() {
document.getElementById('submit_id').click();
setTimeout(console.log("dummy"), 200);
}
but it didn't work. Any help or feedback on this would be greatly appreciated.
if you use jquery, you can try to save via ajax. and maybe adding async to false, not recomended but could work in your example if save function is really fast.
http://api.jquery.com/jQuery.ajax/
here is how i save:
var $form = $('#formId');
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
error: function (xhr, status, error) {
// error
},
success: function (response) {
// sucess
}
});

Categories