jQueryForm (plugin) on submit do something with form -> $(this) - javascript

I have multiple forms on one page and I am using jQueryForm plugin to handle them without page reload. The problem is, i need some visual response that form submit worked or not, so I am changing the border from gray to green if it worked and to red if it did not.
Well, that works with pure jQuery, but not with this plugin, as when I use $(this) it refers to function itself.
Does somebody have idea how to do that?
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);
Console log returns this:
[Object, constructor: function, init: function, selector: "", jquery: "1.7.2", size: function…]
Normally for such things I would use $.post but I need to be able to upload images with those forms...
Thanks.

If you look at the plugin documentation(look at the success option), the success method gets the form object as the 4th parameter
success
Callback function to be invoked after the form has been
submitted. If a 'success' callback function is provided it is invoked
after the response has been returned from the server. It is passed the
following arguments:
1.) responseText or responseXML value (depending on the value of the dataType option).
2.) statusText
3.) xhr (or the jQuery-wrapped 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

According to the documentation here's how you create a success callback:
var options = {
success: showResponse
...
}
function showResponse(responseText, statusText, xhr, $form) {
...
}
http://malsup.com/jquery/form/#ajaxForm

Read the API, In there provide available options... try this
<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>

Related

Get id of parent div from clicked form submit

Okay so I have multiple forms on the page, the difference is their id, also each one has a parent box, all of which also have a different id.
The html of one of the box:
<div class="center-block" id="box2">
<form action="/login" id="form2" method="post" novalidate="novalidate">
<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="2">
<input id="Name" name="Name" type="hidden">
<input type="submit" value="Submit">
</form>
</div>
I submit the forms with ajax, and what I want to do is find the id of the box that had its form submitted.
This is the script:
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function () {
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Here I would like to alert the id of the parent box.
//Something like this:
alert($(this).closest('div').attr('id'));
//Which returns undefined
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
</script>
Any idea how I would do that?
$(this) won't work in success callback. $(this) is relative, the scope of $(this) will be of success callback. You need to assign a variable first & then use it in success callback
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function () {
var curr_form = $(this);
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Here I would like to alert the id of the parent box.
//Something like this:
curr_form.closest('div').attr('id')
//Which returns undefined
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});
</script>
Just use the JQuery parent() method:
alert($(this).parent().attr('id'));
Also, as others have pointed out, you have a different issue in that this isn't pointing to the form when you use it in the success callback. You should cache that value and then use the cache variable. You can read more about how this works in JavaScript in another post of mine.
$(document).ready(function() {
$('form').submit(function () {
// Cache the object that "this" is bound to because
// in the success function, the invocation context
// changes and "this" won't point to the same object
// it does now.
var theForm = this;
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: $(this).serialize(),
success: function (data) {
if (data !== "0") {
window.location.href = data;
} else {
//Just use the JQuery parent() method with the cached object
$(theForm).parent().attr('id')
}
},
error: function () {
alert("No idea what went wrong");
}
});
return false;
});
});

Uncaught TypeError is not a function

I have a form that I'm trying to submit via ajax and I'm having some issues that I don't understand.
So I have the following function defined at the top of my main.js:
function formSubmit() {
var valid = true;
$(this).find('input, select, textarea').each(function(index, el) {
if(valid)
{
if($(el).is(':hidden'))
{
$(el).removeAttr('required');
}
if(!el.checkValidity())
{
valid = false;
//el.focus();
}
}
});
if (!valid)
return; // not ready to submit
var options = {
url: document.location.origin + 'update.php',
type: 'post',
dataType: 'json',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showError // post-submit callback
};
// bind form using 'ajaxForm'
$(this).ajaxSubmit(options);
};
Later in my main.js I have the following line that is run when I click a button:
$('#contact-form').formSubmit();
Also in my main.js I have:
$('body').on('change', '#contact-form', formSubmit);
In my HTML:
<form name="contact" id="contact-form">
<input type="text" name="name" value="" required>
<input type="hidden" name="page" value="contact">
</form>
When I run the $('#contact-form').formSubmit(); line, I get the error:
Uncaught TypeError: $(...).formSubmit is not a function
However, when I simply edit the name field (triggering the "on change" line) it updates and runs the function just fine.
What am I missing?
EDIT: It looks like the outcome I'm looking for is not apparent, probably because I'm not super familiar with javascript.
What I was trying to do was have a button that ran the formSubmit() function such that the $(this) element in that function was the form element.
I thought I could just run $('#contact-form').formSubmit() to do that but apparently not?
How would I go about running the formSubmit() function such that $(this) in that function refers to the element with an id of '#contact-form'?
Replace
$('#contact-form').formSubmit();
With
$('#contact-form').submit();
https://api.jquery.com/submit/
Try on submit.
$('#contact-form').submit(function(){
}
Since you are using jQuery, try something like this:
+function ($) {
$.fn.formSubmit = function() {
var valid = true;
$(this).find('input, select, textarea').each(function(index, el) {
if(valid)
{
if($(el).is(':hidden'))
{
$(el).removeAttr('required');
}
if(!el.checkValidity())
{
valid = false;
//el.focus();
}
}
});
if (!valid)
return this; // not ready to submit
var options = {
url: document.location.origin + 'update.php',
type: 'post',
dataType: 'json',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showError // post-submit callback
};
// bind form using 'ajaxForm'
$(this).ajaxSubmit(options);
return this;
}
}(jQuery);
That way, you should be able to use it like this: $("#contact-form").formSubmit();

jQuery Animation Works But Not Always

I have a form that contains an input with type="image" attribute. I am changing the image everytime whether I get a success or fail call.
But It doesn't work always, I don't see why. Is there any possible way to eliminate setTimeout(function()) or alternative way to implement this animation since this may cause the problem?
HTML
<p class="text-center" style="color:brown" id="input_result">Send</p>
<form data-ajax="false" method="post" name="login_form" role="form">
<div class="form-group">
<input type="image" src="images/default.png" class="img-responsive center-block" name="submit" class="submitBtn" id="input_img">
</div>
</form>
Script
<script>
$('form').bind('submit', function() {
$.ajax({
type: 'POST',
url: 'includes/sendmail.php',
data: $(this).serialize(),
cache: false,
dataType: 'text',
success: function(data, status, xhttp) {
$("#input_img").slideUp(2000).slideDown(1000);
setTimeout(function() {
// Success animation
$('#input_img').attr("src", "images/success.png");
jQuery("input[type='image']").prop("disabled", true);
$('selector').click(false);
$("#input_result").text("Sent!");
$("#input_result").css("color", "green");
}, 1999);
this.submit();
},
error: function(jqXHR, textStatus, errorThrown) {
$("#input_img").slideUp(2000).slideDown(1000);
setTimeout(function() {
// Fail animation
$('#input_img').attr("src", "images/fail.png");
jQuery("input[type='image']").prop("disabled", true);
$('selector').click(false);
$("#input_result").text("Failed to send!");
$("#input_result").css("color", "red");
}, 1999);
},
});
return false;
})
</script>
When you submit the form using this.submit(); the page is submitted to the server and reloaded again, so you lose the success animation. Since you are posting the values in the function, you don't need to submit the form.
Instead of $("#input_img").slideUp(2000).slideDown(1000); you can use the callback of slideUp to run your function and then in the end of that function call .slideDown()
Like:
$("#input_img").slideUp(2000, function(){
$('#input_img').attr("src", "images/fail.png");
jQuery("input[type='image']").prop("disabled", true);
$('selector').click(false);
$("#input_result").text("Failed to send!");
$("#input_result").css("color", "red");
$("#input_img").slideDown(1000);
}

jQuery is not getting applied

I am working on notification system and loading html notification body from database to views which populate as follows:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and applying jQuery function which I already defined on same page is like this:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
});
So when user click on button it's not work even not showing alert.
But things gets more interesting when I inject above jquery function from chrome console while view is loaded and button start working fine and shows alert too!
I am not getting the point which not letting things work!
It's because your acceptingRequest function is visible only inside anonymous jQuery(document).ready callback.
So when you click the button acceptingRequest is not visible.
Solutions keeping jQuery(document).ready(function() {})
To solve this bind the handler inside the callback using $('button.acceptinvite').on('click',acceptingRequest)
or use an anonymous callback (something like this):
$('button.acceptinvite').on('click',function(){
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
});
In both cases remove onclick="acceptingRequest();" since it's no longer needed.
Another option is to make acceptingRequest visible outside using a global variable (it's not a good practice anyway):
acceptingRequest = function () {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
Now acceptingRequest is visible outside jQuery().ready and you can do onclick="acceptingRequest();"
Solutions without jQuery(document).ready(function() {})
If you don't need the DOM to be completely loaded (like in this case) you can remove
jQuery(document).ready(function() {}) and just write your function from in head, so they are visible to the button.
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
</script>
Let me know if this was useful.
I think you are defining the function acceptingRequest() on document ready, but you are not really calling it. Try adding:
acceptingRequest();
just after the definition of the acceptingRequest() function. The result would be:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
acceptingRequest();
});
It is because this string
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
will be proceded by the browser earlier than the definition of your acceptingRequest function. 'acceptingRequest' in your code will be defined asynchronously when document ready fired. So browser can't assign it with the click listener. Try to put your script exactly before </body>(and after jQuery script) and without jQuery(document).ready
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
</script>
</body>
Function defined in ready state can be used in it's own scope.So you can use acceptingRequest() method in ready state.
in my view below code is bestpractice in event binding:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" id="acceptInviteButton" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and in ready state:
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
$("#acceptInviteButton").on("click",acceptingRequest);
});

AJAX: Submitting a form without refreshing the page

I have a form similar to the following:
<form method="post" action="mail.php" id="myForm">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="submit">
</form>
I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.php script to run behind the scenes without refreshing the page.
I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):
$.post('mail.php', $('#myForm').serialize());
If possible, I would like to get help implementing this using AJAX,
Many thanks in advance
You need to prevent the default action (the actual submit).
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('mail.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
You haven't provided your full code, but it sounds like the problem is because you are performing the $.post() on submit of the form, but not stopping the default behaviour. Try this:
$('#myForm').submit(function(e) {
e.preventDefault();
$.post('mail.php', $('#myForm').serialize());
});
/**
* it's better to always use the .on(event, context, callback) instead of the .submit(callback) or .click(callback)
* for explanation why, try googling event delegation.
*/
//$("#myForm").on('submit', callback) catches the submit event of the #myForm element and triggers the callbackfunction
$("#myForm").on('submit', function(event, optionalData){
/*
* do ajax logic -> $.post is a shortcut for the basic $.ajax function which would automatically set the method used to being post
* $.get(), $.load(), $.post() are all variations of the basic $.ajax function with parameters predefined like 'method' used in the ajax call (get or post)
* i mostly use the $.ajax function so i'm not to sure extending the $.post example with an addition .error() (as Kristof Claes mentions) function is allowed
*/
//example using post method
$.post('mail.php', $("#myForm").serialize(), function(response){
alert("hey, my ajax call has been complete using the post function and i got the following response:" + response);
})
//example using ajax method
$.ajax({
url:'mail.php',
type:'POST',
data: $("#myForm").serialize(),
dataType: 'json', //expects response to be json format, if it wouldn't be, error function will get triggered
success: function(response){
alert("hey, my ajax call has been complete using the ajax function and i got the following response in json format:" + response);
},
error: function(response){
//as far as i know, this function will only get triggered if there are some request errors (f.e: 404) or if the response is not in the expected format provided by the dataType parameter
alert("something went wrong");
}
})
//preventing the default behavior when the form is submit by
return false;
//or
event.preventDefault();
})
try this:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
The modern way to do this (which also doesn't require jquery) is to use the fetch API. Older browsers won't support it, but there's a polyfill if that's an issue. For example:
var form = document.getElementById('myForm');
var params = {
method: 'post',
body: new FormData(form),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
};
form.addEventListener('submit', function (e) {
window.fetch('mail.php', params).then(function (response) {
console.log(response.text());
});
e.preventDefault();
});
try this..
<form method="post" action="mail.php" id="myForm" onsubmit="return false;">
OR
add
e.preventDefault(); in your click function
$(#yourselector).click(function(e){
$.post('mail.php', $(this).serialize());
e.preventDefault();
})
You need to prevent default action if you are using input type as submit <input type="submit" name="submit" value="Submit">.
By putting $("form").submit(...) you're attaching the submit handler, this will submit form (this is default action).
If don't want this default action use preventDefault() method.
If you are using other than submit, no need to prevent default.
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'save.asmx/saveData',
dataType: 'json',
contentType:"application/json;charset=utf-8",
data: $('form').serialize(),
async:false,
success: function() {
alert("success");
}
error: function(request,error) {
console.log("error");
}
Take a look at the JQuery Post documentation. It should help you out.

Categories