Rectangle 27 49

You are loading an entire HTML page into your div, including the html, head and body tags. What happens if you do the load and just have the opening script, closing script, and JavaScript code in the HTML that you load?

Here is the driver page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>jQuery Load of Script</title>
        <script type="text/javascript" src="http://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("jquery", "1.3.2");
        </script>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#myButton").click(function() {
                    $("#myDiv").load("trackingCode.html");
                });
             });
         </script>
    </head>
    <body>
        <button id="myButton">Click Me</button>
        <div id="myDiv"></div>
    </body>
</html>

Here is the contents of trackingCode.html:

<script type="text/javascript">
    alert("Outside the jQuery ready");
    $(function() {
        alert("Inside the jQuery ready");
    });
 </script>

This works for me in Safari 4.

Update: Added DOCTYPE and html namespace to match the code on my test environment. Tested with Firefox 3.6.13 and example code works.

Got it, thanks Tony! Removing the <html>, <head> and <body> tags seemed to do the trick.

i was wandering whether i should do a seperate ajax call getJson() because i heard of this.. But if it works like that it is ok!! I would call the same queries twice otherwise

Your code is not actually working in FF (IE8 - working fine). Is there a way to make this work in all the browsers? Thanks

@Maxim Galushka I still had these files in my personal workstation. Without modification, they produced the correct behavior. I am using Firefox 3.6.13 on Windows 7.

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari
Rectangle 27 49

You are loading an entire HTML page into your div, including the html, head and body tags. What happens if you do the load and just have the opening script, closing script, and JavaScript code in the HTML that you load?

Here is the driver page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>jQuery Load of Script</title>
        <script type="text/javascript" src="http://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("jquery", "1.3.2");
        </script>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#myButton").click(function() {
                    $("#myDiv").load("trackingCode.html");
                });
             });
         </script>
    </head>
    <body>
        <button id="myButton">Click Me</button>
        <div id="myDiv"></div>
    </body>
</html>

Here is the contents of trackingCode.html:

<script type="text/javascript">
    alert("Outside the jQuery ready");
    $(function() {
        alert("Inside the jQuery ready");
    });
 </script>

This works for me in Safari 4.

Update: Added DOCTYPE and html namespace to match the code on my test environment. Tested with Firefox 3.6.13 and example code works.

Got it, thanks Tony! Removing the <html>, <head> and <body> tags seemed to do the trick.

i was wandering whether i should do a seperate ajax call getJson() because i heard of this.. But if it works like that it is ok!! I would call the same queries twice otherwise

Your code is not actually working in FF (IE8 - working fine). Is there a way to make this work in all the browsers? Thanks

@Maxim Galushka I still had these files in my personal workstation. Without modification, they produced the correct behavior. I am using Firefox 3.6.13 on Windows 7.

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari
Rectangle 27 33

$("#images").load(location.href+" #images",function(){
    $.getScript("js/productHelper.js"); 
});

really is $.getScript() good solution in this problem ;) +1

This did the trick for me. Here is an example that you can try: var frmAcademicCalendar = "frmAcademicCalendar.aspx" if (window.location.href.toLowerCase().indexOf(frmAcademicCalendar.toLowerCase()) >= 0) { $("#IncludeCMSContent").load("example.com #externalContent",function() { $.getScript("example.js"); }); }

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari
Rectangle 27 33

$("#images").load(location.href+" #images",function(){
    $.getScript("js/productHelper.js"); 
});

really is $.getScript() good solution in this problem ;) +1

This did the trick for me. Here is an example that you can try: var frmAcademicCalendar = "frmAcademicCalendar.aspx" if (window.location.href.toLowerCase().indexOf(frmAcademicCalendar.toLowerCase()) >= 0) { $("#IncludeCMSContent").load("example.com #externalContent",function() { $.getScript("example.js"); }); }

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari
Rectangle 27 18

A other version of John Pick's solution just before, this works fine for me :

jQuery.ajax({
   ....
   success: function(data, textStatus, jqXHR) {
       jQuery(selecteur).html(jqXHR.responseText);
       var reponse = jQuery(jqXHR.responseText);
       var reponseScript = reponse.filter("script");
       jQuery.each(reponseScript, function(idx, val) { eval(val.text); } );
   }
   ...
});

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari
Rectangle 27 18

A other version of John Pick's solution just before, this works fine for me :

jQuery.ajax({
   ....
   success: function(data, textStatus, jqXHR) {
       jQuery(selecteur).html(jqXHR.responseText);
       var reponse = jQuery(jqXHR.responseText);
       var reponseScript = reponse.filter("script");
       jQuery.each(reponseScript, function(idx, val) { eval(val.text); } );
   }
   ...
});

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari
Rectangle 27 14

onclick="return confirm('Are you sure?');"

funny that if constructs are suggested in all posts below by developers with some experience.. and even more funny I'm learning from them :)

How can I execute Javascript before a JSF action is pe...

javascript jsf
Rectangle 27 14

onclick="return confirm('Are you sure?');"

funny that if constructs are suggested in all posts below by developers with some experience.. and even more funny I'm learning from them :)

How can I execute Javascript before a JSF action is pe...

javascript jsf
Rectangle 27 14

Add layout: false option to the render block:

def pupil_leads
   # some code here
  respond_to do |f|
    f.js { render layout: false, content_type: 'text/javascript' }
    f.html
  end
end
xhr
.erb.html
.slim

Thank you. Can you possibly give a short explanation as to why this is needed? Just for reference.

Thanks so much, I was going totally crazy with this. One of those "wish I had asked sooner and saved a dozen hours" ones. Thanks again.

for debug async action use Chrome/Network response tab, here you always can see whats wrong with your server response.

Also keep in mind, a single error in your js and all may fail silently - even an initial console.log statement on the first line. Start with only a console.log statement in your js file, then slowly add pieces back until the console.log statement doesn't appear - which means there is an untracable (in rails) bug somewhere in the latest code you pasted back.

jquery - js.erb not executing javascript but is processed rails - Stac...

javascript jquery ruby-on-rails ruby
Rectangle 27 12

I realize this is somewhat of an older post, but for anyone that comes to this page looking for a similar solution...

jQuery.getScript( url, [ success(data, textStatus) ] )
$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari
Rectangle 27 12

I realize this is somewhat of an older post, but for anyone that comes to this page looking for a similar solution...

jQuery.getScript( url, [ success(data, textStatus) ] )
$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari
Rectangle 27 7

<h:commandButton title="#{bundle.NewPatient}" action="#{identifController.prepareCreate}"  
                                             id="newibutton" 
                                             onclick="if(confirm('#{bundle.NewPatient}?'))return true; else return false;" 
                                             value="#{bundle.NewPatient}"/>

That can be simplified as onclick="return confirm('Are you sure?')". It's unnecessary to check a boolean value to return a boolean value. Just return it directly.

Is there an easy way in Primefaces to implement the above using <p:commandLink.../> instead?

How can I execute Javascript before a JSF action is pe...

javascript jsf
Rectangle 27 7

<h:commandLink id="myCommandLink" action="#{myPageCode.doDelete}">
    <h:outputText value="#{msgs.deleteText}" />
</h:commandLink>
<script type="text/javascript">
if (document.getElementById) {
    var commandLink = document.getElementById('<c:out value="${myPageCode.myCommandLinkClientId}" />');
    if (commandLink && commandLink.onclick) {
        var commandLinkOnclick = commandLink.onclick;
        commandLink.onclick = function() {
            var result = confirm('Do you really want to <c:out value="${msgs.deleteText}" />?');
            if (result) {
                return commandLinkOnclick();
            }
            return false;
        }
    }
}
</script>

Other Javascript actions (like validating form input etc) could be performed by replacing the call to confirm() with a call to another function.

How can I execute Javascript before a JSF action is pe...

javascript jsf
Rectangle 27 7

<h:commandLink id="myCommandLink" action="#{myPageCode.doDelete}">
    <h:outputText value="#{msgs.deleteText}" />
</h:commandLink>
<script type="text/javascript">
if (document.getElementById) {
    var commandLink = document.getElementById('<c:out value="${myPageCode.myCommandLinkClientId}" />');
    if (commandLink && commandLink.onclick) {
        var commandLinkOnclick = commandLink.onclick;
        commandLink.onclick = function() {
            var result = confirm('Do you really want to <c:out value="${msgs.deleteText}" />?');
            if (result) {
                return commandLinkOnclick();
            }
            return false;
        }
    }
}
</script>

Other Javascript actions (like validating form input etc) could be performed by replacing the call to confirm() with a call to another function.

How can I execute Javascript before a JSF action is pe...

javascript jsf
Rectangle 27 7

<h:commandButton title="#{bundle.NewPatient}" action="#{identifController.prepareCreate}"  
                                             id="newibutton" 
                                             onclick="if(confirm('#{bundle.NewPatient}?'))return true; else return false;" 
                                             value="#{bundle.NewPatient}"/>

That can be simplified as onclick="return confirm('Are you sure?')". It's unnecessary to check a boolean value to return a boolean value. Just return it directly.

Is there an easy way in Primefaces to implement the above using <p:commandLink.../> instead?

How can I execute Javascript before a JSF action is pe...

javascript jsf
Rectangle 27 7

Lee's answer already adequately addresses the case of HTML responses - scripts embedded in these are not in fact executed automatically unless you add the HTML to the DOM, contrary to the erroneous documentation you quoted.

That leaves the other case asked about in your question title - preventing script responses from being executed automatically when received. You can do this easily using the dataType setting.

$.ajax('myscript.js', {
    dataType: 'text',
    success: function (response) {
        // Do something with the response
    }
})

Setting dataType to 'text' will cause jQuery to disregard the Content-Type header returned from the server and treat the response like plain text, thus preventing the default behaviour for JavaScript responses (which is to execute them). From the (recently corrected) docs:

The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.

If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.

prevent jquery ajax to execute javascript from script or html response...

javascript html ajax jquery
Rectangle 27 6

This doesn't seem to work if you're loading the HTML field into a dynamically created element.

$('body').append('<div id="loader"></div>');
$('#loader').load('htmlwithscript.htm');

Anyone have come across this?

I had to load the html, then in the callback, use $.getScript to get the javascript.

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari
Rectangle 27 6

This doesn't seem to work if you're loading the HTML field into a dynamically created element.

$('body').append('<div id="loader"></div>');
$('#loader').load('htmlwithscript.htm');

Anyone have come across this?

I had to load the html, then in the callback, use $.getScript to get the javascript.

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari
Rectangle 27 24

This is a poor example. Consider the following:

var a = (function(){
    var ret = {};
    ret.test = "123";
    function imPrivate() { /* ... */ }
    ret.public = function() { imPrivate(); }
    return ret;
})();

a will contain the varible test and the function public, however you can not access imPrivate. This is the common way to handle public vs private variables;

Awkward way of executing JavaScript code - Stack Overflow

javascript
Rectangle 27 2

I have try to make one jquery plugin for html loading function. Please refer the following link.

ajax - jQuery .load() call doesn't execute JavaScript in loaded HTML f...

jquery ajax safari