1

I'm including a script "foo.js" that I want to modify:

<head>
    <script src="/myPath/foo.js" type="text/javascript"> </script>
</head>

To be able to hook into an ajax call on my main page:

$.ajax({
    url: urlPath,
    success: function (data) {
        //hook into here from foo.js somehow??
    }
});

Is there any way to do this solely in foo.js without modifying the main page's script at all? (perhaps hook into a call inside the main script that is filling out/changing content?)

Thanks!

2
  • I don't understand. Do you want to call a function defined in foo.js in your ajax success handler? Apr 2, 2012 at 18:34
  • No, I want to completely leave my ajax success handler alone but script foo.js so that it alters data that is returned in that call.
    – Buchannon
    Apr 2, 2012 at 21:09

2 Answers 2

5

You can try to use a Global Ajax Event Handlers for listning global events.

1
  • These are great, however it looks like you can't alter the data in the xhr.responseText object that it returns? However, I did get a solution working using ajaxSuccess() and window.setInterval() - thanks!
    – Buchannon
    Apr 2, 2012 at 19:15
0

If your foo.js is wrapped in a closure (if you don't know what this means, just ignore) then you can bind to a namespace and call functions through there.

Otherwise, javascript has a global scope so any scripts imported into your file will have the ability to call functions as long as it is imported in order of dependencies.

ie:

foo.js:

function foo(data) {
   // do stuff with data
}

main.html:

<head>
   <script src="/myPath/foo.js" type="text/javascript"></script>
   <script type="text/javascript">
       $.ajax({
          url: urlPath,
          success: function(data) {
              foo(data);
          }
       });
   </script>
 </head>

It's important that the embedded script comes AFTER the import so that it can make reference to functions inside foo.js.

1
  • 1
    Like I was saying, I don't want to alter what is in "main.html" at all, including adding a call to foo(data); I just need to hook into the success of that ajax call through the external script.
    – Buchannon
    Apr 2, 2012 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.