jQuery Animation Works But Not Always - javascript

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);
}

Related

Display reesults from another html on same page using jquery web

Below is my code of html and jquery, i want to dsiplay results on submit button on the same page rather than its goes on next page. But it is not returning me any results and go to next page.
HTML code
<form id="create" action="/engine_search/search/" method="get">
<input style="height:40px;" type="text" class="form-control" placeholder="Search" name="q">
<center>
<input style="float:left; margin-left:150px;" type="submit" class="btn btn-default" value="Search">
</center>
</form>
jquery code:
<script>
$(document).ready(function() {
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
<input style="float:left; margin-left:150px;" type="submit" class="btn btn-default" value="Search" onclick="return SubmitFunction(this);">
Javascript :
function SubmitFunction(thisId){
$.ajax({ // create an AJAX call...
data: $(thisId).serialize(), // get the form data
type: $(thisId).attr('method'), // GET or POST
url: $(thisId).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
}
You should use event.preventDefault();
<script>
$(document).ready(function() {
$('#create').submit(function(event) { // catch the form's submit event
event.preventDefault();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
Look for console for any errors. It might be helpful.

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

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>

How to clear all inputs after form submission

I want to clear all inputs value whenever result succeed.
I have tried unbind from Jquery but doesn't get any result
so any suggestion would be great
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="Result"></div>
<form id="Form" action="File.php" autocomplete="off">
<input type="text" name="Name" />
<br/>
<input type="text" name="Pass" />
<br/>
<input type="button" id="Submit" value="Run Code" />
</form>
<script>
$(document).ready(function()
{
$("#Submit").click(function()
{
$("#Form").submit(function(e)
{
$.ajax(
{
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function(data, textStatus, jqXHR)
{
$("#Result").html(data);
}
});
e.preventDefault();
});
$("#Form").submit();
});
});
</script>
</body>
</html>
please feel free to ask for more details
You can clear all inputs using
$("input[type='text']").val('');
You are binding an event handler inside another event handler. Each time the button is clicked, a new handler is attached to the form. So, after n number of clicks, you'll be sending n number of ajax requests, as you can see here
Ideally, your code should be
$(document).ready(function () {
$("#Submit").click(function () {
$("#Form").submit();
});
$("#Form").submit(function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function (data, textStatus, jqXHR) {
$("input[type='text']").val(''); // reset the input values
$("#Result").html(data);
}
});
});
});
Demo.
Side note: You can simply use a submit button instead of triggering the form submission manually like this
Here you go:
$(document).find('input').each(function(){
$(this).val('');
});
More info on: http://api.jquery.com/val/

Ajax request is called too many times ( ajax loading gifs stops)

I am having a problem doing an ajax request with the following code.
Ajax Request
function doRequest(url, hostname) {
$.ajax({
url: url,
type: 'GET',
data: 'hostname=' + hostname,
error: function () { alert('erro'); $('#loading').hide(); },
success: function (data) {
$('#content').html(data);
$('#loading').hide();
},
beforeSend: function () {
alert(1);
$('#content').html("");
$('#loading').show();
}
});
return false;
}
Search Form
<form action="/Home/SearchMachine" class="form-wrapper cf" id="search">
<input type="text" placeholder="Hostname..." id="hostname" required>
<button type="submit">Validar</button>
</form>
Click event
$('#search').submit(function() {
if (validateSearchForm()) {
$('#val_error').hide();
doRequest('/Home/SearchMachine',$('#hostname').val());
}
else
$('#val_error').show();
return false;
});
In the first request I get one alert(1), in the second two alert(1), in the next four alert(1) that are triggered in success function. I made too many tests but I did not find the solution. After many requests, the ajax loading gif stops, as well as the browser.
I made a quick test with your code and a test service. I'm not able to reproduce the problem. Each callback only happens once per click.
doRequest('http://headers.jsontest.com/', $('#hostname').val());
http://jsfiddle.net/QUXJU/
Are you re-binding submit somehow after each click?
Give an onSubmit to the form for transparency..
Form :
<form action="/Home/SearchMachine" onSubmit="submit_form(); return false;" class="form-wrapper cf" id="search">
<input type="text" placeholder="Hostname..." id="hostname" required>
<button type="submit">Validar</button>
</form>
Function:
function submit_form()
{
if (validateSearchForm()) {
$('#val_error').hide();
doRequest('/Home/SearchMachine',$('#hostname').val());
}
else
$('#val_error').show();
}

JQuery sends empty values

I dont get it... I reviewed my code hundred times and I dont get the error...
I am actually testing a bit with JQuery and AJAX and made a simple form with a textarea to submit. Without AJAX it works fine, but with, it sends always an empty value of my textarea...
The Javascript Code:
$(document).ready(function(e) {
$("#formPost input").attr("disabled", false);
$("#formPost input:submit").click(function() {
$.ajax({
type: 'POST',
url: 'post.php',
dataType: 'json',
data: $('#formPost').serialize(),
beforeSend: function(XMLHttpRequest) {
$("#formPost input").attr("disabled", true);
$("#formPost .ajaxloader").show();
},
success: function(data) {
var message = $("#flashMessage");
message.text(data.msg);
if(data.error) {
message.addClass("fail");
}
else {
message.addClass("success");
}
message.show();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#formPost .ajaxloader').hide();
$('#flashMessage').removeClass().
addClass('fail').text('There was an error.').show();
},
complete: function(XMLHttpRequest) {
$("#formPost input").attr("disabled", false);
$("#formPost .ajaxloader").hide();
}
});
return false;
});
});
The HTML:
<div>
<h1>Add new post</h1>
<div id="flashMessage"></div>
<form id="formPost" method="post" action="post.php">
<textarea id="post" name="post"></textarea>
<input type="submit" value="Save" />
<div class="ajaxloader">
<img src="ajax-loader.gif" />
</div>
<div class="clear"></div>
</form>
</div>
I use Firebug and look under "Network" -> "XHR" -> "Post" and under Source he shows post=
So where is the value gone?
Your problem is related with CKEditor (as you said in the comment), because WYSIWYG editors replace the appearance of textarea and update value on form submit. So you have to use built-in functions of CKEditor for updating textarea's value manually as you are using Ajax. I can't help you specifically with CKEditor but this thread may help: CKEditor, AJAX Save .
You are disabling the form elements in the beforeSend method, but JQuery's serialize will ignore those disabled elements. Try removing that first to test. This SO question has some ways to get around it.

Categories