I am using the JQuery Form plug-in to send forms via Ajax. I cobbled together the code from various places and everything works perfectly, except one thing.
Upon success
the data from the PHP processing file gets output to a <div>
(i.e. the 'message sent' response). The ID of that <div>
is currently set within the function. What I want to do is to be able to set that ID outside of the function so it is more easily re-usable, but I can't for the life of me work out how to pass that ID into the function. Because:
I cannot set any arguments in the success:
section, I can only name the function.
I can't seem to be able to pass an argument any other way, i.e. I cannot add an extra argument to the success function, i.e. writeOutput(data,divID)
, defining divID
elsewhere.
Here's the relevant code:
$(formOne).ajaxForm({
beforeSubmit: function() {
return $(formOne).validate({
// validation rules
}).form();
},
beforeSend: function() {
// beforeSend actions
},
success: writeOutput
});
function writeOutput(data) {
var $out = $('#output');
if (typeof data == 'object' && data.nodeType)
data = elementToString(data.documentElement, true);
else if (typeof data == 'object')
data = objToString(data);
$out.append('<div>'+ data +'</div>');
}
So how can I define the ID (which is currently #output) outside of the writeOutput()
function?
Not sure if this works and not a direct answer,
For "I cannot set any arguments in the success: section", you could do something like:
$(formOne).ajaxForm({
beforeSubmit: function() {
return $(formOne).validate({
// validation rules
}).form();
},
beforeSend: function() {
// beforeSend actions
},
success: writeOutput,
context: { extra_arg: 'some_value' }
});
function writeOutput(data) {
var extra_var_val = this.extra_var; //the extra argument
var $out = $('#output');
if (typeof data == 'object' && data.nodeType)
data = elementToString(data.documentElement, true);
else if (typeof data == 'object')
data = objToString(data);
$out.append('<div>'+ data +'</div>');
}
Whatever is passed into 'context' becomes the context of the callback function. Hope it works.