AJAX form $('form')[0].reset(); on submit not clearing values. What am I missing? - ajax

thank you in advance for any help given. I'm just learning jQuery and AJAX and would appreciate some help with the following code. All validation rules work, the form submits and the page does not refresh. The problem is that the form values are not clearing/resetting to default after the submit has triggered. Thoughts?
**********EDITED to include HTML markup*************
<div id="form">
<h1 class="title">Contact Us</h1><!-- title ends -->
<p class="contactUs">Ask about our services and request a quote today!</p><!-- contactUs ends -->
<div id="success"><p>Your message was sent successfully. Thank you.</p></div>
<p id="required">* All fields required.</p>
<form name="form" id="contactMe" method="post" action="process.php" onSubmit="return validateForm()" enctype="multipart/form-data">
<input class="txt" type="text" maxlength="50" size="50" required name="name" value="<?php echo $_GET['name'];?>" placeholder="Name" />
<div id="nameError"><p>Your name is required.</p></div>
<input class="txt" type="text" maxlength="50" size="50" required name="email" value="<?php echo $_GET['email'];?>" placeholder="Email Address" />
<div id="emailError"><p>A valid email address is required.</p></div>
<textarea name="message" rows="6" cols="40" required placeholder="Message"></textarea>
<div id="messageError"><p>A message is required.</p></div>
<input type="hidden" maxlength="80" size="50" id="complete" name="complete" placeholder="Please Keep This Field Empty" />
<input type="submit" value="SUBMIT" name="submit" />
<input type="reset" value="RESET" name="reset" />
</form>
</div><!-- form ends -->
//hide form submit success message by default. to be shown on successfull ajax submission only.
$(document).ready(function() {
if ($('#success').is(':visible')){
$(this).hide()
}
});
//form validation
function validateForm() {
//name
var a=document.forms["form"]["name"].value;
if (a==null || a=="")
{
$('#nameError').fadeIn(250);
return false;
}
//email address
var c=document.forms["form"]["email"].value;
var atpos=c.indexOf("#");
var dotpos=c.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)
{
$('#emailError').fadeIn(250);
return false;
}
//message
var e=document.forms["form"]["message"].value;
if (e==null || e=="")
{
$('#messageError').fadeIn(250);
return false;
}
}//javascript form validation ends
//ajax submit and clear form on success
$(function () {
$('form').on('submit', function (e) {
var myForm = validateForm();
if (myForm == false){
e.preventDefault();//stop submission for safari if fields empty
}
else{
$.ajax({
type: 'post',
url: 'process.php',
data: $('form').serialize(),
success: function () {
$('#success').fadeIn(250);
if ($('#nameError, #emailError, #messageError').is(':visible')) {
$('#nameError, #emailError, #messageError').fadeOut(250);
}
$('form')[0].reset();//clear form after submit success
}//success ends
});//ajax ends
e.preventDefault();//prevent default page refresh
}//else ends
});//submit ends
});//function ends
//if reset button is clicked AND messages displayed, remove all form html messages
$(document).ready(function() {
$('#form input[type="reset"]').click(function() {
if ($('#success, #nameError, #emailError, #messageError').is(':visible')) {
$('#success, #nameError, #emailError, #messageError').fadeOut(250);
}
});
});

By giving your input id="reset" and/or name="reset", you effectively overwrote the form.reset method of the form because by doing so you made form.reset target the reset button. Simply give it a different id and name value.
Never give elements name or id attributes that equal the name of a property of a dom node.

Related

fancybox and jquery form validation

Have problem with fancybox and jquery validate plugin when form is in fancybox container.
For examle (inline):
html:
<script>
$(document).ready(function(){ $.fancybox('
<form class="myform">
<input type="text" name="email" class="email" />
<input type="submit" value="submit" name="submit" />
</form>
');
})
</script>
js file:
$(".myform").validate(
{
rules: {
email: "required",
email: "email"
}
}
);
How to make jquery validation pluging to work in fancybox?
Do two things...
Use the afterLoad FancyBox callback function to initialize .validate() immediately after the form is loaded.
Put the content for FancyBox in a hidden div instead of in your jQuery. It's cleaner.
Note: You may want to reconsider using email for the name attribute. It has potential to cause great confusion since the rule is also called email.
HTML:
<a id="test" href="#inline">Test</a>
<div style="display:none" id="inline">
<form class="myform">
<input type="text" name="email" class="email" />
<input type="submit" value="submit" name="submit" />
</form>
</div>
jQuery:
$(document).ready(function () {
$('#test').fancybox({
afterLoad: function() {
$('.myform').validate({
// rules and options for validate plugin,
rules: {
email: { // "email" is name of the field
required: true,
email: true // "email" is name of the rule
}
}
});
}
});
});
Working DEMO: http://jsfiddle.net/ZMEEW/

ajax contact form Id, bugged

i have a contact form on http://daniloportal.com/NPC2/contact.html
Now this ajax script works very well, but i have other contact forms that i would like to use the same script for. so when i tried to create mulitple instances of the script, i noticed it stopped working because the ID name is not specifically ajax-contact-form. take a look at the code:
<form id="ajax-contact-form" action="">
<input type="text" name="name" value="Name *" title="Name *" />
<input type="text" name="email" value="Email " title="Email *" />
<input type="text" name="email" value="Email *" title="Email *" />
<textarea name="message" id="message" title="Message *">Message *</textarea>
<div class="clear"></div>
<input type="reset" class="btn btn_clear" value="Clear form" />
<input type="submit" class="btn btn_blue btn_send" value="Send message!" />
<div class="clear"></div>
</form>
and heres the JS
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact_form/contact_process.php",
data: str,
success: function(msg) {
// Message Sent - Show the 'Thank You' message and hide the form
if(msg == 'OK') {
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
} else {
result = msg;
}
$('#note').html(result);
}
});
return false;
});
Now if i were to switch that ID name on both and MATCH them, the script stops working- Theoretically it should work- not sure whats wrong with this.
as always any help is appreciated, thanks!
If you are trying to access two elements with the same id with jQuery - nothing gonna happen. Each element must have a unique identifier, otherwise you should use classes.
However, can you give us the markup of another form?

Codeigniter Cart: How to add multiple items with ajax and jquery

I'm building a ajax based shopping cart with Codeigniter, and the add / remove functions work perfectly. I am now trying to add an option for adding multiple items, and can't get it to work.
Here's the markup I'm using. I'm not sure if it's the best design, but it's working with the non-ajax function, so I guess it should be fine.
<form action="cart/add_multiple" method="post" accept-charset="utf-8">
<input type="hidden" name="items[0][id]" value="3571310" />
<input type="hidden" name="items[0][qty]" value="1" />
<input type="hidden" name="items[0][price]" value="59.00" />
<input type="hidden" name="items[0][name]" value="London" />
<input type="hidden" name="items[0][heb_name]" value="לונדון" />
<input type="hidden" name="items[0][full_price]" value="59.00" />
<input type="hidden" name="items[0][discount_price]" value="59.00" />
<input type="hidden" name="items[1][id]" value="7397903" />
<input type="hidden" name="items[1][qty]" value="1" />
<input type="hidden" name="items[1][price]" value="29.00" />
<input type="hidden" name="items[1][name]" value="London Triple" />
<input type="hidden" name="items[1][heb_name]" value="לונדון טריפל" />
<input type="hidden" name="items[1][full_price]" value="29.00" />
<input type="hidden" name="items[1][discount_price]" value="29.00" />
<input type="submit" name="add_multi" value="add to cart" /></form>
The ajax script is as follows:
$(document).ready(function() {
$(document).on("submit", "div#winning_combo_small form", function () { //catches every click on the submit button of the "add to cart" form
var items = $(this).serialize();
alert(items);
$.post(base_url + "cart/add_multiple", {items: items, ajax: '1' },
function(data){
if (data =='true')
{ // Interact with returned data
$.get(base_url + "cart", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_sidebar").html(cart);
})
$.get(base_url + "cart/count_items", function(items){
$("#cart_items").html(items);
})
}
});
return false;
})
});
But it's not working, because the add_multiple function receives the data as a string, not an array. Do I have to decode the data somehow to convert it to an array? Do the Hebrew characters get in the way and mess it all up?
I should say that when posting the form the regular way, without ajax, the items are added to the cart and all works well. So what is the difference between the regular post and the ajax post?
Well, I got it to work, though I'm not sure if it's the most elegant way.
Here's what I did:
In the ajax script, I changed var items = $(this).serialize(); to var items = $(this).serializeArray();. I now get an array instead of a string, but it's not the format I need to insert into the cart. So I looped over this array to create an array in the desired format, and used that new array to insert into the cart.
This is my add_multiple function under the cart controller:
function add_multiple()
{
$items = $this->input->post('items');
$ajax = $this->input->post('ajax');
// Check if user has javascript enabled
if($ajax != '1'){
$this->cart->insert($items); //if posted the regular non-ajax way, the fields will be in an array in the correct format
echo 'false';
redirect('cart'); // If javascript is not enabled, reload the page with new data
}else{
$i = 0;
foreach($items as $key=>$form_field)
{
$field_name = $form_field['name'];
$from_char = strrpos($field_name, '[') +1 ;
$length = strlen($field_name)-$from_char-1;
$field = substr($field_name,$from_char,$length);
$data[$i][$field] = $form_field['value'];
if ($field == "discount_price") $i+=1; // I know 'discount price' is always the last field
}
$this->cart->insert($data);
echo 'true'; // If javascript is enabled, return true, so the cart gets updated
}
}

Submitting form into a div

Can anyone tell me why this is not working or give me another way into doing what I want.
I have a form on a page when click submit I want it to process into add.php and for it to open up in a DIV called right.
Form page
<script>
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
</script>
</head>
<body>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload">
</form>
</body>
Now if I add action to form to direct it to add.php all works fine so other script is ok yet when i do it this way,nothing happens it does not load add.php into the 'right' div like I want it to.
Anyone got any suggestions?
Your $("#Submit") selector does not match anything (the submit button has no id and is defined after that bind attempt), so the function is not bound to any event, thus never executed.
Instead the form acts the way it should: upon submit it posts its content to the url specified in the 'action' attribute. This is what happens, that div is never touched.
you have to go back to understand how jquery selectors work. How to bind a function to an event.
Is this your exact code? There are a few issues:
$("#Submit").click should be wrapped in a document ready
handler so it doesnt run before the page has actually loaded.
There is no button that matches #Submit
There is no div that matches #right
Try
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
</head>
<body>
<div id="right">
</div>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload" id="Submit">
</form>
you have to create on div in body tag which id will be right and
<input id="submit" type="submit" name="upload" >
add new div in body tag like this
<div id="right"></div>

jQuery ajaxSubmit ignored by IE8

I am combing the jQuery validation plug-in with the jQuery Form Plugin to submit the form via AJAX.
This works perfectly in Firefox & Chrome, but (as usual) Internet Explorer is being a pain. For reasons that are alluding me, IE is ignoring the ajaxSubmit, as a result it submits the form in the normal fashion.
I've followed the validation plug-in's documentation when constructing my code:
JS:
<script src="/js/jquery.validate.min.js" type="text/javascript"></script>
<script src="/js/jquery.form.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var validator = $("#form_notify").validate({
messages: {
email: {
required: 'Please insert your email address. Without your email address we will not be able to contact you!',
email:'Please enter a <b>valid</b> email address. Without a valid email address we will not be able to contact you!'
}
},
errorLabelContainer: "#error",
success: "valid",
submitHandler: function(form) {$(form).ajaxSubmit();}
});
$('#email').blur(function() {
if (validator.numberOfInvalids() > 0) {
$("#label").addClass("label_error");
return false;
}
else {$("#label").removeClass("label_error");}
});
$('#form_notify').submit(function() {
if (validator.numberOfInvalids() == 0) {
$(this).fadeOut('fast', function() {$('#thank-you').fadeIn();});
return true;
}
return false;
});
});
</script>
Form HTML:
<form id="form_notify" class="cmxform" name="form_notify" action="optin.pl" method="get">
<fieldset>
<div class="input">
<label id="label" for="email">Email Address:</label>
<input type="text" id="email" name="email" value="" title="email address" class="{required:true, email:true}"/>
<div class="clearfix"></div>
</div>
<input type="hidden" name="key" value="sub-745-9.224;1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0;;subscribe-224.htm">
<input type="hidden" name="followup" value="19">
<input type="submit" name="submit" id="submit-button" value="Notify Me">
<div id="error"></div>
</fieldset>
</form>
I can't understand what is causing IE to act differently, any assistance would be greatly appreciated.
I can provide more information if needed.
Thanks in advance!
Try the following:
$('#form_notify').submit(function(e) {
e.preventDefault();
if (validator.numberOfInvalids() == 0) {
$(this).fadeOut('fast', function() {$('#thank-you').fadeIn();});
return true;
}
return false;
});

Resources