Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload javascript file after an AJAX request

Tags:

After the request, the new elements created are not recognized by the event handlers in my jQuery code.

Is there a way to reload the file to re-register these events?

like image 546
Michaël Avatar asked Dec 21 '11 18:12

Michaël


People also ask

How do you reload the same page after AJAX success?

You can use the location. reload() method to reload or refresh an entire web page or just the content inside an element. The . reload() method can be triggered either explicitly (with a button click) or automatically.

How do you refresh a JavaScript script?

You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button.

Do AJAX requests reload the page?

AJAX is a developer's dream, because you can: Update a web page without reloading the page. Request data from a server - after the page has loaded. Receive data from a server - after the page has loaded.

What does AJAX reload do?

Description. In an environment where the data shown in the table can be updated at the server-side, it is often useful to be able to reload the table, showing the latest data. This method provides exactly that ability, making an Ajax request to the already defined URL (use ajax. url() if you need to alter the URL).


1 Answers

I'm assuming that you mean that events you've registered for elements that have been replaced by with the results of your ajax requests aren't firing?

Use .live() (see http://api.jquery.com/live/) to register the events against elements that the match the selector (including the new DOM elements created from the results of the ajax), rather than the results of the selector when the event handlers were first, which will be destroyed when they are replaced.

e.g. replace

$('div.someClass').click(function(e){     //do stuff }); 

with

$('div.someClass').live('click', function(e){     //do stuff }); 

Important:

While I've recommended using .live() this is for clarity as its syntax is similar to .bind(), you should use .on() if possible. See links in @jbabey's comment for important information.

like image 174
StuperUser Avatar answered Sep 19 '22 15:09

StuperUser