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.
Related
I tried to print something using window.print();
It is working, but whenever I click my print button for the second time without reloading the page (which is unnecessary),
the window print will appear again even though I already click on close button.
After the code runs until $('#main').show(); , it goes back to window.print(); again.
And if I tried for the third time, it will reload the window print 3 times and so on.
I'm not sure how to terminate the query after I close the window for the first time.
I do not want the window to be reloaded again.
This is my code;
self.QrCode = ko.observable("../Content/img/qr-code (1).png");
self.GetQrCode = function (obj) {
var ID = obj.Id;
$.ajax({
url: '/QC/GetQrCode',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: { rejectsId: ID },
success: function (rejectsId) {
self.QrCode(rejectsId.QRCode);
self.PrintQrCode();
}
});
}
self.PrintQrCode = function (obj) {
$('#main').hide();
$('#QrCodePrint').show();
$("#test").on("load", function () {
window.print();
$('#QrCodePrint').hide();
$('#main').show();
return false;
});
}
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
}
}
Writing some JavaScript to update some text in a Bootstrap 3 Popover. I'm probably not using Promises right, but I want the text to appear in the popover the first time I click, not when I've clicked it twice.
The Javascript calls a local Proxy written in C#. The JavaScript for the setup of the popover itself looks like this:
$(function () {
$('#session-cookie-showcase').popover({
html: true
});
$('#session-cookie-showcase').on('show.bs.popover', function () {
Promise.resolve(getSessionCookieAsString()).then(function (value) {
$('#session-cookie-showcase').data('bs.popover').config.content = value;
})
})
})
The ajax call looks like this:
async function getSessionCookieAsString(callback) {
return $.ajax({
type: "GET",
url: AppName + '/api/omitted/hentSessionCookieSomTekst',
dataType: "json",
contentType: "application/json",
success: ((result) => function (result) { return result }),
error: ((XMLHttpRequest, textStatus, errorThrown) =>
handleWebserviceCallError(XMLHttpRequest, textStatus, errorThrown, false))
});
}
And finally the C# proxy looks like this:
[HttpGet("hentSessionCookieSomTekst")]
public string HentSessionCookieSomTekst()
{
string userKey = _configuration.GetSection("SessionKeys:User").Value;
if (!string.IsNullOrEmpty(userKey))
{
BrugerObjekt bruger = HttpContext.Session.Get<BrugerObjekt>(userKey);
return JsonConvert.SerializeObject(bruger.ToString('n'));
}
else
{
return JsonConvert.SerializeObject("NULL");
}
}
So to reiterate; The call works. But it only works on the second click of my element, never on the first. Can I somehow make the text load in whenever it is deemed ready instead of having to click again or fix this some other way?
getSessionCookieAsString function is returning a promise itself. can you try below code.
getSessionCookieAsString().done(function (value) {
$('#session-cookie-showcase').data('bs.popover').config.content = value;
});
edited it.
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();
}
}