Is there a way in JavaScript where I can execute some functions only after page is loaded. Other functions should execute only on an event.
The problem is, I have some calculations in my php page and after doing all the calculations, the data is saved in mysql. Now when I come to the edit mode some functions are executing which makes the total field as NaN. I just want the code to take the total field from the db only not from any function. Hope l'm clear.
Fiddle
You can try like this:
Make an AJAX call to the server to get the count from Database when the user clicks on edit mode and avoid getting from the html document.
function JQueryGETAjaxCall(servletPath,callBck){
var path = window.location.origin
var url = path+servletPath;
console.log(url)
$.ajax({
'type':'GET',
'url':url,
'async': true,
'success':function(res){
callBck(res);
},
'error':function(res){
}
});
}
Related
Sorry if this type of question is already been answered.
I am trying to add a page using $("Div").load() inside $(document).ready().
Page is getting loaded but it is not showing anything inside its' variables.
Steps in my code:
Page starts loading
Value come from back-end code (spring java)
Loading a specific page when values are present and show them on page.
If values are null, do not load page.
Jquery version: "2.1.3"
Below is my code:
$(document).ready(
if(condition1){
var var1= data //some json data;
$('#divId').load('url/mypage.jsp');
if(condtition == true){
myFunctionToProcessData(var1);
}
}
)
I have tried ajax call, but its not working.
After completion, I can see my page is loaded and appended in division but not showing on UI and have empty variables.
Please help.
Thank you for your responses. I could not reveal my full code, so made a snippet to give an idea about what i wanted. Issue is fixed now.
Issue was: I wanted to append a JSP on certain condition inside $(document).ready() but the working of $(document).ready() is something like, it ensures executions of methods and conditions written inside it.
Problem was:
Method "myFunctionToProcessData" and "$('#divId').load('url/mypage.jsp');" was called simultaneously , and HTML was not complete at the same time when method called and due to this, my method did not find division to set values and do other validations.
To solve this I have used below approach:
Appended html/jsp page using .load function.
used an ajax method in which i am getting data.
execution steps:
1. Code appended HTML in some time (Using setTimeout function)
2. after execution of all lines in $(document).ready(), ajax function called
3. Now myFunctionToProcessData ca find divisions to set values and proper out put shown on the UI.
code:
$(document).ready(
if(condition1){
var var1= data //some json data;
setTimeout(function() {
$('#divId').load('url/mypage.jsp');
}, 10);
if(condtition == true){
$.ajax({
type : "GET",
contentType : "application/json",
data : "&sid=" + Math.random(),
url : "url", // change to full path of file on server
success : function (data) {
myFunctionToProcessData(var1);
});
}
}
)
This is just a workaround to make sure that myFunctionToProcessData executes only after jsp appended succesfully in it.
now myFunctionToProcessData is executing at the end.
Here's the scenario:
- there is a set of variables
- these variables indicate the statuses of various equipment
- the goal is to display an always-updated status chart
So, I have gotten as far as having a parser in Perl that spits out JavaScript var x = 'y'; type code, and now I'm looking for how to have the HTML or other JavaScript automatically check for updates to this "spit out" code, versus just caching it after the first time.
The closest thing I've seen is to use "setInterval" to have it execute a function, so I went ahead and wrapped the "var" statements in a function with a "setInterval" timer. But will this reliably be always up-to-date, or does it cache the whole function, depending on the browser?
EDIT: I'm not currently using any libraries or anything, and would prefer not to - but I will if I have to.
EDIT2: Finally found what I'm looking for. http://www.philnicholas.com/2009/05/11/reloading-your-javascript-without-reloading-your-page/
Just had to modify the last line to get it to work.
You're already close to the solution. Create a function that makes an ajax call to the 'spit out' you have written in perl.
function getSpitOut() {
$.ajax({
async: true,
type: "GET",
url: "spit_out.pl",
data: "x=8&y=7",
success: function(msg){
// UPDATE CHART
}
});
}
And another function to make the ajax calls at intervals:
$(document).ready(function() {
setInterval(getSpitOut, 60000); // Call getSpitOut every 60s
})
The browser won't cache it because you're updating the chart based on the server side perl script.
Apparently I never closed this.
Slightly modified from: "http://www.philnicholas.com/2009/05/11/reloading-your-javascript-without-reloading-your-page/", I have this:
var docHeadObj = document.getElementsByTagName("head")[0];
var dynamicScript = document.createElement("script");
dynamicScript.type = "text/javascript";
dynamicScript.src = scriptName;
docHeadObj.appendChild(dynamicScript);
i have script that works as follows:
there is main page with 'start' button that initializes javascript function which loads a php page into a div frame, then via setTimeout it calls a 'refresh' function thats supposed to work indefinitelly and refresh the page inside frame
the refreesh timer is in database and is forwarded to java like this:
var min_refresh_time = ;
$min_refresh_time_sec is taken from database earlier in the code
what i wanted to modify is so the refresh min_refresh_time would be taken each time a refresh function is run, to my surprise this worked (or at least i thought so):
var min_refresh_time = ;
(custom sql functions are defined in separate php file included in main.php which is my main page)
unfortunatelly it seems that it 'worked' only due to some strange caching on java part and my pseudo-php code to take value from database is just a hoax - it looks like it is run only initially and then stores output somehow
simplified code of what is done and what i want to do:
function refresh_code(){
refresh_time = <?php Print(sql_result(sql_execute("SELECT value FROM settings WHERE setting='min_refresh_time'", $connection), 0, 0)); ?>;
refresh_time = 5;
alert(refresh_time);
$.post("index.php",{refresh_time:refresh_time_post, account_group: "1"},
function(data)
{
$.ajaxSetup ({
cache: false,
});
$("#frame_1").html(data);
});
setTimeout(function(){refresh_code()}, refresh_time);}
lets say min_refresh_time is 1 in database, i run it, it alerts 1 then 5 each time it self-refreshes, now if i go to database and change 1 to 3 i would want it to alert 3 then 5 obvious, it still does 1 then 5 tho...
i need a way to execute a dummy php file that only takes value from database, then sends it via post back to java and it gets intercepted there, any simple way to do that?
or do i need to use entirely different method for retrieving database value without js...
thx in advance
update:
i actually came back to it and analyzed potential solutions with fresh mind
first of all, i dont think my initial code had chance to work, java cant execute serverside code by itself, i took some of my aax code from other script and reworked it to launch php file that grabs the value from database, then i intercept output data and put into variable
looks like that:
$.ajax({
method: "POST",
url: "retrieve_refresh.php",
data: { retrieve_data: "max"},
cache: false,
timeout: 5000,
async: false,
cache: false,
error: function(){
return true;
},
success: function(msg){
if (parseFloat(msg)){
return false;
}
else {
return true;
}
}
}).done(function(php_output2) {
max_refresh_time = php_output2;
});
retrieve_refresh.php returns only the variable i want but the solution is unelegant to say the least, i havent searched yet but could use a way of sending variables as post back to ajax...
How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php
I have code snippent which is executed on click of a link which is as below
cj_redirecturl="/HomeWork/main/load_course";
utility.xhttprw.data(cj_redirecturl,{data:courseid},function(response){
if(response){
window.location.href=base_url+"main";
///next
utility.xhttprw.data(redirecturl,{data:""},function(response){
if(response){
id=ent;
document.getElementById('content').innerHTML=response;
// Assignemnt module
//Call function from javascript/assignment.js file to display particular assignment (ent:means assignment_id) //
if(con==5)
{
get_assignment_id(ent);
}
if(con==9)
{
get_content_details(ent);
}
} //end of response
},false,false,false,'POST','html',true);
}
},false,false,false,'POST','html');
in above code window.location.href=base_url+"main";redirects the page to its respective page but this stops the execution of the code written just next to it. Now I want this code to be executed as it is been written i.e. firstly the code should take me to the respective "main" page and then code writte after that must execute and give me a required output.
Can someone guide me to achieve this?
window.location.href = base_url + "main"; <- when you load this page, call your code defined at ///next
you will have to add some parameters:
window.location.href=base_url+"main?parameter=true";
The other way would be to load the page with ajax into a div in the html.
Have a look at $.ajax() from jQuery.
please try to write
window.location.href = base_url + "main";
just before the end of if condition or use
setTimeout('window.location.href=base_url+"main"', 2000);
As already been noticed, you cant execute code after you went to another page
What you can do is to create redirector function, that will pass your function in cookie and ,redirect and then eval it on next page. (with another call to that redirector on next page)
But you should be aware of number of issues
1) Packing. It is upon you to decide how you pack cookie.
2) Encription. If you pass non-packed OR non-encrypted cookie the "bad user" can pass some malware code inside that cookie.
3) You should have VERY, VERY good reasons to do it.
This way is too complicated, hard to code, hard to maintain
Much better if you do additional server-side controls, save it somewhere and reload on next page with one more request.
You'll need to wrap the rest of the JS code inside a window.onbeforeunload callback.
See here: Intercept page exit event
You need to use the onBlur event to continue to execute js code before exit from the page.
Example:
function downloadExcel()
{
// Your code...
$('#download_excel_button').hide();
$('#download_spinner').show();
window.location.href = download_page;
window.onblur = function(event)
{
// other event code...
$('#download_spinner').hide();
$('#download_excel_button').show();
}
}