tags:

views:

99

answers:

2

I'm having trouble using jQuery with child page

parent.html loads child.html like so: ie user clicks

<a href="#" id="n-email">

JQuery

$('a#n-email').click(function() {


    $.ajax({
   type: "GET",
   url: "/scripts/contact.js",
   dataType: "script"
 });

    $('#content').load("child.htm");         

});

contact.js

$(function() {

    alert ("contact js hit");
}

This occasionally works. But i can't work out the logic why it works. I've also tried adding adding a ref to the Jquery on the handler also. I feel like i'm missing a trick here.

Thanks to jake + lucus. I've got the following working. Needs a refactor, but works

$('#n-email').click(function() { var e = this; reset(e);

    var mypage = $('#contentemail').load("email.php"); 

    $.ajax({
          type: "GET",
          url: "/scripts/contact.js",
          dataType: "script",
          success: function(mypage)
          {
              $(document).append(mypage);
          }
        });

    $('#contentemail').show();            

});
+2  A: 

First, you need to put a callback function in the jQuery ajax using the success property. Second, you cant just put javascript en a html element. That just doenst work. You could try using eval. Try this code as a start:

$('a #n-email').click(function() {
    $.ajax({
          type: "GET",
          url: "/scripts/contact.js",
          dataType: "script",
          success: function(value){eval(value)}
        });     
});
Lucas
thank lucas. do you mind explaining how the eval would workMaybe i could be clearer what i'm trying to do. - Parent loads child- child contains a contact form which i needs to have validation etc.
frosty
eval execute javascript from text. In this case that is the text that came from the ajax response.
Lucas
+1  A: 

Using $(document).append(content) will strip out all script tags from content and attempt to evaluate them. So you could go

$('a #n-email').click(function() {
    $.ajax({
          type: "GET",
          url: "/scripts/contact.js",
          dataType: "script",
          success: function(result)
          {
              $(document).append(result);
          }
        });     
});
Jake Scott
thanks jake, very useful comments.
frosty