Jump to content

jquery: changing an js function based on data returned from ajax call


thewooleymammoth

Recommended Posts

I am creating a page that loads new content via ajax, but i need to execute a javascript function based on the content. ex

<div id='content'>

  <script type='text/javascript'>
      function newFunction(){

         alert('first function');
      }
  </script>

<p>here is content 1</p>
</div>

Then i want to change the contents of the page div, with ajax, to the following:

 

  <script type='text/javascript'>
      function newFunction(){

         alert('second function');

      }
  </script>

<p>here is content 2</p>

then call the newFunction() on a user event. but i need the function performed to match the function currently loaded inside the #page div. However, the function called is always the one first loaded ex:

 

loadpage->newFunction returns "first function" -> load new function via ajax->newFunction still returns "first function"

 

Any idea on how to achieve a return of second function after the ajax interaction?

 

PS: im using jquery.

 

Link to comment
Share on other sites

With the little bit posted here, it seems to me like you're going about it backward.  Are you putting the script inside a div?  Don't do that.  Put all the functions in a separate file linked in your <head>.

 

As far as running one function instead of another, which I think you're trying to do, you have to look at the existing situation in the script and evaluate it.  Set up an if statement or switch for more than two possibilites which will evaluate the situation and run the proper function, even if that if is something simple like (psuedocode): if div K is hidden, run  function A.  Else run function B. 

 

All of that code, however, should be in a separate file and kept together there. 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.