Javascript on loaded page not executed - javascript

// Change the value of the outputText field
function setAjaxOutput(){
if(httpObject.readyState == 4){
document.getElementById('maincontent').innerHTML = httpObject.responseText;
}
}
i try to load a page which contain this script
<script type="text/javascript">
$(document).ready(function() {
alert('dfd');
$("#formAddUser").validate({
rules: {
userImage: {
required: true,
accept: "png|jpg|gif|jpeg"
}
}
});
});
</script>
<div class="content-box">
<div class="content-box-header">
........................
Why javascript on loaded page not executed? Thank you.

Your problem is that innerHTML doesn't execute scripts in the HTML fragment. When you say 'element.innerHTML = htmlfragment;', it just adds the tags and renders the HTML. Script tags are not rendered as part of the HTML by the browser, so they are ignored.
You need to use jQuery.load() instead of jQuery.ajax() like this:
$('#maincontent').load('yourscript.php');
jQuery.load(); has code inside that first takes those tags out, then adds the remaining HTML via innerHTML, then runs the tags separately. You can see the code that does this here at around line 211. From the docs:
When calling .load() using a URL without a suffixed selector
expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is called with a selector expression appended to the URL,
however, the scripts are stripped out prior to the DOM being updated,
and thus are not executed.

first try:
<script type="text/javascript">
alert('dfd');
</script>
and then try
<script type="text/javascript">
$(document).ready(function() {
alert('dfd');
});
</script>
and paste the results.

I believe your form comes with ajax. so it is better if you can turn your validation into a function, and call it inside ajax loaded content.

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

Executing script written inside the div when the div dynamically loads on to the page

I have a div which looks like
<div>
//Useful content
<script type="text/javascript">
function(){
//some useful code
}
</script>
</div>
Now am getting this div as a response of an Ajax call and appending that into body. Now when the gets appended to body, the function inside the script tag should get executed. But not.. what is the problem here?
You should be using document.createElement("script"); if you need to insert some script dynamically. This is recommended approach.
Anyway, following code is working just fine for me:
var str = "<script>alert('Hi!');</scr"+"ipt>";
$('#container').append($(str)[0]);
Make sure you escape you script properly.
Your function is not executing because it is not being called.
You should use a self-executing function that will just run as soon as it's loaded:
(function() {
alert('hello world!');
})();

javascript in innerhtml not working

For example:
<html>
<div id="media">123</div>
Click
<script type="text/javascript">
function fun() {
document.getElementById("media").innerHTML = '<script type="text/javascript">alert("working");<\/script>';
}
</script>
</html>
After you click the alert does not show.
alert("working"); is just an example. I want it to finish one job other javascript
. I have a job to be processed through ajax should have used innerHTML
The HTML spec specifies that script tags inserted using innerHTML should not be executed. This is a security consideration.
There are still ways to do this if you are determined, such as adding it to img handlers or creating a script element, inserting it into the DOM and changing its text property. I will not elaborate on these, since doing this is generally considered somewhat sketchy. If you are not trying to inject script, you should include the script element in the page source.
<script type="text/javascript">
function fun() {
alert("working");
}
</script>
<div id="media">123</div> Click
Your JS function should be like this.
function fun() {
alert("working");
}

executing javascript function from HTML without event

I wish to call a javascript function from an HTML page and I do not want it dependent on any event. The function is in a separate .js file since I wish to use it from many web pages. I am also passing variables to it. I've tried this:
HTML:
<script type="text/javascript" src="fp_footer2.js">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
The function in fp_footer2.js:
function footerFunction(path, file) {
document.write("<a href=" + path + "/" + file + " target='_blank'>Link to the original web page for this assignment.</a>");
return;
}
(I have also tried putting the fp_footer2.js file reference in the header, to no avail. I'm not sure if I can put it 'inline' like I did in this example. If not, please let me know.
PS: I know I can do this with a simple 'a href=""' in the HTML itself. I wanted to see if this could work, for my own curiosity.
If a <script> has a src, then the external script replaces the inline script.
You need to use two script elements.
The strings you pass to the function also need to be actual strings and not undefined variables (or properties of undefined variables). String literals must be quoted.
<script src="fp_footer2.js"></script>
<script>
footerFunction("1_basic_web_page_with_links", "1bwpwl.html");
</script>
JavaScript will run while your page is being rendered. A common mistake is to execute a script that tries to access an element further down the page. This fails because the element isn't there when the script runs.
So includes in the <head> will run before any DOM content is available.
If your scripts are dependent on the existence of DOM elements (like a footer!) try to put the script includes after the DOM element. A better solution is to use the document ready event ($(document).ready() in jQuery). Or window.onload.
The difference between documen ready and window onload is that document ready will fire when the DOM has been rendered; so all initial DOM elements will be available. Where as window onload fires after all resources have loaded, like images. window onload is useful if you're doing things with those images. Usually document ready is the right one.
Maybe I misunderstand your question, but you should be able to do something like this:
<script type="text/javascript" src="fp_footer2.js"></script>
<script type="text/javascript">
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
</script>
Have you tried calling it from a document.ready?
<script type="text/javascript">
$(document).ready(function() {
footerFunction(1_basic_web_page_with_links, 1bwpwl.html);
});
</script>

Execute JavaScript code at the end when the HTML has been loaded

I want to execute a function at the end when the HTML has been loaded. I tried it with onload without success. I also tried it with ready, but it still doesn’t work. Here is my code. This is again placed in the header:
<script type="text/javascript">
$(document).ready(function() {
$('#infowindow_content').html('test');
});
</script>
The div is also set by an external JavaScript file. Content:
window.onload = initialize;
function initialize() {
document.getElementById('infowindow_content').innerHTML = 'testa';
}
It is included the following way before the closing body tag:
<script type="text/javascript" src="../lib/functions.js"></script>
I tried to place the above code before the closing body tag, but currently I have no idea why this doesn't work (the content isn't changed by my JavaScript code). If I execute it on the console afterwards everything works fine.
Solution:
I set a configuration parameter (language) in the HTML file. In the JavaScript file I ask for this value and depending on the value I define another content. Sometimes it could be so simple ...
Try this:
setTimeout(function() {
$(document).ready(function() {
$('#infowindow_content').html('test');
});
}, 20);
I don't know the jQuery equivalent but try the native JS.
Since the <body> has the most HTML & loads after <head>...
document.body.onload=function(){
yourFunction(args)
}
<body onload="yourFunction(args)">...</body>
Or maybe the window object, since it's the root of every webpage DOM...
window.onload=function(){
yourFunction(args)
}
Always place DOM manipulating code directly before your </body> tag. JavaScript in the header should only be called to libraries, such as jQuery.

Categories

Resources