Javascript function only works once - javascript

I have an inline script on my page as such:
<script type="text/javascript">
var rootPath = '<%= Url.Content("~/") %>';
$(document).ready(function () {
$('#logonStatus').click(function () { loadLoginForm(); });
alert('Document Ready');
});
function loadLoginForm() {
if(!serenity.tools.isStyleSheetLoaded('redmond.css')) {
$('head').append('<%= Url.StyleTag("Redmond/redmond.css", MediaTypes.Screen) %>');
}
if(!serenity.tools.elementExists($('#logonContainer'))) {
$.ajax({
async: false,
cache: false,
datatype: 'html',
success: function (data) { $('body').append(data); },
type: 'GET',
url: '/Membership/LogOn'
});
}
$('#logonContainer').dialog({
modal: true,
hide: 'slide'
});
}
</script>
I also am loading a custom javascript file and the contents of it are as such:
var serenity = new function () {
$(document).ready(function () {
jQuery.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
});
});
this.tools = new function () {
this.isStyleSheetLoaded = function (fileName) {
$(document.styleSheets).each(function () {
if (this.href.toLowerCase().indexOf(fileName) != -1) {
this.isStyleSheetLoaded = true;
return;
}
});
this.isStyleSheetLoaded = false;
}
this.elementExists = function (element) {
this.elementExists = element.length != 0;
}
}
}
The file that is being loaded by the ajax call is simply a div with an table containing input elements. The file does not contain any javascript in it whatsoever.
My problem is that the first time I call isStyleSheetLoaded it works just fine but after the file is loaded and the dialog is shown and closed I click on the link that fires the loadLoginForm function but this time it says isStyleSheetLoaded is not a function. This is showing up in all browsers, so I am 99% sure it is my problem, but I have no idea what it is. Could someone please point me in the right direction?
Thanks in advance.

I think your problem is the following:
you define a function "this.isStyleSheetLoaded = function (fileName)" but in his body you overwride this property "this.isStyleSheetLoaded = true;".
So after your first call of isStyleSheetLoaded the function is overwride with a boolen.
the right way could be:
this.isStyleSheetLoaded = function (fileName) {
$(document.styleSheets).each(function () {
if (this.href.toLowerCase().indexOf(fileName) != -1) {
return true;
}
});
return false;
}

Related

Follow Up For: I have 2 radio buttons and i want to make a different ajax page load into a div element depending on which one is selected

I have the script working on nearly all devices. However, The Issue I am having is that the JavaScript doesn't work on an iPad 2, I need to allow this to work on an iPad 2, Either that or some other version of the script that detects that it is on an iPad 2 and uses a different script because of that.
This is the script I am using currently that doesn't support iPad 2:
<script>
$(document).ready(function() {
let location_one = document.getElementById('location1');
let location_two = document.getElementById('location2');
let getLocationOneData = function () {
$.ajax({
type: 'POST',
url: 'locationData1.php',
success: function(data){
$('#locationoutput').html(data);
}
});
};
let getLocationTwoData = function () {
$.ajax({
type: 'POST',
url: 'locationData2.php',
success: function(data){
$('#locationoutput').html(data);
}
});
};
let getData = function () {
if (location_one.checked) {
getLocationOneData();
} else if (location_two.checked) {
getLocationTwoData();
}
}
location_one.addEventListener('change', function () {
if (this.checked) {
getLocationOneData()
}
});
location_two.addEventListener('change', function () {
if (this.checked) {
getLocationTwoData();
}
});
getData();
setInterval(function () {
getData();
}, 120000); // it will refresh the data every 3 mins
});
</script>

Open window after script execution

Is it possible to open the window after the execution of the script expandNextLevel()?
I'm asking this because I don't want to let the client see the expand/collapse animation but just the treeview collapsed.
This is my code.
<script type="text/javascript">
$(function () {
$(".k-gantt").click(function () {
expandNextLevel();
var windowWidget = $("#window");
windowWidget.data("kendoWindow").open().center();
$.ajax({
type: 'GET',
url: '/Act/load',
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
function expandNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-plus').length;
treeview.expand(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
expandNextLevel();
collapseNextLevel();
}
}
, 200);
};
function collapseNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-minus').length;
treeview.collapse(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
collapseNextLevel();
}
}
, 200);
};
</script>
Regards
try this
$.when(expandNextLevel()).done(function(){
/// show window
});
docs https://api.jquery.com/jquery.when/
I think the fastest way to do something like this is put everything in a hidden div, wich you will then show when you're done with the code execution.
You could also put a visible div with a rotating icon while the code is being executed, and hide it when you show the main content to make the users know something is happening.
EDIT:
I made a slight modification to the expand function, that should let me know when it's done executing the recursion, by adding an index I increment everytime. At the end of the function there is a code that will be executed only when the index is equal to one, wich means the first instance of the function is done executing.
<script type="text/javascript">
$(function () {
$(".k-gantt").click(function () {
expandNextLevel(0);
var windowWidget = $("#window");
windowWidget.data("kendoWindow").open().center();
$.ajax({
type: 'GET',
url: '/Act/load',
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
function expandNextLevel(var i)
{
i++;
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-plus').length;
treeview.expand(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
expandNextLevel(i);
collapseNextLevel();
}
if (i == 1)
{
$.("#maincontent").show();
}
}
, 200);
};
function collapseNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-minus').length;
treeview.collapse(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
collapseNextLevel();
}
}
, 200);
};
</script>
You should put you content inside a div
<div id="maincontent" style="display:none;">
/*your content*/
</div>
I didn't test it but it should work :)
There is a better way to do this with jQuery.when, jQuery.done and promises, but I'm not confident I can give you a working sample since I never used those methods

Get the url of xml with jquery

I have a button that gets the current URL, then that URL will be sought within the XML, this will return a URL1 to redirect.
What's is the problem?
Image of XML
$(document).ready(function () {
$("#leerxml").click(function () {
var urlactual = document.location.href;
$.get("students.xml", {}, function (xml) {
$(xml).find("urldirige").each(function () {
if ($(this).find("url").text() == urlactual) {
//do something
document.location.href = $(this).find("reserva").text();
}
});
});
});
});

how to put an ajax loader before .ready

I need to archive this task.i have seen this type of tasks in various sites.
$(document).ready(function () {
$.ajax // rest of codes goes here
$("").load // rest of codes goes here
});
I need to show a gif before ready the document(DOM).After the ready the DOM it should disappear automatically.The gif should on the middle of the page.Any idea?
JAVASCRIPT
$(document).ready(function () {
//calculater start
$("#step2_6").click(function () {
$("#calculater").load("cal/cal.html");
});
//calculater end
//menu start
$(".container").load("../../view/html/menu.html", function () {
$(".main_menu.nav a").css("opacity", 0.3);
$("#step1").css("opacity", 1);
//new company start
$("#step1_1").on("click", function () {
//new company start setup opening....
$(".load_window").load("../../view/html/Finalsetup.html", function () {
//company file download
$("#downloadLink").click(function () {
var companyname = $("#company_name").val();
$(this).attr("href", +"../../company_info/" + companyname + "/" + companyname + ".json");
$(this).attr("target", "_new");
});
//create the company through ajax...
$("#CreateCompanyButton").click(function (event) {
event.preventDefault();
//adding step1 and step2 forms
var data = $("#companyData").serialize();
var dataTwo = $("#companyDataStepTwo").serialize();
$.ajax({
type: "POST",
url: "../../controller/business_contact_info.php",
data: data + "&" + dataTwo,
beforeSend: function () {
//loading a gif
$(".loader").html("<img src='../../img/loader.gif' />");
},
success: function (response) {
$(".main_menu.nav a").css("opacity", 1);
//remove gif after loaded
$(".loader").html(" ");
//add your infor window operning...
$(".load_window").load("../../view/html/addYourInfo.html", function () {
$("#addThePeople").click(function () {
//hidden add people window is opening...
$("#addPeopleWindow").show();
//select the excel sheet...
$("#excel").change(function () {
//opening table window...
$("#addPeopleWindow").load("../../view/html/tabledata.html", function () {});
});
});
});
}
});
});
//adding scipt to selectors...
$('.selectpicker').selectpicker();
$(".drag").draggable();
$("#previewButton").on("click", function () {
$("#previewSettingsView").show();
});
$("#previewClose").on("click", function () {
$("#previewSettingsView").hide();
});
$("#step_two").hide();
$("#step_three").hide();
$("#step_four").hide();
$("#step_one_button").click(function () {
$("#step_one").hide();
$(".tell_us").css("opacity", "0.4");
$(".contact_info").css("opacity", "*0.2");
$("#step_two").show();
});
$("#step_two_back").click(function () {
$("#step_two").hide();
$("#step_one").show();
});
});
});
});
});
Just put the code into your script, without enclosing $(document).ready(). It will be executed as soon as the <script> tag is parsed by the browser.

Issue with getting value from $.ajax inside a $.when

Hey guys I have the following code:
function runATF(){
var urlatf = '/pcg/ATF/updateATF_window.php';
var tagatf = $("#insider_dialog");
var promise1 = showUrlInDialogATF(urlatf);
var promise2 = sendUpdateATFwindow();
$.when(promise1, promise2).done(function(data1, data2) {
tagatf.html(data1[0]).dialog({
width: '100%',
modal: true
}).dialog('open');
//$('.updaterATF_outerbody').text(data2[0].atfName),
//$('.updaterATF_outerbody').text(data2[0].atfAmount)
//console.log(data2[1]);
alert(data2[0].text(atfName));
alert(data2[0].text(atfAmount));
});
}
The part I need you to look at it the alert(data2[0].text(atfName)); and the alert(data2[0].text(atfAmount)); My problem is I can't seem to get the values?
Let me show you the 2 functions that are ran:
First this one just sends a url and returns....
function showUrlInDialogATF(urlatf)
{
return $.ajax({
url: urlatf
});
}
The second one returns the two data values that are created in a document.ready (I have tested them and they do hold values, it's only when I try and get it into the $.when statement).....
function sendUpdateATFwindow()
{
return $.ajax({
data: {
'atfName': atf_name.val(),
'atfAmount': atf_amount.val()
}
});
}
Let me know if you need anything else, thank you
David
Oh here is the first statement that begins everything:
$(document).ready(function () {
$(".atf-submit").click(function () {
atf_name = $(this).parent().parent().find(".user_table");
atf_amount = $(this).parent().parent().find(".user_atf");
runATF();
});
});
Note: I am using the Jquery UI dialog opener, I already have one open so I am making another one open. I don't know if this will effect anything? I would assume not because the functions and values are different names.
UPDATE:
Okay I want to show the first code that opens the first dialog window up:
$(document).ready(function () {
$("#ATF").click(function () {
runATF();
});
});
function runATF(){
var urlATF = '/pcg/ATF/atf_layout.php';
showUrlInDialogATF(urlATF);
}
function showUrlInDialogATF(urlATF)
{
var tag = $("#dialog-container");
$.ajax({
url: urlATF,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
Than the other code runs - I will re post here:
$(document).ready(function () {
$(".atf-submit").click(function () {
atf_name = $(this).parent().parent().find(".user_table");
atf_amount = $(this).parent().parent().find(".user_atf");
runATFinsider();
});
});
function runATFinsider(){
var urlatfinsider = '/pcg/ATF/updateATF_window.php';
var tagatfinsider = $("#insider_dialog");
var promise1 = showUrlInDialogATFinsider(urlatfinsider);
var promise2 = sendUpdateATFwindow();
$.when(promise1, promise2).done(function(data1, data2) {
tagatfinsider.html(data1[0]).dialog({
width: '100%',
modal: true
}).dialog('open');
//$('.updaterATF_outerbody').text(data2[0].atfName),
//$('.updaterATF_outerbody').text(data2[0].atfAmount)
console.log(data2[1]);
alert(data2[0].text(atfName));
});
}
function showUrlInDialogATFinsider(urlatfinsider)
{
return $.ajax({
url: urlatfinsider
});
}
function sendUpdateATFwindow()
{
return $.ajax({
data: {
'atfName': atf_name.val(),
'atfAmount': atf_amount.val()
}
});
}
Also I try to do a console.log(data2) and it just gives me, [0] = abunch of html? , [1] = success, [2] = object
UPDATE:
Here is an example of what it I should be getting in the data2[0]...
alert(atf_name.val()); = bob
alert(atf_amount.val()); = 0

Categories