Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove ajax loaded content and script

I dont know this may be duplicate but,

I use ajax in my website, now in response to that call i send some html and script.

Then I replace that data with some of my element exist in page.

Now, I want to make second ajax call so I have removed html content from loaded div. Then again ajax call return some other html code and script. But Some times it is conflict between previous script and newly arrived script.

EX. 1st response I replace html and script with some element: $('.ma_right_main').html(response.data);

then before 2nd call I remove content: $('.ma_right_main').html('');

2nd response I replace html and script with some element: $('.ma_right_main').html(response.data);

but after replace it 2nd time script returned from first time still there in execution. I want to remove it just like how I can remove html content.

like image 237
Parixit Avatar asked Jul 20 '12 09:07

Parixit


2 Answers

I don't think once a browser has loaded a script that it can be removed (this doesn't mean you can't remove it from the dom, but it would still exist.) For example if you had a script with variable x, load the page so the script gets loaded, remove the script from the dom, x I think would still be defined.

There are ways around this though, if each dynamically loaded script was its own object, when "unloading" you could set the object to null. This is a solution I came across a while back when looking for a similar solution.

Found the reference I was referring to: https://stackoverflow.com/a/1346903/1475461

like image 77
Jon Taylor Avatar answered Sep 22 '22 10:09

Jon Taylor


The scripts aren't naturally executed at all. (Setting .innerHTML will not execute scripts inside the HTML).

jQuery manually finds all the script elements in the html, removes them and evaluates them. So if you are using .html and don't want the scripts to execute, do not include scripts in the html.

And you cannot deactivate scripts, so you need to refactor your website with this in mind. Don't include new code in responses if they can conflict with previous ones. Use generic code that is always loaded.

like image 36
Esailija Avatar answered Sep 22 '22 10:09

Esailija