Sync issue with iframe in Chrome and Edge - javascript

the following script is used to load in a IFRAME a web application.
function openCashier(destination) {
postIsAnonymous(function (data) {
if (data.IsAnonymous) {
window.parent.location.replace('<%= ResolveUrl("~/Popup/login") %>');
} else {
stateReset('showUserBtn');
WCore.OpenTab('cashier');
$("#cashierPopup").addClass(destination);
$("#cashierFrame").attr('src', '<%= ResolveUrl(Routing.GetUrl("Root-TPAutologin")) %>?Destinazione=' + destination);
}
});
}
In Firefox everything works fine, while in Edge and Chrome I get error 404. If I try to load the contents of the IFRAME in a separate browser session everything works.
I tried to edit the javascript as follows, fearing an asynchronism problem:
function openCashier(destination) {
setTimeout(function () {
postIsAnonymous(function (data) {
if (data.IsAnonymous) {
window.parent.location.replace('<%= ResolveUrl("~/Popup/login") %>');
} else {
stateReset('showUserBtn');
WCore.OpenTab('cashier');
$("#cashierPopup").addClass(destination);
$("#cashierFrame").attr('src', '<%= ResolveUrl(Routing.GetUrl("Root-TPAutologin")) %>?Destinazione=' + destination);
}
});
}, 1000 * 20);
}
With this trick the problem is solved with very bad performances.
PostIsAnonymous code is the following :
function postIsAnonymous(successFunc) {
$.ajax({
type: "POST",
url: '?checkIsAnonymous=1',
cache: false,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
processData: false,
success: successFunc
});
}
Do you have any suggestions to give me to solve the problem in a more
elegant way? Thank you

I solved the problem with the following code.
function openCashier(destination) {
var dest = destination;
sessionManager.isAnonymous()
.then((data) => {
if (data.IsAnonymous) {
window.parent.location.replace('<%= ResolveUrl("~/Popup/login") %>');
}
else {
stateReset('showUserBtn');
WCore.OpenTab('cashier');
$("#cashierPopup").addClass(dest);
$("#cashierFrame").attr('src', '<%= ResolveUrl(Routing.GetUrl("Root-TPAutologin")) %>?Destinazione=' + dest);
}
})
.catch((err) => {
console.error(err);
});
}
var sessionManager = {
isAnonymous: () => {
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: '?checkIsAnonymous=1',
cache: false,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
processData: false,
success: function (data) {
resolve(data);
},
error: function (data) {
reject(data);
}
});
})
}
}

Related

How can I console "Sucess" present on $.ajax?

How can I show "success" up on Console screen? In a nutshell, I want to show on Console the erros that I forced to happen in a register formulary.
function getRoot() {
var root = "http://" + document.location.hostname + "/login_AMUBA/";
return root;
}
$("#formCadastro").on("submit", function (event) {
event.preventDefault();
var dados = $(this).serialize();
function response() {
return $.ajax({
url: getRoot() + 'controllers/controllerCadastro',
type: 'post',
dataType: 'json',
data: dados,
success: function (response) {
console.log(response);
}
});
}
if (response) {
console.log(success);<--Here
}
});
Finally, the final function (on a php file) should show the error(errors) on console screen, but only "else" works (when it is not commented)
public function validateFinalCad($arrVar)
{
if (count($this->getErro()) > 0) {
$arrResponse = [
"retorno" => "erro",
"erros" => $this->getErro()
];
} else {
/*$this->cadastro->insertCad($arrVar);*/
}
return json_encode($arrResponse);
}

beautifulsoup - how i remove js code in my crawling data?

i use find_all but there is some problem on my data.
i only need text, but js script was copied too
crawled js data is like this.
how can i remove this?
window.__mugFnList__.push(function() { !function($, window) { if (mug.common.isDev()) { console.log("asyncGet funding"); } function asyncGet() { $.ajax({ url: "getSe3FundingView.nhn", dataType:"html", data: { authorNo: "11166748", seriesNo: "368342" }, success: function(resultHtml){ if (mug.common.isDev()) { console.log("asyncGet funding success!!"); } $.trim(resultHtml); $("#__tmp_fundingView").replaceWith(resultHtml); $(window).trigger("viewerFundingLoad"); }, error: function(resp) { console.log(resp); } }); } $(window).load(function() { setTimeout(asyncGet, 1); }); }(jQuery, window); });
window.__mugFnList__.push(function() {
!function($, window) {
if (mug.common.isDev()) {
console.log("asyncGet event");
}
function asyncGet() {
$.ajax({
url: "getEventView.nhn",
dataType:"html",
data: {
volumeNo: "13440747",
memberNo: "11166748"
},
success: function(resultHtml){
if (mug.common.isDev()) {
console.log("asyncGet event success!!");
}
$.trim(resultHtml);
$("#__tmp_eventView").replaceWith(resultHtml);
"") {
try {window.__viewer._resizePan();}catch(e){};
}
$(window).trigger("viewerEventLoad");
},
error: function(resp) {
console.log(resp);
}
});
}
$(window).load(function() {
setTimeout(asyncGet, 1);
});
}(jQuery, window);
});

Jquery/JavaScript - Get active URL, split

Can anyone help me put my three snippets below into one usable script.
1) Get active window URL
2) Strip URL for ID only
3) Concatenate API request to include ID from URL
The below returns my current window URL.
chrome.tabs.query({active: true, currentWindow: true},
function(tabs) {
var tabURL = tabs[0].url;
console.log(tabURL);
});
Example....https://myapi.com/users/PLLFFR6
function test() {
var urlID = tabURL.split("/");
urlID = urlID[urlID.length-1];
}
This splits down https://myapi.com/users/PLLFFR6 and returns only "PLLFFR6"
var authorizationToken = "xxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Address').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
myapiRequest('/users/' + urlID + '?include%5B%5D=contact_methods&include%5B%5D=teams');
Based on this example myapiRequest should =
**/users/PLLFFR6?include%5B%5D=contact_methods&include%5B%5D=teams**
Something like this should work:
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
function apiRequest(endpoint, options) {
return new Promise(function (resolve) {
$.ajax(
$.extend({}, {
type: 'GET',
dataType: 'json',
success: function(data) {
resolve(data)
},
url: 'https://api.website.com/' + endpoint,
headers: {
Authorization: 'Token token='+authToken,
Accept: 'application/vnd.myapi+json;version=2'
}
}, options)
)
})
}
/* example usage */
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return apiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
Note that since you're using chrome.tabs, this will only work as a Chrome extension, not in a browser. You'll also need jQuery loaded (to use $.ajax and $.extend).

External method from an AJAX callback in JavaScript & jQuery

I have a function in JS & jQuery that fires an AJAX call and it has a callback block to let me know when it's finished:
function ajaxCall(url, type, dataType, dataToSend, callback) {
if (dataType == undefined) dataType = "json";
if (dataToSend == undefined) dataToSend = null;
$.ajax({
url: url,
type: type,
dataType: dataType,
contentType: "application/json",
data: dataToSend,
async: true,
success: function (result) {
callback(result);
},
error: function (data, status) {
console.error("Server Error: " + status);
}
});
}
I am accessing it like so, but using external functions like showAjaxLoader() just doesn't work! it says this function is undefined:
function registerUser(data) {
ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) {
// SOME CODE THAT RUNS WHEN IT'S COMPLETE
// External method:
showAjaxLoader(false); // Doesn't work
});
});
function showAjaxLoader(show) {
var loader = $('.ajax-loader');
if (show) {
loader.fadeIn("fast");
} else {
loader.fadeOut("fast");
}
}
What am I doing wrong?
Thanks :)
Worked out some sample. this may be good practice. Try this :
$(document).ready(function() {
$("button").click(function() {registerUser();});
});
var Scallback = function(arg) {
alert("Success :"+arg);
showAjaxLoader(true);
}
var Ecallback = function(arg) {
alert("Err :"+arg);
showAjaxLoader(true);
}
function showAjaxLoader(show) {
var loader = $('.ajax-loader');
if (show) {
loader.fadeIn("fast");
} else {
loader.fadeOut("fast");
}
}
function ajaxCall(url, type, Scallback, Ecallback) {
$.ajax({
url : url,
type : type,
async : true,
success : function(result) {
Scallback(result);
},
error : function(data) {
Ecallback(data)
}
});
}
function registerUser()
{
ajaxCall(pathServiceRegister, "GET", Scallback, Ecallback);
}
Have you tried to do something like:
var that = this;
function registerUser(data) {
ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) {
// SOME CODE THAT RUNS WHEN IT'S COMPLETE
// External method:
that.showAjaxLoader(false);
});
});
Declare your method like this
var obj = {
showAjaxLoader : function(show) {
var loader = $('.ajax-loader');
if (show) {
loader.fadeIn("fast");
} else {
loader.fadeOut("fast");
}
}
}
Then inside ajax, call obj.showAjaxLoader(false); This may work.

get script Jquery issues

im having troubles with getting script from another file in jquery.
i've tried with $.getScript and $.ajax();
how can i include one script like require.js in jquery?
util.js
function getSessionInformation () {
$.ajax({
url: '../controller/controller.php',
type: 'POST',
dataType:'JSON',
data: {
action: 'getInfoCompany'
},
})
.done(function(data) {
try{
return data;
}catch(e){
console.log(e);
}
})
.fail(function() {
console.log("error");
});
}
file.js
$(document).ready(function() {
_getAllUsers();
});
function _getAllUsers()
{
jQuery.ajax({
url: "util.js",
dataType: "script",
cache: true
}).done(function() {
alert("im in");
jQuery.cookie("cookie_name", "value", { expires: 7 });
});
}
Try again, the getScript method is the right tool for this:
function _getAllUsers()
{
jQuery.getScript("util.js", function() {
alert("im in");
jQuery.cookie("cookie_name", "value", { expires: 7 });
});
}
Update:
The reason that you get a HTTP 404 error is that the URL that you are using will look for the script in the same folder as the page. You need a ../ to get out of the view folder and a js to get into the script folder:
jQuery.getScript("../js/util.js", function() {

Categories

Resources