JQueryForm (plugin) on submit do something with form & # 8594; $ (this)
I have multiple forms on the same page and I am using the jQueryForm plugin to process them without reloading the page. The problem is that I need some kind of visual response that forms the submit view or not, so I change the border from gray to green if it works, and red if it doesn't.
Well this works with pure jQuery, but not with this plugin, since when I use $(this)
it is for the function itself.
Does anyone have any idea how to do this?
var edit_form = {
dataType: 'json',
success: function(output) {
console.log($(this));
$form = $(this);
$form.css("border-color", "green");
setTimeout(function(){
$form.css("border-color", "#323131");
}, 3000);
},
error: function(output) {
console.log($(this));
$form = $(this);
$form.css("border-color", "red");
setTimeout(function(){
$form.css("border-color", "#323131");
}, 3000);
}
};
$('.twitch-form').ajaxForm(edit_form);
The console log returns this:
[Object, constructor: function, init: function, selector: "", jquery: "1.7.2", size: functionβ¦]
Usually for things like this I would use $.post
, but I need to be able to upload images with these forms ...
Thank.
source to share
If you look at the plugin documentation (look at the parameter success
) the success method gets the form object as the 4th parameter
success
Callback to be called after the form has been submitted. If a "success" callback is provided, it is called after the response has been returned from the server. It passed the following arguments: 1.) responseText or responseXML (depending on the value of the dataType parameter). 2.) statusText 3.) xhr (or jQuery filled form element if using jQuery <1.4) 4.) jQuery-wrapped form element (or undefined if using jQuery <1.4)
So,
var edit_form = {
url: 'asdf/asdf',
dataType: 'json',
success: function (output, status, xhr, $form) {
console.log('x',$form, status);
$form.css("border-color", "green");
setTimeout(function () {
$form.css("border-color", "#323131");
}, 3000);
},
error: function (xhr, status, error, $form) {
console.log($form)
$form.css("border-color", "red");
setTimeout(function () {
$form.css("border-color", "#323131");
}, 3000);
}
};
$('.twitch-form').ajaxForm(edit_form);
Demo: Fiddle
source to share
Read the API, there are options available ... try
<script>
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
var options = {
target: '#divToUpdate',
url: 'comment.php',
success: function(){ alert("Success ")},
error:function(){
alert("Error occurd");
}
};
$('#myForm').ajaxForm(options);
});
</script>
<form id="myForm" action="" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>
source to share