data is updated on database but Ajax is not successful - php

I would like to update information on database. It is updated when i use this line of codes. Unfortunately it is telling me that my ajax is not successfull since it didnt proceed to success function. please help.
HTML CODE
<form class="EditEmployees" method="POST">
<span>Employee ID:</span><span id="employeeid"></span>
<span>First Name</span>
<input type="text" id="editfirstname" name="editfirstname" placeholder="" class="tb-style">
<span>Last Name</span>
<input type="text" id="editlastname" name="editlastname" placeholder="" class="tb-style">
<span class="label" for="">Gender</span>
<select class="tb-style" name="editgender" id="editgender">
<option>Please Select</option>
<option value = "male">Male</option>
<option value="female">Female</option>
</select>
<span class="label" for="dob">Date of Birth</span>
<input type="date" id="editdob" name="editdob" class="tb-style">
<div class='input-group date' id='datetimepicker1' >
<div class="input-group-addon">
<span class="label" for="dob">Date Hired</span>
<input type="date" id="editdatehired" name="editdatehired" class="tb-style">
<button type="" class="btn-EditSave w-100" name="">Save Changes</button>
</form>
JQuery code.
$('.btn-EditSave').click(function(){
// alert($('#editfirstname').val())
$.ajax({
url:'ajax.php',
data:{id:id,
type:'update-records-via-id',
FirstName:$('#editfirstname').val(),
LastName:$('#editlastname').val(),
dob:$('#editdob').val(),
datehired:$('#editdatehired').val(),
gender:$('#editgender').val()
},
dataType:'JSON',
type:'POST',
success: function(data){
alert("data saved")
}
})
})
PHP CODE: update data on database
function updaterecordviaid($id,$FirstName,$LastName,$gender,$dob,$datehired,$position){
$conn = mysqli_connect("localhost","root","","test");
$result = "update employees set FirstName = '$FirstName', LastName='$LastName', Gender = '$gender', DateOfBirth = '$dob', DateHired= '$datehired', PositionId='$position' where EmployeeId='$id'";
if(mysqli_query($conn,$result)){
echo json_encode(array('message'=>'Record Succesfully Updated!','FirstName'=>$FirstName,'LastName'=>$LastName));
return;
}
echo json_encode(array('message'=>'Something went wrong'));
return;
}

Related

Drop down onchange event to get the amount in the tex tbox in ajax from mysql

I change my drop down i didn't get the amount in my text box.
anything wrong in this code? Do I need to change the function?
Database table name is product
e.x:
pid product amount
1 phone 1500
index.php
<div class="form-group">
<label for="product">product name</label>
<select class="form-control" id="product" name="product" onChange="getamount(this.value);">
<option value="">Select product</option>
</div>
<div class="form-group">
<label for="amount">amount</label>
<input type="text" class="form-control" id="amount" placeholder="amount" name="amount" readonly>
</div>
Ajax function:
function getamount(val) {
alert(val);
$.ajax({
type: "POST",
url: "get_amount.php",
data:'pid='+val,
success: function(data){
$("#amount").html(data);
}
});
}
get_amount.php
<?php
require_once("db.php");
if(!empty($_POST["pid"]))
{
$query =mysqli_query($conn,"SELECT amount FROM product WHERE pid= '" . $_POST["pid"] . "'");
?>
<?php
while($row=mysqli_fetch_array($query))
{
?>
<input type="text" value="<?php $row['amount]?>">
<?php
}
}
?>
In your html code, there is no closing select-tag, the value of the option field is empty, and there is no other option so onchange will not trigger.
I also changed the data of the ajax call in your getamount function.
This is how i tested it, to get it working:
function getamount(val) {
alert(val);
$.ajax({
type: "POST",
url: "get_amount.php",
data: {
pid: val
},
success: function(data) {
$("#amount").html(data);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="product">product name</label>
<select class="form-control" id="product" name="product" onChange="getamount(this.value);">
<option value="">Select product</option>
<option value="1">Select product1</option>
<option value="2">Select product2</option>
</select>
</div>
<div class="form-group">
<label for="amount">amount</label>
<input type="text" class="form-control" id="amount" placeholder="amount" name="amount" readonly>
</div>

POST Request doesnt get received

So I have this form to add a person to a database:
<div id="formDiv">
<form id="form1" method="post" action="#">
<input type="text" name="title" placeholder="Title">
<br>
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="group" placeholder="Group">
<br>
<input type="text" name="company" placeholder="Company">
<br>
<select name="sex" required>
<option value="" disabled selected>Sex/option>
<option value="male">male</option>
<option value="female">female</option>
</select>
<br>
<button type="submit" id="insert" name="insert">Insert</button>
</form>
</div>
And a php File that handles inserting the data into the database:
<?php
include($_SERVER['DOCUMENT_ROOT'].'/website/dbConnection.php');
include($_SERVER['DOCUMENT_ROOT'].'/website/administrator/components/com_backend/backend.php');
if(isset($_POST['insert'])){
$title = $_POST['title'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$group = $_POST['group'];
$company = $_POST['company'];
$sex = $_POST['sex'];
if ($sex == "male"){
$sex = 0;
}
else{
$sex = 1;
}
$query = "INSERT INTO members (Title, Firstname, Lastname, Group, Company, Sex)
VALUES('$title', '$firstname', '$lastname', '$group', '$company', '$sex')";
mysqli_query($GLOBALS['connect'], $query);
}
I know that theres a problem between the 2 files communicating. Because the 2nd File does not receive the POST from the 1st file.
When I use the first file and press the submit Button, it reloads the page and enters nothing into the database.
When I navigate directly to the 2nd file, I can use the form since I include the first file. So I fill out the form, press the submit button and like magic, it works there!
I have checked the path, when including the 1st file 100 times. Its correct. I have checked the path when including the databse connection 100 times. Its correct. I have run the query directly in my database. Its correct.
I am assuming that I made a small mistake, that I cant spot, but the code is so small and simple thats just impossible.
<form id="form1" method="post" action="your_php_file.php">
This will point to your php file and proceed the POST request from your front-end to the back-end. According to your code you don't send anything to your php file. So the code you have there may work but your request is never made to your php file, so nothing is put inside the database.
Edit
In order not to reload the page as you requested then you shouldn't submit the form but you must make an ajax call to the backend side.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div id="formDiv">
<input type="text" name="title" placeholder="Title">
<br>
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="group" placeholder="Group">
<br>
<input type="text" name="company" placeholder="Company">
<br>
<select name="sex" required>
<option value="" disabled selected>Sex/option>
<option value="male">male</option>
<option value="female">female</option>
</select>
<br>
<button type="button" id="insert" name="insert">Insert</button>
</div>
<script>
$( "#insert" ).click(function() {
let title = $("input[name=title]").val();
let firstname = $("input[name=firstname]").val();
let lastname = $("input[name=lastname]").val();
let group = $("input[name=group]").val();
let company = $("input[name=company]").val();
let sex = $("input[name=sex] option:selected").text();
$.ajax({
method: 'POST',
url: 'your_php_file.php',
data: {'title': title, 'firstname': firstname, 'lastname': lastname, 'group': group, 'company': company, 'sex': sex},
success: function (response) {
console.log(works)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
})
</script>
That way the data will be send to your backend and you can handle it the same like you did. It's in json format so don't forget to decode if needed.
<div id="formDiv">
<form id="form1" method="post" action="#">
<input type="text" name="title" placeholder="Title">
<br>
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="group" placeholder="Group">
<br>
<input type="text" name="company" placeholder="Company">
<br>
<select name="sex" required>
<option value="" disabled selected>Sex/option>
<option value="0">male</option>
<option value="1">female</option>
</select>
<br>
<button type="submit" id="insert" name="insert">Insert</button>
</form>
</div>
<script>
$('#form1').submit(function (e) {
e.preventDefault();
var senddata = $(this).serializeArray();
var sendto = $(this).attr("action");
$.ajax({
url: sendto,
type: 'POST',
data: senddata,
success: function (data) {
$('.messages').html(data);
},
error: function (error) {
$('.messages').html(error);
}
});
});
</script>

Send html form data to database through php without switching page

Hey guys so i have a form:
<form action="signup.php" method="post" class="cd-form">
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" name="primeiro_nome" />
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="Last Name" name="segundo_nome">
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="email" required maxlength="50" placeholder="E-mail" name="o_email">
</p>
<p class="fieldset">
<input class="full-width" type="submit" value="Sign Up!">
</p>
</form>
And you may notice that the action is calling "signup.php" :
<?php
$con=new mysqli ("localhost","root","","chroniclemark");
mysqli_set_charset($con, 'utf8mb4');
if($con->connect_error)
{
echo $con->connect_errno;
die("Database Connection Failed");
}
if(($_POST['primeiro_nome']) != ""){
$sql = "INSERT INTO users (nome, sobrenome, email)
VALUES('{$con->real_escape_string($_POST['primeiro_nome'])}', '{$con->real_escape_string($_POST['segundo_nome'])}', '{$con->real_escape_string($_POST['o_email'])}')";
$insert = $con->query($sql);
}
?>
And this is working. The data from the form is getting inserted into my database. The problem i have is that the main page closes when the form is submitted and the "signup.php" page opens instead of it.
How do i fix this? I would very much like to have a "Thank you for signing up" popping up on the same page instead of it switching to another one.
You can use AJAX to save data to database and show user a message in same page. Clicking on button a request is sent to server, data is saved into database, on success or failure a response is returned then show a message to user.
Form
First Give ids to input types in you form and add a message div.
<form method="post" class="cd-form">
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" id="primeiro_nome" />
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="Last Name" id="segundo_nome">
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="email" required maxlength="50" placeholder="E-mail" id="o_email">
</p>
<p class="fieldset">
<input class="full-width" id='saverecords' type="button" value="Sign Up!">
</p>
jQuery Code to send AJAX request to server
Add a script tag include jQuery and inside click event get values of fields and then post to php page:
<script src=”http://code.jquery.com/jquery-3.1.1.min.js”></script>
<script type=”text/javascript”>
$(function(){
$("#saverecords").on('click', function(){
var pnome = $("#primeiro_nome").val();
var sname = $("#segundo_nome").val();
var email = $("#o_email").val();
$.ajax({
method: "POST",
url: "saverecords.php",
data: {"pname": pname, "sname": sname, "email": email},
}).done(function( data ) {
var result = $.parseJSON(data);
var str = '';
if(result == 1) {
str = 'Signup successfull.';
}else{
str = 'Data could not be saved. Please try again';
}
$("#message").html(str);
});
});
</script>
php server side code:
Please change it according to your requirement
Create a php page: saverecords.php
In saverecords.php you can insert data into database.
$conn = new mysqli($host, $username, $password, $dbname);
$pname = $_POST['pname'];
$sname = $_POST['sname'];
$email = $_POST['email'];
$sql = "insert into tablename (pname, sname, email) values (?, ?, ?) ";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sss', $pname, $sname, $email);
if($stmt->execute()){
$result = 1;
}
}
echo $result;
$conn->close();
If you still face issue please visit this link you can find a detailed tutorial on how to use jQuery Ajax with php mysqli
You have to use AJAX instead of directly submitting the form
You send POST request with JS XMLHttpRequest or Fetch_API to signup.php, get the response and show the "Thank you for signing up" popup
There are mainly two ways you can do this.
1. You can use Jquery $.ajax method to send data, get a response and display your message.
2. Or you can simply let the php page it self do the processing. Add a submit button.
Change your <form action="signup.php" method="post" class="cd-form">to
<form action="" method="post" class="cd-form">
Add below after the form.
<?php
if (isset($_POST["submit"]){
//do your processing here
//at the end of processing you can use echo or HTML to display a thank you message
}
?>
You can make action page run inside an iframe so your form page remains on top
just like that:
<form action="signup.php" method="post" class="cd-form" target="my_iframe">
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" name="primeiro_nome" />
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="Last Name" name="segundo_nome">
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="email" required maxlength="50" placeholder="E-mail" name="o_email">
</p>
<p class="fieldset">
<input class="full-width" type="submit" value="Sign Up!">
</p>
</form>
<iframe id="my_iframe" name="my_iframe" style="display:none"></iframe>
Also you can send form data to your PHP page by using jquery:
$(document).on('submit','.cd-form',function(e){
e.preventDefault();
$.ajax( {
url: "signup.php",
type: 'POST',
data: new FormData( this ),
cache: false,
dataType: "json",
success: function(r){
alert("data sent successfully");
}
} );
} );

AJAX code not updating table

Here is my form, from which i want to update the values. When i try this with simple php+html it works perfectly!! But when i try to post values through ajax call it doesn't work.Any suggestions please.
HTML
<form class="form-block" role="form" action="" method="post">
<div class="form-group">
<?php
$email=$_SESSION["login_email"];
$query=mysqli_query($con,"select * from customers where email='$email'");
while($row=mysqli_fetch_array($query,MYSQLI_ASSOC))
{
?>
<label for="name">Full Name</label>
<input type="text" name="name" class="form-control" id="name" value="<?= $row["name"]; ?>" placeholder="Full Name">
<label for="comment">Address</label>
<textarea class="form-control" name="address" id="address" rows="5" id="comment" ></textarea>
<label for="telephone">Telephone</label>
<input type="tel" class="form-control" name="phone" id="phone" placeholder="Enter Mobile Number" value="" >
<label for="city">City</label>
<input type="text" class="form-control" name="city" id="city" placeholder="Enter City" value="<?= $row["city"]; ?>" >
</div>
<?php
}?>
<input type="submit" class="btn btn-default" name="add" id="add" value="Update"/>
<span class='msg'></span>
<div id="error"></div>
</form>
AJAX
$(document).ready(function() {
$('#add').click(function()
{
$.ajax({
url: "address_update.php",
type: "POST",
async: true,
data: { Name:$("#name").val(),Address:$("#address").val(), Phone:$("#phone").val(), City:$("#city").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
if(data)
{
//$('#output').html(data);
$("body").load("index.php?page=form");//.hide();//.fadeIn(1500).delay(6000);
}
else
{
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}}});
});});
PHP
<?php
include ("db/db.php");
session_start();
$name=$_POST['Name'];
$address=$_POST['Address'];
$phone=$_POST['Phone'];
$city=$_POST['City'];
$email=$_SESSION['login_email'];
$sql=mysqli_query($con,"Update customers set name='$name',address='$address',phone='$phone',city='$city' where email='$email'");
if($sql)
{
echo "updated";
}
This selector:
$('#add')
doesn't find anything. Because there is no HTML element in your markup with id="add".
You do have an element with name="add". So either add an id to that element:
<input id="add" type="submit" class="btn btn-default" name="add" value="Update"/>
or change your selector to target the existing element:
$('input[name="add"]')
Note: The same is also true of $('#address') and $('#phone'). No such elements exist in your markup. Take a look at the jQuery documentation for selectors.
Remove the IF loop mentioned under
if(isset($_SESSION["login_email"]))
Additionally, you nee to change the button type from submit to button
<input type="submit" class="btn btn-default" name="add" value="Update"/>
Above sends the form, whatever you add to the click event is done in parralel.
<input type="button" class="btn btn-default" name="add" value="Update"/>
only executes your JavaScript, when using:
$('input [name="add"]').click(function(){
// your improved ajax call here
}
Try this:
$.ajax({
.
.
data: {
'Name': $name,
'address': $address,
.
.
}
});

How to use jquery to post dropdown values to another php form

Thank you for your time, I have spent a good part of my day googling every way I can think of and I cant find a clear simple answer. Ive tried everything I can think of and have found great answers here. I sure hope someone can help me. Ive done most of my research on jquery on there site and to no avail I'm still looking for answers. Ive found some help full articles here also, I just must not be fully understanding or am overlooking some simple facts. I'm definitely new to all of this so lets take it nice and easy ! To start I am taking user form data and validating with a php script that will hopefully be talking to a data base and storing form info.
So here are the forms guts:
<form method="post" action="test.php" name="contactform" id="contactform">
<div class="grid_6" id="register">
<center><h4>Required Information</h4></center>
<p>
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</p>
<p>
<label for="email">Your Email:</label>
<input name="email" id="email" type="text" />
</p>
<p>
<label for="trew">Contact Phone:</label>
<input name="txtAreaCode" id="txtAreaCode" style="width: 30px;" maxlength="3" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPrefix" id="txtPrefix" style="width: 30px;" maxlength="3" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPhone" id="txtPhone" style="width: 45px;" maxlength="4" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPhoneExt" id="txtPhoneExt" style="width: 35px;" maxlength="10" value=""type="text">
ext.
</p>
<p>
<label for="zip">Zip Code:</label>
<input name="zip" id="zip" type="text" />
</p>
<p>
<label for="school">Name of School:</label>
<input name="school" id="school" type="text" />
</p>
<p>
<label for="title">Affiliation</label>
<select name="title">
<option selected="NULL">Please Select</option>
<option value="student">Student</option>
<option value="parent">Parent</option>
<option value="teacher">Teacher</option>
<option value="booster">Booster</option>
<option value="clubpres">Club President</option>
<option value="principal">Principal</option>
<option value="ptsa">PTSA</option>
</select>
</p>
</div>
<div class="grid_6" id="contactinfo">
<center><h4>Additional Information</h4></center>
<p>
<label for="color">School Colors:</label>
<input name="color" id="color" type="text" />
</p>
<p>
<label for="mascot">Mascot:</label>
<input name="mascot" id="mascot" type="text" />
</p>
<p>
<label for="tagline">Tagline/Motto:</label>
<input name="tagline" id="tagline" type="text" />
</p>
<p>
<label for="sbsize">Approximate Student Body Size:</label>
<input name="sbsize" id="sbsize" type="text" />
</p>
<p>
<label for="level">Interest Level:</label>
<select name="level">
<option value="1">Interested</option>
<option value="2">Slightly Interested</option>
<option value="3">Moderately Interested</option>
<option value="4">Highly Interested</option>
<option value="5">Extremely Interested</option>
</select>
</p>
<p>
<label for="verify">1 + 3 =</label>
<input name="verify" id="verify" class="small" type="text" />
</p>
<button class="fr" type="submit" id="submit">Send</button>
</form>
</div>
I take this form and make it all pretty with jquery now this is where I am getting the most headache of my life, I spent an hr rewriting from scratch thinking I had syntax errors or something. Come to find out this little gem was the problem, its all good we all make mistakes. Here is the jquery form file, this isn't my project i not even sure if this is needed but here is the source of my problems, Ive figured them all out but 1 (hopefully !).
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(750,function() {
$('#message').hide();
$('#submit')
.after('<img src="./img/form/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
txtAreaCode: $('#txtAreaCode').val(),
txtPrefix: $('#txtPrefix').val(),
txtPhone: $('#txtPhone').val(),
txtPhoneExt: $('#txtPhoneExt').val(),
zip: $('#zip').val(),
school: $('#school').val(),
title: singleValues = $("#title").val(),
color: $('#color').val(),
mascot: $('#mascot').val(),
tagline: $('#tagline').val(),
sbsize: $('#sbsize').val(),
level: $('#level').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#contactform #submit').attr('disabled','');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
});
return false;
});
});
Alright now here is where I see the problem, im trying to get the values of the multiple choice to post to the last and final piece of code my php file that preforms the verification, Ive stripped down the fluff for debugging . But am sure that ive provided more than enough to fix. so here is the php...
<?php
if(trim($_POST['name']) == '') {
echo '<div class="error-message">Attention! You must enter your name.</div>';
exit();
} else {
$name = trim($_POST['name']);
}
if(trim($_POST['email']) == '') {
echo '<div class="error-message">Attention! You must enter your email.</div>';
exit();
} else {
$email = trim($_POST['email']);
}
if(trim($_POST['txtAreaCode']) == '') {
echo '<div class="error-message">Attention! You must enter your txtAreaCode.</div>';
exit();
} else {
$txtAreaCode = trim($_POST['txtAreaCode']);
}
if(trim($_POST['txtPrefix']) == '') {
echo '<div class="error-message">Attention! You must enter your txtPrefix.</div>';
exit();
} else {
$txtPrefix = trim($_POST['txtPrefix']);
}
if(trim($_POST['txtPhone']) == '') {
echo '<div class="error-message">Attention! You must enter your txtPhone.</div>';
exit();
} else {
$txtPhone = trim($_POST['txtPhone']);
}
if(trim($_POST['zip']) == '') {
echo '<div class="error-message">Attention! You must enter your zip.</div>';
exit();
} else {
$zip = trim($_POST['zip']);
}
if(trim($_POST['school']) == '') {
echo '<div class="error-message">Attention! You must enter your school.</div>';
exit();
} else {
$school = trim($_POST['school']);
}
if(trim($_POST['title']) != 'NULL') {
echo '<div class="error-message">Attention! You must enter your title.</div>';
exit();
} else {
$title = trim($_POST['title']);
}
if(trim($_POST['verify']) == '') {
echo '<div class="error-message">Attention! Please enter the verification number.</div>';
exit();
} else if(trim($_POST['verify']) != '4') {
echo '<div class="error-message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
echo 'working';
?>
Now im sure there are many workarounds, I would like to know what I need to do to get this all working. I cant scrap jQuery as its a must for the project, Im sure it should be a simple fix. Fingers crossed as always forgive me for going overboard, i just feel I should let you guys see what my problem is. Ive noticed that if I dont use the 2nd piece of code at all it works wonders, but like i said I need to use it....
From what I gather im clearly doing something wrong in the .post action section as it isnt posting values of the dropdown.
I do a lot of these type forms for my company's application, and there's definitely some shortcuts you can take.
Serialize the data rather than using pure ID's. That way, you don't have to reference EVERY id to submit a form.
Use a validation script on the front end, it'll cut down on the back-end validation you have to worry about reporting back on after the submit. You can't get rid of back end validation, but using a front-end validation tool allows you to quickly and effectively warn the user of a potential problem without the "cost" of a submit. I really like the inline validator script.
If you post your data via an Ajax call rather than just a post, you can use the success callback to deal with issues like validation, success modal windows, etc.
When I do have to do a back-end validation alert, I ususally just make one common alert div at the top of the form and report back to that via the success element of the Ajax call (usually sending JSON) Remember, success on Ajax means the transaction happened, you can still have errors report back through from PHP and have to deal with an error case. By only doing one alert box, I save myself a ton of work and syntax, since most all errors get dealt with on the front end and the back-end is simply redundancy.
So, here's a sample of how I'd do a form on my site:
<div id="error" style="display:none"></div> <!-- error div, hidden -->
<form id="form">
<input type="text" id="name" name="name" class="validator"> <!-- don't forget names! -->
<input type="text" id="name" name="name2" class="validator">
<button id="submit">Send</button>
</form>
<script type="text/javascript">
$('#submit').click(function() { // onclick of submit, submit form via ajax
$.ajax({
url: "url_to_submit_to.php", //url to submit to
timeout: 30000,
type: "POST",
data: $('#form).serialize(), //gets form data, sends via post to processing page
dataType: 'json', //what to do with returned data, in this case, it's json
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown)
},
success: function(outstuff){
if (outstuff.success == 1) { //
alert('success')
} else {
$('#error').html('there is an error, do something');
//Do other stuff
}
}
});
});
</script>
Yes, you should add and id to the drop down menu, otherwise you can't call it as $("#title") in jquery
and in your jquery, it will try to submit when the page loads as you're calling it like
jQuery(document).ready(function(){
Try to change it to $(function(){
Hope it will work
It's weird isn't it, that you've nicely set IDs for all the other items in your form except for your drop downs, where you've only set names.
Forms submit the values of the controls using name, but you're referencing the value in your jquery code using id ('#').
So just try changing your dropdown declarations to have ids... like this:
<form method="post" action="test.php" name="contactform" id="contactform">
<div class="grid_6" id="register">
<center><h4>Required Information</h4></center>
<p>
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</p>
<p>
<label for="email">Your Email:</label>
<input name="email" id="email" type="text" />
</p>
<p>
<label for="trew">Contact Phone:</label>
<input name="txtAreaCode" id="txtAreaCode" style="width: 30px;" maxlength="3" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPrefix" id="txtPrefix" style="width: 30px;" maxlength="3" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPhone" id="txtPhone" style="width: 45px;" maxlength="4" value=""type="text">
<span style="color: rgb(255, 200, 46);"> - </span>
<input name="txtPhoneExt" id="txtPhoneExt" style="width: 35px;" maxlength="10" value=""type="text">
ext.
</p>
<p>
<label for="zip">Zip Code:</label>
<input name="zip" id="zip" type="text" />
</p>
<p>
<label for="school">Name of School:</label>
<input name="school" id="school" type="text" />
</p>
<p>
<label for="title">Affiliation</label>
<select name="title" id="title">
<option selected="NULL">Please Select</option>
<option value="student">Student</option>
<option value="parent">Parent</option>
<option value="teacher">Teacher</option>
<option value="booster">Booster</option>
<option value="clubpres">Club President</option>
<option value="principal">Principal</option>
<option value="ptsa">PTSA</option>
</select>
</p>
</div>
<div class="grid_6" id="contactinfo">
<center><h4>Additional Information</h4></center>
<p>
<label for="color">School Colors:</label>
<input name="color" id="color" type="text" />
</p>
<p>
<label for="mascot">Mascot:</label>
<input name="mascot" id="mascot" type="text" />
</p>
<p>
<label for="tagline">Tagline/Motto:</label>
<input name="tagline" id="tagline" type="text" />
</p>
<p>
<label for="sbsize">Approximate Student Body Size:</label>
<input name="sbsize" id="sbsize" type="text" />
</p>
<p>
<label for="level">Interest Level:</label>
<select name="level" id="level">
<option value="1">Interested</option>
<option value="2">Slightly Interested</option>
<option value="3">Moderately Interested</option>
<option value="4">Highly Interested</option>
<option value="5">Extremely Interested</option>
</select>
</p>
<p>
<label for="verify">1 + 3 =</label>
<input name="verify" id="verify" class="small" type="text" />
</p>
<button class="fr" type="submit" id="submit">Send</button>
</form>
</div>

Categories