chaplain
chaplain

Reputation: 9

How to get html and javascript in from response

I have the following javascript

$.ajax({
    type: ... url: ... data: ... bla bla...

    success: function( html ) {

        var response = $( html ).filter( '#targetID' ).html();

        $( 'body' ).html( response ).show('slow');

    }
});

It works fine except for loading pages with javascript, the javascript disapears. So how to solve this problem?

Upvotes: 0

Views: 2298

Answers (2)

Nicolini
Nicolini

Reputation: 41

You should use a container inside the body and not place the code directly in the body.

ie. Add on the div tag inside the body which will be the container

<div class="container"></div>

Then on the JS call

 $( '.container' ).html( response ).show('slow');

That way the content loads in the container and not directly in the body which would replace all the content of the page including the JS you have there.

Also when using Ajax calls I believe it makes for a cleaner code to pass the response to other functions to process. That way you will have smaller functions to debug and easier to understand code.

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {

      //Here you pass the response to the other function
      processSuccess(data);
  },
  fail: function(data) {

      //Here you pass the response to the other function
      processFail(data);
  }

});

function processSuccess(response) {
     //Print the response in the console (ie. Firebug console) 
     //if console is available
     if(console) {
        console.log(response);
     }
};

function processFail(response) {
     //Print the response in the console (ie. Firebug console) 
     //if console is available
     if(console) {
        console.log(response);
     }
};

Of course all that inside a namespace would make it even better.

Upvotes: 1

Sangoku
Sangoku

Reputation: 1606

You Mean you are getting the javascript trough the Ajax request.

In that case you need to REALY make sure you have the proper code inside it. Because compability is a bitch with those kind of things. JQuery duos a eval function i think when he loads the result, so the js should load. But it could be that your code haas some aprse errors which are usually ignored on page, but when you use it with eval you will get error in some browsers.

Which broser ar you using?

Try to eval your code after you load it into the designated div.

Upvotes: 0

Related Questions