Hi how do i go about loading up my javascript files after an ajax call has been made, reason being it seems once i click submit, some javascript functions do not end up working. I tried using "$getscript" however it was a bit buggy especially in google chrome? This is what my call looks like;
function InsertStatus() {
var fStatus1 = document.getElementById('<%=txtStatus.ClientID %>').value;
$.ajax({
type: "POST",
url: "WebServices/UserList.asmx/InsertUserStatus",
data: "{ 'fStatus': '" + fStatus1 + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d == "Successful") {
$("#col-3").load(location.href + " #col-3>*", "");
$.getScript('scripts/script.js', function () {
});
}
else {
alert("its false");
$.getScript('scripts/script.js', function () {
});
}
}
});
};
Replace $.getScript('scripts/script.js', function () {});
With:
$.ajax({
dataType: 'script',
url: 'scripts/script.js',
crossDomain:true,
success: function(response)
{
//Whatever
}
});
Related
I'm sure this is going to be something really simple, but I am having a problem when calling a function which needs to do various different function calls via ajax to a .net code behind and I want to show a loader over the page until everything has finished, but its not happening.
function expand(ID, user) {
$('.loadingBlackSml, .loadingSml').fadeIn(1000);
checkSession();
expand2(ID, user);
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
Which calls
function checkSession() {
return $.ajax({
type: "POST",
url: "/Test.aspx/checkForSession",
//data: "{}",
data: "{'idleTime':'" + clickedDT + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (sessionCheck) {
sessionActive = JSON.stringify(sessionCheck.d);
}
}).done(function () {
//if session comes back as dead, redirect to restart session
if (sessionActive == "\"false\"") {
var url = "/Error.aspx?RefreshNeeded=true&page=" + window.location.pathname;
$(location).attr('href', url);
}
//if page has gone past timeout length, try and reload it
else if (sessionActive == "\"timeout\"") {
var urlTO = window.location.pathname;
$(location).attr('href', urlTO);
}
});
}
and
function expand2(ID, user) {
return $.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '/Test.aspx/markExpanded',
data: "{'ID':'" + ID + "', 'user':'" + user + "'}",
async: false,
success: function (response) {
},
error: function ()
{ console.log('there is some error'); }
}).done(function () {
});
}
But the loading overlays are disappearing before it is finishing doing what its doing? I've seen something about using $.when for my calls but I'm not sure how to get this working properly?
Any advice would be great. Thanks
Try to hide loading in expand2 or checkSession function on finish request. Like this
... .done(function () {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
});
So loader will be hidden after everything will have finished.
To be sure that everything is over, you can set "flag". For example check = 2. And do
check--; check||$('.loadingBlackSml, .loadingSml').fadeOut(1000);
edited 10.04.17
Example with flag (check) for requests
var check = 0; // count pending requests
function expand(ID, user) {
$('.loadingBlackSml, .loadingSml').fadeIn(1000);
count = 2;
checkSession();
expand2(ID, user);
}
function checkSession() {
return $.ajax({
type: "POST",
url: "/Test.aspx/checkForSession",
//data: "{}",
data: "{'idleTime':'" + clickedDT + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (sessionCheck) {
sessionActive = JSON.stringify(sessionCheck.d);
}
}).done(function () {
//if session comes back as dead, redirect to restart session
if (sessionActive == "\"false\"") {
var url = "/Error.aspx?RefreshNeeded=true&page=" + window.location.pathname;
$(location).attr('href', url);
}
//if page has gone past timeout length, try and reload it
else if (sessionActive == "\"timeout\"") {
var urlTO = window.location.pathname;
$(location).attr('href', urlTO);
}
count--;
if (count === 0) { // check. are all requests finished
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
});
}
function expand2(ID, user) {
return $.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '/Test.aspx/markExpanded',
data: "{'ID':'" + ID + "', 'user':'" + user + "'}",
async: false,
success: function (response) {
},
error: function ()
{ console.log('there is some error'); }
}).done(function () {
count--;
if (count === 0) {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
});
}
Of course, you can move
count--;
if (count === 0) {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
to separate function
I made 3 navigation navbarheader.html, navbar.html and sidebar.html.Only navbarheader.html is loading but others is not loading. if I remove navbarheader.html navbar.html is loading.
<script type="text/javascript">
// let $ = requirejs('./jquery.min.js');
//mainWindow.$ = $;
$(document).ready(function () {
var navbarheaderData = localStorage.getItem('navbarheaderStorage');
if (navbarheaderData) {
$('#navbarheader1').html(navbarheaderData);
} else {
$.ajax({
url: 'navbarheader.html',
dataType: 'text',
success: function (data) {
localStorage.setItem('navbarheaderStorage', data);
$('#navbarheader1').html(data);
var navbarData = localStorage.getItem('navbarStorage');
if (navbarData) {
$('#navbar1').html(navbarData);
} else {
$.ajax({
url: 'navbar.html',
dataType: 'text',
success: function (data) {
localStorage.setItem('navbarStorage', data);
$('#navbar1').html(data);
var sidebarData = localStorage.getItem('sidebarStorage');
if (sidebarData) {
$('#sidebar1').html(sidebarData);
} else {
$.ajax({
url: 'sidebar.html',
dataType: 'text',
success: function (data) {
localStorage.setItem('sidebarStorage', data);
$('#sidebar1').html(data);
}
});
}
}
});
}
}
});
}
});
</script>
That's because you are using ajax requests, which stands for Asynchronous JavaScript and XML, but can be used with other datatypes (like text and therefore json), so the lines where you retrieve navbarheaderData, navbarData, and sidebarData are being executed immediately after you launch the requests, which would explain why only the first one would load (because there's only time for the first one to get a response before you start rendering the data).
What you really want is
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'navbarheader.html',
dataType: 'text',
success: function (data) {
localStorage.setItem('navbarheaderStorage', data);
//console.log(localStorage.getItem('navbarheaderStorage'));
var navbarheaderData = localStorage.getItem('navbarheaderStorage');
$('#navbarheader1').html(navbarheaderData);
}
});
$.ajax({
url: 'navbar.html',
dataType: 'text',
success: function (data) {
localStorage.setItem('navbarStorage', data);
//console.log(localStorage.getItem('navbarStorage'));
var navbarData = localStorage.getItem('navbarStorage');
$('#navbar1').html(navbarData);
}
});
$.ajax({
url: 'sidebar.html',
dataType: 'text',
success: function (data) {
localStorage.setItem('sidebarStorage', data);
//console.log(localStorage.getItem('sidebarStorage'));
var sidebarData = localStorage.getItem('sidebarStorage');
$('#sidebar1').html(sidebarData);
}
});
});
</script>
which could be simplified into the following if you don't need to use local storage.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'navbarheader.html',
dataType: 'text',
success: function (data) {
$('#navbarheader1').html(data);
}
});
$.ajax({
url: 'navbar.html',
dataType: 'text',
success: function (data) {
$('#navbar1').html(data);
}
});
$.ajax({
url: 'sidebar.html',
dataType: 'text',
success: function (data) {
$('#sidebar1').html(data);
}
});
});
</script>
#Penguen replied and changed their above code.
I see that you don't want to send an ajax request unless you need to, which is functioning as some sort of weird caching mechanism. In this case the way you have written this, we only had navbarHeaderData cached and not the rest, then the page would fail to render properly. The following way not only protects against what I said, but is also faster than if the rewritten method works as if you were loading this for the first time and didn't have this cached, then the ajax requests would be sent out almost at the same time, rather than one by one.
<script type="text/javascript">
// let $ = requirejs('./jquery.min.js');
//mainWindow.$ = $;
$(document).ready(function () {
var navbarheaderData = localStorage.getItem('navbarheaderStorage');
if (navbarheaderData) {
$('#navbarheader1').html(navbarheaderData);
} else {
$.ajax({
url: 'navbarheader.html',
dataType: 'text',
success: function (data) {
localStorage.setItem('navbarheaderStorage', data);
$('#navbarheader1').html(data);
}
});
}
var navbarData = localStorage.getItem('navbarStorage');
if (navbarData) {
$('#navbar1').html(navbarData);
} else {
$.ajax({
url: 'navbar.html',
dataType: 'text',
success: function (data) {
localStorage.setItem('navbarStorage', data);
$('#navbar1').html(data);
}
});
}
var sidebarData = localStorage.getItem('sidebarStorage');
if (sidebarData) {
$('#sidebar1').html(sidebarData);
} else {
$.ajax({
url: 'sidebar.html',
dataType: 'text',
success: function (data) {
localStorage.setItem('sidebarStorage', data);
$('#sidebar1').html(data);
}
});
}
});
</script>
From what I see, I see 3 templates being fetched by making AJAX calls and then you are caching the template in your local storage and then use that to render the 3 sections of your web page.
Here is what you are doing it wrong. The render part of the code is written all together in the window.load and does not care about whether the AJAX call is complete or not. As your calls are asynchronous the code will not wait until the response template is fetched.
What you can do instead is have a common render function which each ajax call success method can call.
You are suffering from asynchronous issues, you should do the work inside each request. I dont think its related to local storage.
<script type="text/javascript">
$(document).ready(function () {
var navbarheaderData = localStorage.getItem('navbarheaderStorage');
if (navbarheaderData) {
$('#navbar1').html(data);
} else {
$.ajax({
url: 'navbarheader.html',
dataType: 'text',
success: function (data) {
$('#navbar1').html(data);
}
});
}
.... and so on...
});
I am new with jquery. I want to insert all the list items of ul. I tried the following but its not working can someone please guide me whats wrong with the code as i did "async:false" but it still not working
$('#sortable li').each(function () {
items += $(this).text();
insertCustomBCFields($(this).text(), plu);
});
And insertCustomBCFields ftn is below
function insertCustomBCFields(field, plu) {
alert(field + plu);
$.ajax({
type: "POST",
url: 'ProductDefinition.aspx/insertBCCustomFields',
data: "{'field':'" + field + "', 'plu':'" + plu + "'}",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data) {
alert("Success");
},
failure: function (response) {
alert("Insert Failed!");
}
});
}
Making a ajax call with async: false, will make it synchronous call . this option should be set to true to make a asynchronous call async: false, unless a synchronous call is necessary.
I can see that your making call to the ajax function each time a li is found in your DOM structure(now thats very bad in terms of performance), well thats not so good, instead you can make ajax call once all the items are iterated.
something like this
var arr="";
var index=0;
$('#sortable li').each(function () {
items += $(this).text();
arr+="{field"+index+":" + field + , "plu"+index+":" + plu + "}";
});
insertCustomBCFields(arr);
Similarly change the ajax call as well
function insertCustomBCFields(arr) {
alert(field + plu);
$.ajax({
type: "POST",
url: 'ProductDefinition.aspx/insertBCCustomFields',
data: {'arr':arr},
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data) {
alert("Success");
},
failure: function (response) {
alert("Insert Failed!");
}
});
}
Happy coding :)
My code looks like this. The problem is, PHP side does it job and returns right value. But ajax doesn't execute things inside success: function. What am I missing?
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
$(this).removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" + $(this).data("id") + "]").toggleClass("SelectedDiv");
}
}
});
return false;
});
Try to cache $(this) before ajax call
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
thisElem=$(this),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
thisElem.removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" +thisElem.data("id")+ "]").toggleClass("SelectedDiv");
return false;
}
}
});
});
In the following JavaScript code I repeatedly make AJAX calls to my FastCGI module to query some values. At some point the code terminates when the data variable for the div2 case is not 0 but contains the value that should go into div1 while the div1 displays the value that was supposed to go into div2.
I am using the Chromium Browser (14.0.835.202 (Developer Build 103287 Linux) Ubuntu 10.10) but it also happens with FireFox. I also tried using the XMLHttpRequest object alone and I got the same results.
How can this be and how can this be solved?
function TimerEvent() {
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=s#SYSDATETIME",
success: function(data) {
document.getElementById("div1").innerHTML = data;
}
});
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=#LOGINSTATE",
success: function(data) {
document.getElementById("div2").innerHTML = data;
if (data == "0")
setTimeout("TimerEvent()", 50);
}
});
}
Maybe try have them sequential:
function TimerEvent() {
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=s#SYSDATETIME",
success: function(data) {
document.getElementById("div1").innerHTML = data;
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=#LOGINSTATE",
success: function(data) {
document.getElementById("div2").innerHTML = data;
if (data == "0")
setTimeout("TimerEvent()", 50);
}
});
}
});
}
If your requirements allows, try this:
function TimerEvent() {
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=s#SYSDATETIME",
success: function(data) {
document.getElementById("div1").innerHTML = data;
$.ajax({
url: "/cgi-bin/wvvar.cgi",
type: "POST",
data: "cmd=get&varname=#LOGINSTATE",
success: function(data) {
document.getElementById("div2").innerHTML = data;
if (data == "0")
setTimeout("TimerEvent()", 50);
}
});
}
});
}
Try to execute the calls synchronously by adding the async=false option.