Joe Torraca
Joe Torraca

Reputation: 2018

jQuery pass arguments to external function from ajax loaded page

The title may sound confusing but it actually isn't, I just didn't know how to explain it. So my home page has a script which loads an external php file for a section of my website. Inside that php file, I need to call a function, with parameters, inside the main javascript file(the file that loaded it). I have tried .bind("click", parameter1, paramter2, loadFunction);, the expanded version of that and .click({...}) but I can't get it to work. How would I go about doing this? I don't want to put the code that I need to call inside the php file because it is calling another ajax request(yes my site is ajax heavy) and don't want people to find it that easy, I would rather it be buried in my javascript file. Thanks for any help! If you need any more info, let me know.

Upvotes: 0

Views: 756

Answers (1)

Greg Pettit
Greg Pettit

Reputation: 10830

You may say it isn't confusing, but it is, a little. ;-) My answer is based on the following flow of events:

  1. An Ajax call is made from a function defined in your main JS.
  2. The PHP acts on given parameters, does "something", and returns a result
  3. The returned result may NOT contain more script to execute, however, more script DOES execute depending on the contents of the returned result.

This statement: "I would rather it be buried in my javascript file" sends up a red flag for me. If anyone cares to know what your site is doing, they'll figure it out whether the script is in a minified JS file or not. I would argue that returning a script is actually going to be more secure because the scope will be limited.

That said, I wouldn't return a script anyhow. The very premise of the problem is its own answer.

  1. Make your Ajax call, passing parameters to PHP in a query string or in POST data.
  2. Your PHP processes the parameters and returns a response.
  3. The success function of the Ajax call grabs the response, perhaps encoded in JSON for nice and easy processing, and then fires up a function call scoped in the main application.

I honestly can't tell where the bind and click failures even factor into the equation. Are you not able to bind click for the first Ajax call in the first place? I imagine if your site is Ajax-heavy you already know how to do this, no?

[response to comment]

If your PHP generates and returns JSON, you can do whatever you want with it:

{
    "content": "<div>Some HTML</div>",
    "action": "append_and_refresh",
    "recordsDeleted": 5
}

In the success function all you have to do is process it however you want:

success: function(data) {
  $('#someDiv').html(data.content);
  if(data.action == "append_and_refresh") {
    doAppend();
    doRefresh();
  }
  recordsDeleted += data.recordsDeleted
}

An intentionally simplified example, but hopefully you get the picture!

Upvotes: 1

Related Questions