ajax contact form Id, bugged - ajax

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?

Related

Get data with AJAX and save them as variables

I'm totally new to AJAX and I don't seem to know the best way to search what I'm looking for. So trying to explain it here.
I have a table which lists my users. I want to be able to edit any row of the table without refreshing. So I added a button for each row, by clicking which you'll be able to edit that user with the help of Bootstrap modals.
There's this button which initiates the action:
<span class="updateInfo" user-id="<?php echo $users_array['id']; ?>" data-target=".editInfo" data-toggle="modal"><i class="fa fa-pencil" ></i></span>
$users_array is an array fetched earlier from a table in database. The table also has 'id, name, email, phone' as columns.
So, what I basically have in my JS code is this:
jQuery(document).ready(function() {
$('.updateInfo').click(function(){
var userID = $(this).attr('user-id');
$.ajax({
url: "edit.php",
method: "POST",
dataType: 'json',
data: {
selected_user_id: userID,
},
success: function(data) {
// I don't know what to do here :(
}
});
});
});
The codes included in edit.php file are as followed:
$user_id=$_POST['selected_user_id'];
$get_user=mysql_query("SELECT * FROM users WHERE id='$user_id'");
$user_array=mysql_fetch_row($get_user);
echo json_encode($user_array);
I didn't put the codes that establish database connection and the like, since they're basics and work fine.
I have several problems here:
I have no idea if the way I've written the code so far is correct.
How I'm supposed to get those results and save them as variables for a later use.
I don't know if I can use the newly created variables as placeholders or pre-defined values in a modal that exists in the original file.
P.S: The modal has a simple form with simple inputs for name, email and phone number:
<div class="modal fade editInfo" tabindex="-1" role="dialog" aria-labelledby="myNote" data-backdrop="static" aria-hidden="true">
<form method="POST">
<input name="fullname" value="" />
<input name="email" value="" />
<input name="phone" value="" />
</form>
</div>
set Id for each html element
jQuery(document).ready(function() {
$("#fullname").val("USer One ");
$("#email").val("User#gmail.com");
$("#phone").val("987654");
$('.updateInfo').click(function(){
var userID = $(this).attr('user-id');
$.ajax({
url: "edit.php",
method: "POST",
dataType: 'json',
data: {
selected_user_id: userID,
},
success: function(data) {
console.log(data);
$("#fullname").val(data.fullname);
$("#email").val(data.email);
$("#phone").val(data.phone);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="modal fade editInfo" tabindex="-1" role="dialog" aria-abelledby="myNote" data-backdrop="static" aria-hidden="true">
<form method="POST"> <input id="fullname" name="fullname" value="" /><input id="email" name="email" value="" /> <input id="phone" name="phone" value="" /> </form>
</div>
and then bind like this :

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

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.

My .ajax call isn't working

I have a form on my website that pushes to my e-mail address. Previously before I wrote an ajax function the form would successfully push to my e-mail address. Only problem is when the user fills out the form it takes them to another page upon submitting the form. The HTML for my form is below.
<form id="contact" method="post" action="E-mail-form.php" name="EmailFromMyWebsite">
<label for="name">Name</label> <br>
<input type="text" name="name" class="required" placeholder="Your Name" title=" (Your name is required)"> <br />
<label for="email">E-mail</label> <br>
<input type="email" name="email" class="required email" placeholder="Name#email.com" title=" (Your email is required)"> <br />
<label for="message">Message/Comment</label> <br>
<textarea name="message" class="required" placeholder="Leave a brief message" title=" (Please leave me a brief message)"></textarea> <br />
<input type="submit" name="submit" id="submit" value="Send Message" />
</form>
</div><!-- /end #contact-form -->
The ajax call I wrote is...
$("#submit").on('click', function(){
var formData = $('#contact').serialize();
$.ajax({
type:"POST",
data:"formData",
url:"Email-form.php",
success: function(data){
$('#contact').html('<p>Your message has been sent</p>');
}
});
});
My javaScript console shows no errors so I think the problem is with my jQuery logic. On Chrome when I click submit I am redirected to my homepage. On Firefox the form submits but I am redirected to another page, therefore it is completely ignoring my AJAX call. Can someone with AJAX experience tell me what I'm doing wrong? Also I would love to attach a message if the call fails. Can I add 'failure:' and for the value put a function just like I did for success?
You have two issues
your form is submitting normally
you're attempting to post the wrong data
To prevent the form from submitting you can return false from the jQuery click handler or call preventDefault from the event object.
You are sending a string "formData" as the form data instead of the string in the formData variable
$("#submit").on('click', function(event){
var formData = $('#contact').serialize();
$.ajax({
type:"POST",
data:formData,
url:"Email-form.php",
success: function(data){
$('#contact').html('<p>Your message has been sent</p>');
}
});
event.preventDefault();
// or
return false;
});
There's a good chance that the normal form submit action is still taking place, even though you have an AJAX call as well. An easy fix for this may be to simply change the button type from submit to button. That way your click handler will still work, but it won't perform the default action of submitting the form on its own.
<input type="button" name="submit" id="submit" value="Send Message" />

how to post form with yui3

When i use yui3`s io-form module to post a form, i found the field value that server reseived is null...
Any help is welcome.
<form name='testajax' id="testajax1" >
<input type="text" name="test1" id="test1" ></input>
<input type="text" name="test2" >
<input type="text" name="test3" id="result" >
<input type="submit" value="submit" id="submit">
</form>
Y.io('/ajax/test',{
method:'POST',
form: {
id:Y.one('#testajax1'),
useDisabled: true,
},
on:{
complete:function(id,response){
Y.log(Y.one('#test1').get('value'));
},
start:function(id,response){
Y.log(Y.one('#test1').value);
}
}
});
You are passing a Y.Node to form.id and the docs indicate that it takes either a string or a "formObject" which I'm assuming means a "form element". I don't believe a Y.Node is a valid (which is an unfortunate API choice if true). Try switching your code to:
form: {
id: "#testajax1"
}
http://yuilibrary.com/yui/docs/io/#serializing-html-form-as-data

jquery duplicate spans when append is used with fadeOut()

This is really strange, when I run this code i get 2 span.
$('#_login input').fadeOut('fast', function(){
$('#_login').append('<span id="bob_login_err" style="color:orange;font-size:10px;">Could not log in</span>').fadeIn('fast');});
that's beacause you have 2 input inside #_login i guesse login and password:
try this:
HTML:
<div id="_login">
<div class="inputHolder"><!--Put The 2 input inside a div-->
<input type="text" value="" name="login"/>
<input type="text" value="" name="password"/>
</div>
</div>​
JS:
$('#_login .inputHolder').fadeOut('fast', function(){
$('#_login').append('<span id="bob_login_err" style="color:orange;font-size:10px;">not could not log in</span>').fadeIn('fast');
});​

Resources