Josh Toth
Josh Toth

Reputation: 764

How to write a jQuery function that can be called on its own (no element)

I'm looking to write a function that mimics the ajax calls from the jQuery library. I do a lot of ajax calls on my current project, and I always end up writing the same blocks of code over and over to address errors and such - I'd like to write a function that can get the error data (or success message, if any) and return it, preferably in a JSON object.

That's not the part I'm worried about, what I really need to do is get the function to work without an element So, instead of

$("#element").transfer("page.php", "post", {'key': "value", 'other' : "data"});

I'd like to be able to call it like this:

$.transfer("page.php", "post", {'key': "value", 'other' : "data"});

...Sort of like the $.post() and a few other functions (ajax, get, getJSON) from jQuery.

I've tried every which way of writing the function/plugin, but without any success. Anybody know if it's even possible? [or if there's a better way to do it]

Upvotes: 2

Views: 1381

Answers (3)

BNL
BNL

Reputation: 7133

You don't need to define this function on the jquery obj. Just define a new function.

function transfer() {
    // whatever
}

Upvotes: 1

zzzzBov
zzzzBov

Reputation: 179046

You just set the function on the jQuery object, and it becomes available.

(function ($) {
  $.transfer = function () {
    //your custom logic here
  }
}(jQuery));

Upvotes: 9

Martin.
Martin.

Reputation: 10529

Define it as any other function

$.transfer = function(page, post, values) {
   //function body...
}

Upvotes: 4

Related Questions