JQUERY validation plugin + AJAX + PHP not working - php

I recently started learning AJAX for form submitting, but it seems that i'm still missing something essential, because the submitted data won't go to the PHP file like it's suppose to. I don't understand why it won't work.
HTML:
<div class="col-md-6">
<form class="form" action="../wp-content/themes/tempo/cfgs/js/scrollmagic/contact.php">
Eesnimi:
<input name="eesnimi" id="eesnimi" class="required" type="text">
Perekonnanimi:
<input name="pernimi" id="pernimi" class="required" type="text">
E-Post:
<input name="email" id="email" class="required" type="email">
Telefoni number:
<input name="nr" id="nr" class="required" type="text">
Teema:
<input name="teema" id="teema" class="required" type="text">
Sõnumi sisu:
<textarea name="sisu" id="sisu" class="required"></textarea>
<div></div>
<input type="submit" id="sub" value="Edasta">
</form>
</div>
JQUERY/AJAX
$('#sub').click(function(){
$('.form').submit();
var eesnimi = $('#eesnimi').val();
var pernimi = $('#pernimi').val();
var email = $('#email').val();
var nr = $('#nr').val();
var teema = $('#teema').val();
var sisu = $('#sisu').val();
$('.form').validate({
rules:{
eesnimi: {
required: true,
nowhitespace: true,
lettersonly: true
},
pernimi: {
required: true,
nowhitespace: true,
lettersonly: true
},
email: {
required: true,
email: true
},
nr: {
required: false,
integer: true
},
teema: {
required: true
},
sisu: {
required: true
}
},
messages:{
eesnimi: {
required: valituhiErr,
nowhitespace: tuhikErr,
lettersonly: nonumbersErr
},
pernimi: {
required: valituhiErr,
nowhitespace: tuhikErr,
lettersonly: nonumbersErr
},
email: {
required: valituhiErr,
email: emailErr
},
nr: {
required: valituhiErr,
integer: onlynumbersErr
},
teema: {
required: valituhiErr,
},
sisu: {
required: valituhiErr,
}
},
submitHandler: function(){
$.ajax({
type: "POST",
url: "../wp-content/themes/tempo/cfgs/js/scrollmagic/contact.php",
data: $('.form').serialize(),
success: function (o) {
console.log(o);
}
});
}
});
return false;
});
PHP:
<?php
print_r($_POST);
?>
I'm just experimenting, it seems that validation works correctly but the submit function won't, beceause the server won't recieve anything from my ajax request and it won't display anything on console either.

try this : jquery
var data = {
eesnimi = $('#eesnimi').val();
pernimi = $('#pernimi').val();
email = $('#email').val();
nr = $('#nr').val();
teema = $('#teema').val();
sisu = $('#sisu').val();
};
$.ajax({
type : "post",
dataType : "JSON",
url : "register.php",
data : data,
success : function(result)
{
if (result.hasOwnProperty('error') && result.error == '1'){
var html = '';
$.each(result, function(key, item){
if (key != 'error'){
html += '<li>'+item+'</li>';
}
});
//show in html
php
eesnimi = $_POST['eesnimi']
pernimi = ...
email =...
nr = ...
teema = ...
sisu = ...
//connect db
//sqlquery you want validate
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
if ($row['eesnimi']==$eesnimi ){
$errors['eesnimi '] = ...;
}
// like this
if (count($errors) > 1){
$errors['error'] = 1;
die (json_encode($errors));
}
//insert into db
}
hope this help

Related

How to insert only one record in the database on multiple clicks on submit button

I am using CodeIgniter. I have a form and fields are Name, Email, Mobile no, Message.
I am able to submit the data in the database using AJAX. There is no issue with AJAX.
Now What I did, I fill the form and click on submit button twice then I check my database and I found the same records twice because of two clicks. If I click three times on the submit button then I am getting same records three times in the database.
Is there any way to stop this issue. Like one click should work on submit button till the data submitting in the database?
View
<div class="i_p_aboutTeam_alert" id="popup_verify-1" style="display: none;">
<div class="profile_content">
<div class="profile_header clearfix">
<i class="fas fa-times"></i>
</div>
<div class="profile_body">
<div class="form_heading">
<h2>CONTACT FORM</h2>
</div>
<form action="" method="post" name="form" id="form" autocomplete="off">
<div class="form-group ffl-wrapper">
<label for="name" class="ffl-label">Name</label>
<input type="text" name="name" class="form-control" id="name">
</div>
<div class="form-group ffl-wrapper">
<label for="mobileno" class="ffl-label">Mobile Number</label>
<input type="text" name="mobileno" class="form-control" id="mobileno">
</div>
<div class="form-group ffl-wrapper">
<label for="email" class="ffl-label">Email</label>
<input type="email" name="email" class="form-control" id="email">
</div>
<div class="form-group ffl-wrapper">
<label for="message" class="ffl-label">Message</label>
<textarea class="form-control" name="message" id="message"></textarea>
</div>
<div class="form-group text-center">
<input type="submit" name="send" class="i_btn i_btn_bg i_btn_round w_100p" value="Submit">
</div>
</form>
</div>
</div>
</div>
AJAX
$("#form").validate({
rules: {
name: {
required: true,
minlength: 3,
lettersonly: true
},
mobileno: {
required: true,
minlength: 10,
maxlength: 10,
number: true
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 10
}
},
submitHandler: function(form) {
//form.submit();
$.ajax({
url: "<?php echo base_url('Home_control/contact');?>",
type: "POST",
data: $('#form').serialize(),
success: function(data) {
$("#popup_verify-1").hide();
$("#popup_success-1").show();
},
}); // AJAX Get Jquery statment
}
});
Controller
public function contact() {
$this -> form_validation -> set_error_delimiters('<div class="error">', '</div>');
$this -> form_validation -> set_rules('name', 'Name', 'trim|required|min_length[3]');
$this -> form_validation -> set_rules('mobileno', 'Mobile no', 'trim|required|regex_match[/^[0-9]{10}$/]');
$this -> form_validation -> set_rules('email', 'email', 'required|valid_email');
$this -> form_validation -> set_rules('message', 'Message', 'required');
if ($this -> form_validation -> run() == FALSE) {
//$this->index();
} else {
$form_data = array(
'name' => $this -> input -> post('name', TRUE),
'mobileno' => $this -> input -> post('mobileno', TRUE),
'email' => $this -> input -> post('email', TRUE),
'message' => $this -> input -> post('message', TRUE)
);
$success = $this -> db -> insert('form', $form_data);
echo json_encode(array("data" => $success)); // return to the ajax
}
}
maintain flag for request in progress
<script type="text/javascript">
var isReqInprogress = false;
$("#form").validate({
rules: {
name: {
required: true,
minlength: 3,
lettersonly: true
},
mobileno: {
required: true,
minlength: 10,
maxlength: 10,
number: true
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 10
}
},
submitHandler: function(form) {
//form.submit();
if(isReqInprogress){
return;
}
isReqInprogress = true;
$.ajax({
url: "<?php echo base_url('Home_control/contact');?>",
type: "POST",
data: $('#form').serialize(),
success: function(data) {
$("#popup_verify-1").hide();
$("#popup_success-1").show();
isReqInprogress = false;
},
}); // AJAX Get Jquery statment
}
});
</script>
Here is the AJAX code that you can use:
Solution 1: If you want to disable the submit button click until AJAX call is complete.
$.ajax({
type: "POST",
url: "<?php echo base_url('Home_control/contact');?>",
data: $('#form').serialize(),
beforeSend: function() {
$('#form').find("input[type='submit']").prop('disabled', true); // disable button
},
success:function(data){
$("#popup_verify-1").hide();
$("#popup_success-1").show();
$('#form').find("input[type='submit']").prop('disabled', false); // enable button
}
});
Solution 2: If you don't want to disable the submit button but prevent AJAX call from being used multiple times.
$("#form").validate({
var isCurrentReqInprogress = false;
...
...
submitHandler: function(form) {
//form.submit();
if(isCurrentReqInprogress){
return;
}
isCurrentReqInprogress = true;
$.ajax({
url: "<?php echo base_url('Home_control/contact');?>",
type: "POST",
data: $('#form').serialize(),
success: function(data) {
$("#popup_verify-1").hide();
$("#popup_success-1").show();
isCurrentReqInprogress = false;
},
}); // AJAX Get Jquery statment
}
});

i want to log in a user with enter key

I want to log in a user by pressing the enter key. when I press the enter key it clears the form value. and by clicking with the mouse on the sign in button it allows the user to log in and redirect on the home page.
here is my login.min.js
var Login = function () {
var e = function () {
$(".login-form").validate({
errorElement: "span",
errorClass: "help-block",
focusInvalid: !1,
rules: {username: {required: !0}, password: {required: !0}, remember: {required: !1}},
messages: {username: {required: "Username is required."}, password: {required: "Password is required."}},
invalidHandler: function (e, r) {
$(".alert-danger", $(".login-form")).show()
},
highlight: function (e) {
$(e).closest(".form-group").addClass("has-error")
},
success: function (e) {
e.closest(".form-group").removeClass("has-error"), e.remove()
},
errorPlacement: function (e, r) {
e.insertAfter(r.closest(".input-icon"))
},
submitHandler: function (e) {
e.submit()
}
}), $(".login-form input").keypress(function (e) {
return 13 == e.which ? ($(".login-form").validate().form() && $(".login-form").submit(), !1) : void 0
})
}, r = function () {
$(".forget-form").validate({
errorElement: "span",
errorClass: "help-block",
focusInvalid: !1,
ignore: "",
rules: {email: {required: !0, email: !0}},
messages: {email: {required: "Email is required."}},
invalidHandler: function (e, r) {
},
highlight: function (e) {
$(e).closest(".form-group").addClass("has-error")
},
success: function (e) {
e.closest(".form-group").removeClass("has-error"), e.remove()
},
errorPlacement: function (e, r) {
e.insertAfter(r.closest(".input-icon"))
},
submitHandler: function (e) {
e.submit()
}
}), $(".forget-form input").keypress(function (e) {
return 13 == e.which ? ($(".forget-form").validate().form() && $(".forget-form").submit(), !1) : void 0
}), jQuery("#forget-password").click(function () {
jQuery(".login-form").hide(), jQuery(".forget-form").show()
}), jQuery("#back-btn").click(function () {
jQuery(".login-form").show(), jQuery(".forget-form").hide()
})
}, i = function () {
function e(e) {
if (!e.id)return e.text;
var r = $('<span><img src="../assets/global/img/flags/' + e.element.value.toLowerCase() + '.png" class="img-flag" /> ' + e.text + "</span>");
return r
}
jQuery().select2 && $("#country_list").size() > 0 && ($("#country_list").select2({
placeholder: '<i class="fa fa-map-marker"></i> Select a Country',
templateResult: e,
templateSelection: e,
width: "auto",
escapeMarkup: function (e) {
return e
}
}), $("#country_list").change(function () {
$(".register-form").validate().element($(this))
})), $(".register-form").validate({
errorElement: "span",
errorClass: "help-block",
focusInvalid: !1,
ignore: "",
rules: {
fullname: {required: !0},
email: {required: !0, email: !0},
address: {required: !0},
city: {required: !0},
country: {required: !0},
username: {required: !0},
password: {required: !0},
rpassword: {equalTo: "#register_password"},
tnc: {required: !0}
},
messages: {tnc: {required: "Please accept TNC first."}},
invalidHandler: function (e, r) {
},
highlight: function (e) {
$(e).closest(".form-group").addClass("has-error")
},
success: function (e) {
e.closest(".form-group").removeClass("has-error"), e.remove()
},
errorPlacement: function (e, r) {
"tnc" == r.attr("name") ? e.insertAfter($("#register_tnc_error")) : 1 === r.closest(".input-icon").size() ? e.insertAfter(r.closest(".input-icon")) : e.insertAfter(r)
},
submitHandler: function (e) {
e[0].submit()
}
}), $(".register-form input").keypress(function (e) {
return 13 == e.which ? ($(".register-form").validate().form() && $(".register-form").submit(), !1) : void 0
}), jQuery("#register-btn").click(function () {
jQuery(".login-form").hide(), jQuery(".register-form").show()
}), jQuery("#register-back-btn").click(function () {
jQuery(".login-form").show(), jQuery(".register-form").hide()
})
};
return {
init: function () {
e(), r(), i()
}
}
}();
jQuery(document).ready(function () {
Login.init()
});
and my login_form.tpl
<body class=" login">
<!-- BEGIN LOGO -->
<div class="logo">
<a href="#">
<img src=" {$site_root}application/views/admin/assets/layouts/layout/img/logo.png"
alt="logo" /> </a>
</div>
<!-- END LOGO -->
<!-- BEGIN LOGIN -->
<div class="content">
<!-- BEGIN LOGIN FORM -->
<form class="login-form" action="{$data.action}" method="post">
<h3 class="form-title font-green">Sign In</h3>
<div class="alert alert-danger display-hide" style='display:{if $error != ''}block{/if}'>
<button class="close" data-close="alert"></button>
<span> {if $error != ''}{$error}{else}Enter any username and password.{/if}</span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">{l i='field_nickname' gid='ausers'}</label>
<input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="nickname" /> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">{l i='field_password' gid='ausers'}</label>
<input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" /> </div>
<div class="form-actions">
<input type="submit" name="btn_login" value="{l i='btn_login' gid='start' type='button'}" class="btn green uppercase btn-block">
</div>
</form>
i have tried different solutions but did'nt succeed.
$('.form-group').keydown(function() {
var key = e.which;
if (key == 13) {
$('.form-group').submit();
}
});
Thank you for your help but finally, I find the solution I just needed to make some changes.
$("input").keypress(function (e) {
if (e.which == 13) {
$('input[name="btn_login"]').click();
return false;
}

jQuery Validation - Remote function with additional data

I am having issues with validating some data.
I want to check if someone has reviewed a company before by checking for the company_id and the logged in users account_number in my reviews table.
The code I currently has doesn't ever seem to find anything in the reviews table so doesn't warn people they can't submit another review.
Your help to get this working is much appreciated.
Here is the code I have so far:
Form
<form name="review" id="review" method="post" action="/db_processing/reviews/process-reviews.php">
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" />
<input type="hidden" value="<?php echo($_SESSION["ID"]) ?>" name="account_number" />
<p class="cs-threequarter">
<b>Comments:</b><br>
<textarea name="comments" style="width:95%; height: 150px"></textarea>
</p>
<p class="cs-quarter">
<b>Rating:</b>
<span class="star-rating">
<input type="radio" name="rating" value="1"><i></i>
<input type="radio" name="rating" value="2"><i></i>
<input type="radio" name="rating" value="3"><i></i>
<input type="radio" name="rating" value="4"><i></i>
<input type="radio" name="rating" value="5"><i></i>
</span>
</p>
<p><input class="cs-btn cs-red" name="submit" type="submit" value="Submit Review!"></p>
<div class="cs-container"></div>
<div class="cs-error-note" id="cs-error-note3"></div>
</form>
<script src="/js/validation/reviewval.js"></script>
jQuery Validation Script
$(document).ready(function () {
$('#review').validate({
errorLabelContainer: "#cs-error-note3",
wrapper: "li",
ignore: "not:hidden",
rules: {
comments: {
required: true
},
account_number: {
required: true,
remote: {
url: "/db_processing/reviews/check-account.php",
type: "post",
data: {
company_id: function() {
return $("#company_id").val();
}
}, }
},
rating: {
required: true
}
},
messages: {
comments: {
required: "Please enter some comments."
},
account_number: {
required: "You must be logged in to review.",
remote: "You have already reviewed this company."
},
rating: {
required: "Please select a rating."
}
},
submitHandler: function(form) {
form.submit();
}
});
});
Check-account.php
<?php
require('../../../private_html/db_connection/connection.php');
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
if(isset($_POST['account_number'])) {
$account_number = $_POST['account_number'];
$compid = $_POST['company_id'];
$query = $conn->prepare("SELECT account_number FROM reviews WHERE account_number =$account_number && company_id =$compid");
$query->execute();
$rows = $query->fetchAll();
$total_rows = count($rows);
if( $total_rows > 0 ){
echo 'false';
} else {
echo 'true';
}
}
?>
Validation code working fine, there is no problem expect unnecessary comma ,. remove it, Not all browsers are very forgiving.
$(document).ready(function () {
$('#review').validate({
errorLabelContainer: "#cs-error-note3",
wrapper: "li"
ignore: "not:hidden",
rules: {
comments:
required: true
},
account_number: {
required: true,
remote: {
url: "/db_processing/reviews/check-account.php",
type: "post",
data: {
company_id: function() {
return $("#company_id").val();
}
}, //<-----Remove this, it's unnecessary
}
},
rating: {
required: true
}
},
messages: {
comments: {
required: "Please enter some comments."
},
account_number: {
required: "You must be logged in to review.",
remote: "You have already reviewed this company."
},
rating: {
required: "Please select a rating."
}
},
submitHandler: function(form) {
form.submit();
}
});
});
HTML
The problem is here, because of it validation and query both failing.
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" />
assign id to this input because you are fetching it's value with id selector in validation script here return $("#company_id").val(); so it will be
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" id="company_id" />
last in PHP
put quotes ' around variables inside query, rest is all good and working.
$query = $conn->prepare("SELECT account_number FROM reviews WHERE account_number = '$account_number' && company_id = '$compid'");

Firebug shows POST info, but I can't echo

I have a form that seems to POST successfully after submitting via AJAX. Under "NET" in Firebug the posted info displays properly. But I cannot echo this data at all.
I'm trying this, which is the 1st field in my form: <?php echo $_POST['sun_exposure']; ?>
Does this have anything to do with the form's ACTION not having a url?
Also, I'm trying to POST data to the same page, and not a PHP file. Maybe this is part of the problem? This is also a Wordpress page, and not a file.
Here's the live url: http://www.richmindonline.com/container-creations/personal-creations-assistant/
Here's the form code:
<form id="quotation_form" name="vdmQuotationForm" action="#" method="post">
<div id="page1">
<div id="step0_header" class="steps-headers" onClick="step0ToggleClick();">Step 1<span style="margin-left:30px;">Sun Exposure</span></div>
<div id="step0" class="quotation-steps"><strong>Describe the sun exposure of your planter...</strong><br/>
<div class="radio-container"><input onchange="go_to_next_step();" type="radio" name="sun_exposure[]" id="full_sun" value="Full Sun"<?php checked( 'Full Sun',$_POST['sun_exposure[]']); ?> /><label class="label-quotation-steps">Full Sun</label><br class="clear"/></div>
<div class="radio-container"><input onchange="go_to_next_step();" type="radio" name="sun_exposure[]" id="part_sun" value="Part Sun"<?php checked( 'Part Sun',$_POST['sun_exposure[]']); ?> /><label class="label-quotation-steps">Part Sun</label><br class="clear"/></div>
<div class="radio-container"><input onchange="go_to_next_step();" type="radio" name="sun_exposure[]" id="full_shade" value="Full Shade"<?php checked( 'Full Shade',$_POST['sun_exposure[]']); ?> /><label class="label-quotation-steps">Full Shade</label><br class="clear"/></div>
</div>
</div>
</div>
</form>
Here's the AJAX request, which is wrapped up in the jQuery validate script:
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#quotation_form').validate({ // initialize the plugin
rules: {
'sun_exposure[]': {
required: true,
},
'height[]': {
required:true,
},
'diameter[]': {
required:true,
},
'shape[]': {
required:true,
},
'placement[]': {
required:true,
},
},
messages: {
'sun_exposure[]': {
required: 'Please choose a sun exposure for your plant',
},
'height[]': {
required: 'Please choose the height of your planter'
},
'diameter[]': {
required: 'Please choose the diamter of your planter'
},
'shape[]': {
required: 'Please choose the shape of your planter'
},
'placement[]': {
required: 'Please choose the placement of your planter'
},
},
errorPlacement: function (error, element) {
alert(error.text());
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var form_data = $("#quotation_form").serialize();
$.ajax({
url: "http://www.richmindonline.com/container-creations/personal-creations-assistant/",
type: 'POST',
data: form_data,
cache: true,
success: function(data) {
alert(data);
}
});
$('#page1').hide();
$('html, body').animate({ scrollTop: $('body').offset().top }, 10);
$('#page2').show();
$('.intro').hide();
$('.to_page1').show();
return false;
}
}); // end .validate()
});
</script>

How do I post HTML form data to a php file another server using jQuery

I am a bit of a noob with jQuery and am learning for Uni.
I am working on a HTML web site with an associated HTML mobile application that I will compile in phonegap build.
I have a HTML form that I want to include on both the site and the app which I have coded and is successfully validating with jQuery. I would also like to post the form data with jQuery but am struggling to find how best to achieve this.
My form looks like this
<form action="http://myaddress.com/process.php" method="post" name="jform" id="jform">
<div>
<label for="name"><b>Name:</b></label><br>
<input type="text" name="name" id="name">
</div>
<div>
<label for="dob"><b>Date of Birth:</b></label><br>
<input type="text" name="dob" id="dob">
</div>
<div>
<label for="visit"><b>Date of Visit:</b></label><br>
<input type="text" name="visit" id="visit">
</div>
<div class="labelBlock">
<b>Favourite Exhibit:</b>
<div class="indent">
<input type="radio" name="fave" id="exhibit1" value="Exhibit1">
<label for="exhibit1">Exhibit 1</label><br>
<input type="radio" name="fave" id="exhibit2" value="Exhibit2">
<label for="exhibit2">Exhibit 2</label><br>
<input type="radio" name="fave" id="exhibit3" value="Exhibit3">
<label for="exhibit3">Exhibit 3</label>
</div>
</div>
<div>
<label for="comment"><b>Comments:</b></label><br>
<textarea name="comment" id="comment" rows="10" cols="40" draggable="false"></textarea>
</div>
<div id="center-button">
<input name="submit" type="submit" id="submit" value="Submit" class="center-text">
</div>
</form>
My validation script looks like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
var name = $('#name').val();
var dob = $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[name='fave']:radio:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'process-post.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data1){
if (data1 == 'success') {
window.location.href = 'index.html';
}
else {
alert('Oops! It looks like something has gone wrong. Please try again.');
}
}
});
}}); // end ready
I really am struggling with this so would appreciate any help.
My PHP Looks like this
<?php # PROCESS JOURNAL ENTRY.
# Check form submitted.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
# Open database connection.
require ( '../connect_db.php' ) ;
# Execute inserting into 'forum' database table.
$q = "INSERT INTO journal(name,dob,visit,fave,comment,date)
VALUES ('{$_POST[name]}','{$_POST[dob]}','{$_POST[visit]}','{$_POST[fave]}','{$_POST [comment]}',NOW() )";
$r = mysqli_query ( $dbc, $q ) ;
# Report error on failure.
if (mysqli_affected_rows($dbc) != 1) { die ('Error' . mysqli_error($dbc)); } else { echo "success"; }
# Close database connection.
mysqli_close( $dbc ) ;
}
?>
Yes he is correct jquery's ajax will accomplish this or http post. You will use one of the mentioned methods to get the data from the HTML form and send it to the sever.
You will need jQuery ajax. This is a very powerful function that is used any time jQuery validation is used. It also lets you submit to the PHP file and get the results without refreshing the page.
EDIT:
Depending on the complexity of your project, ajax may be overkill. You can just normally submit the form after it is validated like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
}); // end ready
</script>
Here is the part that I add:
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
This will submit a form normally, meaning that it will run the PHP script and then refresh the page.
If you decide you want to use ajax, you can just replace $(form).submit(); with this:
var name = $('#name').val();
var dob= $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[type='radio'][name='fave']:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'http://myaddress.com/process.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data){
if (data == 'success') {
//do something
}
else {
//do something
}
}
});
The data that I am using in the success portion of the function is the value returned from the PHP script. Since you mentioned comments, I am assuming that you PHP is not returning data, but more or less a completion message. In that case, you would just have your PHP echo 'success'; if it was successful. Then fill in the "do somethings" in the jQuery.

Categories