I'm new to jQuery and I'm trying to use it to validate a login form. However, the validation script doesn't activate: it just sits there doing nothing, while disabling the submit button. I think it is interfering with another script running on the same form, which lets the user switch between different forms in the same div.
Here's the html:
<div class="box">
<?php if (isset($_SESSION['login'])){ ?>
<h2>Welcome back, <?php echo $_SESSION['username']; ?></h2>
<div><p>Click here to log outt</p></div>
<?php } else { ?>
<div id="form_wrapper" class="form_wrapper">
<div class="register"> <!-- First form -->
<form id="registrationform">
<h2>Register</h2>
<div class="box">
<div>
<label>Name:</label>
<input name="nomeagenzia" type="text" required />
</div>
<!-- Some other input fields -->
<input type="submit" value="Register" />
Already a user? Login here
</div>
</form>
</div>
<div class="login active"> <!-- Second form, the one I'm validating-->
<form id="loginform" action="index.php" method="POST">
<h2>Area Agenzie</h2>
<div class="box">
<div>
<label>Username:</label>
<input name="username" type="text" />
</div>
<div style="position:relative;">
<label>Password:</label>
Forgot your password?
<input name="password" type="password" />
</div>
<input name="submit" type="submit" value="Login" />
Register here!
</div>
</form>
</div>
<!-- There's a third form I omitted -->
</div>
<?php } ?>
</div>
Here is the javascript to switch between the forms:
$(function() {
var $form_wrapper = $('#form_wrapper'),
$currentForm = $form_wrapper.children('div.active'),
$linkform = $form_wrapper.find('.linkform');
$form_wrapper.children('div').each(function(i){
var $theForm = $(this);
if(!$theForm.hasClass('active'))
$theForm.hide();
$theForm.data({
width : $theForm.width(),
height : $theForm.height()
});
});
setWrapperWidth();
$linkform.bind('click',function(e){
var $link = $(this);
var target = $link.attr('rel');
$currentForm.fadeOut(100,function(){
$currentForm.removeClass('active');
$currentForm= $form_wrapper.children('div.'+target);
$form_wrapper.stop()
.animate({
width : $currentForm.data('width') + 'px',
height : $currentForm.data('height') + 'px'
},225,function(){
$currentForm.addClass('active');
$currentForm.fadeIn(100);
});
});
e.preventDefault();
});
function setWrapperWidth(){
$form_wrapper.css({
width : $currentForm.data('width') + 'px',
height : $currentForm.data('height') + 'px'
});
}
});
Here's the validation script:
$(document).ready(function()
{
$("#loginform").validate(
{
rules:{
'username':{
required: true,
remote:{
url: "php/validatorAJAX.php",
type: "post"
}
},
'password':{
required: true
}
},
messages:{
'username':{
required: "Il campo username è obbligatorio!",
remote: "L'username non esiste!"
},
'password':{
required: "Il campo password è obbligatorio!"
}
},
submitHandler: function(form){
if($(form).valid())
form.submit();
return false;
}
});
});
Finally, this is validatorAJAX.php included in the validation script:
<?php
$mysqli = new mysqlc();
function usernameExists($username){
$username = trim($username);
$stmt = $mysqli->prepare("SELECT COUNT(*) AS num FROM utenti WHERE username= ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($result);
$result = (bool)$stmt->fetch();
$stmt->close();
return $result;
}
if(isset($_POST['username'])){
if(usernameExists($_POST['username'])){
echo 'true';
}else{
echo 'false';
}
}
?>
You can test out the script at http://pansepol.com/NEW, and you'll see that nothing happens when you click "Submit" on the login_form. Moreover, no validation is done whatsoever. I'm going nuts here :)
I fixed it: there was a problem with the validatorAJAX.php, which causes the whole form to crash. Basically the mysqli object was initialized outside the function, and this caused the validation to fail.
Related
I have this script that allows me to send data to the database without reloading the page. The form data is sent to file process.php.
At the end of the process, inside the div box of the form is printed a notice that everything went ok
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '.formValidation', function(){
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'submit.php',
data : data,
success : function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
});
return false;
});
});
</script>
Page success.php:
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
}
print "ok";
And the div box for the notice <div class="result"></div>
The problem: I have many div box with a form and when I print the notice of success, it happen into all the <div>, because the call notification is always .result
success: function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
What I want: Print the success notice in its own div depending on the form that I sent.
Thanks
EDIT: The html interested
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form> <!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
<?php
$comune = "SELECT * FROM tbl_comune ORDER BY nome_comune ASC";
$result_comune = dbQuery($comune);
if (dbNumRows($result_comune) > 0) {
while($row_comune = dbFetchAssoc($result_comune)) {
extract($row_comune);
?>
<option value="<?php echo $id_comune; ?>"><?php echo $nome_comune; ?></option>
<?php
}
} else {
?>
<option value="">Non ci sono dati</option>
<?php
}
?>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
If the form is in a div and the result is next to the form, you can do sibling:
$form.next(".result").html(data);
or elsewhere in the same parent:
$form.parent().find(".result").html(data);
or in your case
$form.find(".result").html(data);
Like this - note I have removed all the unnecessary hiding.
$(function() {
$(document).on('submit', '.formValidation', function(e) {
e.preventDefault();
var data = $(this).serialize();
$form = $(this); // save a pointer to THIS form
$result = $form.find(".result");
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
success: function(data) {
$result.html(data);
$form.fadeOut(500, function() {
$result.fadeIn(500)
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
Question: I can see that the data is getting written to the database but $action doesn't become register in the insert.php call from the html file and hence php JSON return is NULL ??
<!DOCTYPE html>
<html>
<head>
<title>Load </title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
Register
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="registerp">
<div data-theme="a" data-role="header">
<h3>Register</h3>
</div>
<div data-role="content">
<form id="registerform" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="fname">First Name:</label>
<input type="text" value="" name="fname" id="fname"/>
</div>
<div data-role="fieldcontain">
<label for="lname">Last Name:</label>
<input type="text" value="" name="lname" id="lname"/>
</div>
<div data-role="fieldcontain">
<label for="uname">User Name:</label>
<input type="text" value="" name="uname" id="uname"/>
</div>
<div data-role="fieldcontain">
<label for="pwd">Enter your password:</label>
<input type="password" value="" name="pwd" id="pwd"/>
</div>
<div data-role="fieldcontain">
<label for="email">Email:</label>
<input type="text" value="" name="email" id="email"/>
</div>
<input type="button" data-theme="b" name="submit" id="register" value="Register">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3>Welcome Page</h3>
</div>
<div data-role="content">
Welcome
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<script type="text/javascript">
$(document).on('pageinit', '#login', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: "action=login&" + $('#check-user').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert('Log on unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
<script type="text/javascript">
$(document).on('pageinit', '#registerp', function(){
$(document).on('click', '#register', function() {
if($('#uname').val().length > 0 && $('#pwd').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'insert.php',
data: "action=register&" + $('#registerform').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert(' Try again later ! Server is busy !');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
</body>
</html>
While my PHP Script is simple as shown below... please help
<?php
$con=mysqli_connect("...............", "...........", ".........","........");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$lname = mysqli_real_escape_string($con, $_POST['lname']);
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['pwd']);
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES ('$uname', '$fname', '$lname', '$password','$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
if($action == 'register'){
$output = array('status' => true, 'message' => 'Registered');
}
echo json_encode($output);
?>
Insert php script doesnt work while the below register php script works fine.
<?php
// We don't need action for this tutorial, but in a complex code you need a way to determine Ajax action nature
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
// Get username
$username = $_POST['username'];
// Get password
$password = $_POST['password'];
$db = #mysql_connect('..........', '........', '..........') or die("Could not connect database");
#mysql_select_db('users', $db) or die("Could not select database");
$result = mysql_query("SELECT `password` FROM `userdb` WHERE `username`= '$username'");
$r = mysql_fetch_assoc($result);
$pass_ret = $r['password'];
// Lets say everything is in order
if($action == 'login' && $password == $pass_ret){
$output = array('status' => true, 'message' => 'Login');
}
else
{
$output = array('status' => false, 'message' => 'No Login');
}
echo json_encode($output);
?>
You should use Chrome Dev Tools or Firebug in Firefox to inspect the response from the AJAX call. You set the call to expect JSON as the data type and you also use it as JSON. The problem is you have this line:
echo "1 record added";
Which is output before your JSON. So your response probably looks something like:
1 record added{"status": false, "message": "No Login"}
This isn't valid JSON and it will not parse, and thusly this line will never work:
if(result.status) {
I am not able to write to db when creating new registrations.... ! I have a javascript which has both login and register parts and is shown below... This the updated version of the code for both the scripts and the php scripts for login anc
<!DOCTYPE html>
<html>
<head>
<title>Load </title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
Register
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="registerp">
<div data-theme="a" data-role="header">
<h3>Register</h3>
</div>
<div data-role="content">
<form id="registerform" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="fname">First Name:</label>
<input type="text" value="" name="fname" id="fname"/>
</div>
<div data-role="fieldcontain">
<label for="lname">Last Name:</label>
<input type="text" value="" name="lname" id="lname"/>
</div>
<div data-role="fieldcontain">
<label for="uname">User Name:</label>
<input type="text" value="" name="uname" id="uname"/>
</div>
<div data-role="fieldcontain">
<label for="pwd">Enter your password:</label>
<input type="password" value="" name="pwd" id="pwd"/>
</div>
<div data-role="fieldcontain">
<label for="email">Email:</label>
<input type="text" value="" name="email" id="email"/>
</div>
<input type="button" data-theme="b" name="submit" id="register" value="Register">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3>Welcome Page</h3>
</div>
<div data-role="content">
Welcome
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<script type="text/javascript">
$(document).on('pageinit', '#login', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: "action=login&" + $('#check-user').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert('Log on unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
<script type="text/javascript">
$(document).on('pageinit', '#registerp', function(){
$(document).on('click', '#register', function() {
if($('#uname').val().length > 0 && $('#pwd').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'insert.php',
data: "action=register&" + $('#registerform').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert(' Try again later ! Server is busy !');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
</body>
</html>
While my PHP Script is simple as shown below... please help
<?php
$con=mysqli_connect("...............", "...........", ".........","........");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$lname = mysqli_real_escape_string($con, $_POST['lname']);
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['pwd']);
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES ('$uname', '$fname', '$lname', '$password','$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
if($action == 'register'){
$output = array('status' => true, 'message' => 'Registered');
}
echo json_encode($output);
?>
Insert php script doesnt work while the below register php script works fine.
<?php
// We don't need action for this tutorial, but in a complex code you need a way to determine Ajax action nature
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
// Get username
$username = $_POST['username'];
// Get password
$password = $_POST['password'];
$db = #mysql_connect('..........', '........', '..........') or die("Could not connect database");
#mysql_select_db('users', $db) or die("Could not select database");
$result = mysql_query("SELECT `password` FROM `userdb` WHERE `username`= '$username'");
$r = mysql_fetch_assoc($result);
$pass_ret = $r['password'];
// Lets say everything is in order
if($action == 'login' && $password == $pass_ret){
$output = array('status' => true, 'message' => 'Login');
}
else
{
$output = array('status' => false, 'message' => 'No Login');
}
echo json_encode($output);
?>
The way you are using the insert statement is wrong..and its wrongly encapsulated as #rbcummings said.
You must change
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES ('$uname', '$fname', '$lname', '$password','$email')";
to
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES (".$uname.", ".$fname.", ".$lname.", ".$password.",".$email.")";
without proper intentation you can get errors..so intending ur code can solve ur problem.
Try changing the way your variables are encapsulated. Example:
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES (".$uname.", ".$fname.", ".$lname.", ".$password.",".$email.")";
I'm doing a simple ajax update record.
Here's my code
index.php:
<script type="text/javascript">
$("#submit_button").click( function() {
$.post( $("#updateprofile").attr("action"),
$("#updateprofile :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
$("#updateprofile").submit( function() {
return false;
});
function clearInput() {
$("#updateprofile :input").each( function() {
$(this).val('');
});
}
</script>
<form class="form" id="updateprofile" action="edit-profile.php" method="POST">
<!-- form-horizontal -->
<div class="control-group">
<label class="control-label" for="inputName">Name</label>
<div class="controls">
<input type="text" class="input-block-level" name="fname"
value="<?php echo $fname; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input type="text" class="input-block-level"
value="<?php echo $password; ?>" name="password" >
<input type="hidden" name="id"
value="<?php echo $user; ?>" >
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-custom" type="submit" id="submit_button">Update</button>
<button class="btn btn-custom" type="reset" >Cancel</button>
</div>
</div>
</form>
<span id="result"></span>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
edit-profile.php:
<?php
include('../../db.php');
if( isset($_POST['id']) || isset($_POST['fname']) || isset($_POST['password']) ){
$id = $_POST['id'];
$fname = $_POST['fname'];
$password = $_POST['password'];
$update = $conn->prepare("UPDATE tblusers
SET fname = :fname,
password = :password
WHERE user_id = :id");
$update->execute(array(':fname' => $fname,
':password' => $password,
':id' => $id));
echo 'Successfully updated record!';
} else {
echo 'Required field/s is missing';
}
?>
But I'm not getting the update without refreshing the page or going to other page. Any ideas? Help is much appreciated. Thanks.
Try this, You have missed add ready handler and Added e.preventDefault(); When you trigger the submit button, it uses the default form action page
$(function(){
console.log("Jquery Loaded!!"); // alert("jquery loaded!");
$("#submit_button").click( function(e) {
e.preventDefault();
$.post( $("#updateprofile").attr("action"),
$("#updateprofile :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
});
Use Lateset version of jquery library.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Bind your functions in $(document).ready() function
Your form is being submitted because your $("#submit_button") if of type submit, which means that when your ajax executes (it executes ok) but your form is also submitted.
To stop form from being submitted, you can add
<form onSubmit="return false;">
To your HTML. Or you can also use:
<form onSubmit="return func();">
If func() returns false, form will not be submitted.
First add you script file for including jQuery in starting and put the functions as stated below
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit_button").click( function() {
$.post( $("#updateprofile").attr("action"), $("#updateprofile :input").serializeArray(),function(info){
$("#result").html(info);
});
clearInput();
});
$("#updateprofile").submit( function() {
return false;
});
});
function clearInput() {
$("#updateprofile :input").each( function() {
$(this).val('');
});
}
</script>
and you are sorted
I am using jquery serialize and Ajax to capture form values and process them with Ajax using json as data Type, but no values are being returned. I have tried various ways to try and see why this is happening, but to no avail. There is no errors being returned in firebug or chrome. I would be grateful if someone could check my code and point out my error. Thanks
html code
<!--- Form to add box -->
<div id="boxaddform" style="display:none;">
<div class="dialogTop_padd"></div>
<form id="BA_boxform" name="BA_boxform" method="post">
<fieldset>
<legend><span></span>Select Company</legend>
<div class="spacer"></div>
<div class="formMessage">Click again to open</div>
<div class="fld_fld">
<div>
<label for="BA_customer">Company:</label><br />
<select name="BA_customer" id="BA_customer">
<option SELECTED VALUE="">Select a Company</option>
<?php
do {
?>
<option value="<?php echo $row_Recordsetcust['customer']?>"><?php echo $row_Recordsetcust['customer']?></option>
<?php
}
while ($row_Recordsetcust = mysql_fetch_assoc($Recordsetcust));
$rows = mysql_num_rows($Recordsetcust);
if($rows > 0)
{
mysql_data_seek($Recordsetcust, 0);
$row_Recordsetcust = mysql_fetch_assoc($Recordsetcust);
}
?>
</select>
<div class="spacer"></div>
<!--- displays the address and dept from the change function -->
<div id="BA_dept"></div>
<br />
<div id="BA_address"></div>
</div>
</fieldset>
<div class="dialogTop_padd"></div>
<!--- fieldset for service level -->
<fieldset>
<legend>Service Level</legend>
<div class="spacer"></div>
<div>
<label for="BA_service">Service level:</label>
<select name="BA_service" id="BA_service">
<option SELECTED VALUE="">Select an option</option>
<option value="Standard">Standard</option>
<option value="Rapid">Rapid</option>
</select><br />
</div>
</fieldset>
<div class="dialogTop_padd"></div>
<!--- fieldset for box # -->
<fieldset>
<legend>Box Details</legend>
<div class="spacer"></div>
<div>
<label for="BA_box">Box#:</label><br />
<input id="BA_box" name="BA_box" type="text" size="32" maxlength="128" value = "" /><br />
</div>
<div>
<label for="BA_destdate">Destroy date:</label>
<input id="BA_destdate" name="BA_destdate" type="text" size="32" maxlength="128" value = "" /><br />
</div>
</fieldset>
<div class="dialogTop_padd"></div>
<!--- fieldset for authorisation -->
<fieldset>
<legend>Authorisation</legend>
<div class="spacer"></div>
<div>
<label for="BA_authorised">Requested By:</label>
<input id="BA_authorised" name="BA_authorised" type="text" value="<?php echo $_SESSION['kt_name_usr']; ?>"><br />
</div>
</fieldset>
<!--- div to show callback result from ajax via dialog -->
<div id="BA_addbox"></div>
<br />
<input type="submit" name="submit" value="Submit Intake" />
<input type="reset" name="cancel" value="Clear Form" />
<!--- buttons to submit form and reset form to default status -->
<!-- <button id="BA_submit" class="submitbutton icon-right ui-state-default2 ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Add Box</button>
<button type="reset" id="BA_reset" class="resetbutton icon-right ui-state-default2 ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Reset</button>
--><br />
</form>
</div>
jquery code
$(function() {
$("#BA_customer").live('change', function() {
if($(this).val()!="")
$.get("/domain/admin/getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data).show();
});
$.get("/domain/admin/getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data).show();
});
});
});
//Begin function to submit box intake form
$(function() { // Function to add box
$("#boxaddform").dialog({
autoOpen: false,
resizable: false,
modal: true,
title: 'Submit a box intake request',
width: 550,
height: 400,
beforeclose: function (event, ui) {
$("#BA_addbox").html("");
$("#BA_dept").hide();
$("#BA_address").hide();
},
close: function (event, ui) {
//$("#BA_boxform").get(0).reset();
$("#BA_addbox").html("");
}
});
});
$(function(){
$("#boxaddform").submit(function(){
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "/domain/admin/requests/boxes/boxesadd.php",
data: formdata,
dataType: 'json',
success: function(msg){
//$("#confirm_department").hide();
/*
var $dialog = $('<div id="dialog"></div>')
.html('Your intake was successfully submitted and will be viewable in the reporting area.<br /><br />Thank you.');
$dialog.dialog({
autoOpen: true,
modal: true,
title: 'Box intake submission successfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function() {
$( this ).dialog( "close" );
}
}
});
*/
//alert('You have succesfully submitted your ' + msg.company + ' report. Thank you.');
//console.log(msg);
//$("#BA_addbox").html("You may now close this window.");
//$("#formImage .col_1 li").show();
$("#BA_boxform").get(0).reset();
$("#boxaddform").hide();
}
});
return false;
});
});
// End function to submit box intake form
php code
<?php
$dept = mysql_real_escape_string($_POST['BA_dept']);
$company = mysql_real_escape_string($_POST['BA_customer']);
$address = mysql_real_escape_string($_POST['BA_address']);
$service = mysql_real_escape_string($_POST['BA_service']);
$box = mysql_real_escape_string($_POST['BA_box']);
$destroydate = mysql_real_escape_string($_POST['BA_destdate']);
$authorised = mysql_real_escape_string($_POST['BA_authorised']);
$form = array('dept'=>$dept, 'company'=>$company, 'address'=>$address, 'service'=>$service, 'box'=>$box, 'destroydate'=>$destroydate, 'authorised'=>$authorised);
$result = json_encode($form);
echo $result;
?>
The problem in your code is that you are serializing a DIV, what is incorrect.
The solution would be to serialize only the FORM included in your DIV with a Javascript code like:
...
$(function(){
$("#boxaddform").submit(function(){
var formdata = $('#BA_boxform').serialize();
$.ajax({
type: "POST",
url: "/domain/admin/requests/boxes/boxesadd.php",
data: formdata,
dataType: 'json',
success: function(msg){
...
}
});
return false;
});
....
Also, remember that serialize will only care for INPUT, SELECTand TEXTAREA controls as a normal FORM submit would do (http://api.jquery.com/serialize/).