PHP Post on Bootstrap submitHandler - javascript

I'm pretty new in web development and I know this might sound like a very simple question but I'm trying to add a login functionality in a bootstrap template.
The .js with the template validates the contents of the text and such. I'm trying to add a POST function in the submitHandler.
$(document).ready(function() {
$('#login-form').validate({
focusInvalid: false,
ignore: "",
rules: {
txtusername: {
minlength: 2,
required: true
},
txtpassword: {
required: true,
}
},
invalidHandler: function (event, validator) {
//display error alert on form submit
},
errorPlacement: function (label, element) { // render error placement for each input type
$('<span class="error"></span>').insertAfter(element).append(label)
var parent = $(element).parent('.input-with-icon');
parent.removeClass('success-control').addClass('error-control');
},
highlight: function (element) { // hightlight error inputs
},
unhighlight: function (element) { // revert the change done by hightlight
},
success: function (label, element) {
var parent = $(element).parent('.input-with-icon');
parent.removeClass('error-control').addClass('success-control');
},
submitHandler: function(form) {
var username=$("#txtusername").val();
var password=$("#txtpassword").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
cache: false,
success: function(data){
if(data) {
window.location.href = "index.php";
} else {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
});
});
<?php
if (isset($_POST['submit'])) { // Form has been submitted.
$username = ($_POST['username']));
$password = ($_POST['password']));
.
.
.
.
.
}
else
{
echo "Doesnt Work";
}
?>
.
.
.
<form id="login-form" class="login-form" action="#" method="post">
<div class="row">
<div class="form-group col-md-10">
<div id="error"></div>
<label class="form-label">Username</label>
<div class="controls">
<div class="input-with-icon right">
<i class=""></i>
<input type="text" name="txtusername" id="txtusername" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-10">
<label class="form-label">Password</label>
<span class="help"></span>
<div class="controls">
<div class="input-with-icon right">
<i class=""></i>
<input type="password" name="txtpassword" id="txtpassword" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-10">
<button class="btn btn-primary btn-cons pull-right" type="submit">Login</button>
</div>
</div>
</form>
Thanks in advance!

Please check the documention of data sent to the server. You can use object to send your data. In the link above, there are some examples how to send data to server.
var dataString = {username: username, password: password}

Related

Ajax success function not working on the second time

Aim: Continue to display any form validation errors through json callback
Problem: When I submit on the form with invalid input it shows an error message in a div element. If all inputs are valid it will process the ajax request and show a success message in a div element. After which, the form resets but the modal remain open. When I try to again validate the input in doesn't show any error message. When I try to test the valid input still the same no message shown.
In short: Ajax success function not working on the second time.
Here's my code:
Bootstrap Modal (where my form inputs placed)
<div class="modal fade" id='frmModal'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class='close' data-dismiss='modal'>×</button>
<h4 class='title'>Add new data</h4>
</div>
<div class="modal-body">
<?php echo form_open('Employee/save',array('id'=>'frm', 'class'=>'form-horizontal')); ?>
<div id="message"></div>
<div class="form-group">
<label for='fname' class='col-md-3 control-label'>First Name:</label>
<div class="col-md-9">
<input type="text" name="fname" id='fname' class='form-control' placeholder='First Name...'>
</div>
</div>
<div class='form-group'>
<label for='lname' class='col-md-3 control-label'>Last Name:</label>
<div class="col-md-9">
<input type="text" name="lname" id='lname' class='form-control' placeholder='Last Name...'>
</div>
</div>
<div class='form-group'>
<label for='age' class='col-md-3 control-label'>Age:</label>
<div class="col-md-9">
<input type="text" name="age" id='age' class='form-control' placeholder='Age...'>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary action" type='submit'><i class='glyphicon glyphicon-floppy-disk'></i> Save Data</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
Jquery Code:
$(document).on('submit','#frm',function(e){
e.preventDefault();
var form = $('#frm');
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: 'json',
encode: true,
data: form.serialize(),
success: function(data) {
if (!data.success) {
if (data.errors) {
$('#message').html(data.errors).addClass('alert alert-danger');
}
} else {
reloadData();
$('#message').html("<span class='glyphicon glyphicon-ok'></span> " + data.message).removeClass('alert alert-danger').addClass('alert alert-success');
setTimeout(function() {
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
$('#frm')[0].reset();
}
}
});
});
CodeIgniter Controller:
$this->form_validation->set_rules('fname','First Name', 'required|trim');
$this->form_validation->set_rules('lname','Last Name', 'trim|required');
$this->form_validation->set_rules('age','Age', 'trim|numeric|required');
if($this->form_validation->run()===FALSE)
{
$info['success'] = false;
$info['errors'] = validation_errors();
}
else
{
$info['success'] = true;
$data = array(
"firstname" => $this->input->post('fname'),
"lastname" => $this->input->post('lname'),
"age" => $this->input->post('age'),
);
$this->Employee_model->save('ci_table', $data);
$info['message'] = 'Successfully saved data';
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
I think I understand... The form still works but the messages do not appear? If so then try the below...
You are removing the #message element instead of clearing it... try:
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).empty();
This way you are emptying the #message element instead of removing it completely..

Ajax form submit without page refresh

I simply want to submit my form to the same page with ajax without page refresh. So my below code submits the form but $_POST values are not picked ... Am I submitting it properly. I don't get any error but I think my form is not submitting.
html form
<form action="" id="fixeddonation" name="fixeddonation" method="post">
<input type="hidden" class="donerProject" name="donerProject" value="test">
<input type="hidden" class="donersubProject" id="donersubProject" name="donersubProject" value="general">
<input type="hidden" class="donerLocations" id="donerLocations" name="donerLocations" value="general">
<input type="hidden" class="donationpagetype" name="donationpagetype" value="general">
<input type="hidden" class="projectadded" id="projectadded" name="projectadded" value="1">
<input type="hidden" value="302" id="pageid" name="pageid">
<div class="classsetrepet generalfixshow fullrow row fixed-page">
<div class="col-6 text-right">
<div class="prize">Fixed Amount £</div>
</div>
<div class="col-6">
<input type="text" id="oneoffamt" name="oneoffamt" class="oneoffamt validatenumber">
<span class="amt_error"></span>
</div>
</div>
<br>
<div class="row">
<div class="col-6"></div>
<div class="col-6">
<input type="submit" id="submit_gen_one" class="btn-block" value="submit" name="submit_gen_one">
</div>
</div>
</form>
Ajax code
jQuery('#fixeddonation').on('submit', function (e) {
e.preventDefault();
jQuery.ajax({
type: 'post',
url: 'wp-admin/admin-ajax.php',
data: jQuery('#fixeddonation').serialize(),
success: function (data) {
alert(data);
alert('form was submitted');
jQuery('#collapse2').addClass('in').removeAttr('aria-expanded').removeAttr('style'); jQuery('#collapse1').removeClass('in').removeAttr('aria-expanded').removeAttr('style');
}
});
return false;
});
Add a correct value to the action tag of your form and try this:
<script>
$(document).ready(function() {
var form = $('#fixeddonation');
form.submit(function(ev) {
ev.preventDefault();
var formData = form.serialize();
$.ajax({
method: 'POST',
url: form.attr('action'),
data: formData
}) .done(function(data) {
alert(data);
});
});
}); // end .ready()
</script>
Don't need return false as you already called preventDefault() first thing
First create Template
<?php
/* Template Name: Test */
get_header();
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<p class="register-message" style="display:none"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must Be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register" >
</fieldset>
</form>
<script type="text/javascript">
jQuery('#test').on('click',function(e){
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") { jQuery('#email-error').show(); return false; }
else { jQuery('#email-error').hide(); }
jQuery.ajax({
type:"POST",
url:"<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test",
firstname : firstname,
email : email
},
success: function(results){
console.log(results);
jQuery('.register-message').text(results).show();
},
error: function(results) {
}
});
});
</script>
</main><!-- #main -->
</div><!-- #primary -->
after that create a function (function.php in wordpress)
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test() {
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='".$email."' ");
$res = $wpdb->get_results($q);
if(count($res)>0)
{
echo "Email Allready Register ";
}
else
{
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix.'test'; // if use wordpress
$user_id= $wpdb->insert( $tablename,$user_data );
echo 'we have Created an account for you';
die;
}
}

Getting XMLHttpRequest erros on ajax Post

I have a modal in which there's a form that I want users to be able to submit an email with. I set up the ajax post like I usually would, however, the post keeps failing. When it does, I get the following two errors in the console.
Setting XMLHttpRequest.withCredentials for synchronous requests is deprecated
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
Interestingly, the email sometimes sends regardless of the errors, but sometimes it doesn't either.
Here is my Html:
<form class="cmxform" id="contactForm" >
<div class="row">
<div class="col-xs-6">
<label class="col-md-12 control-label" style="text-align: left;" >Name</label>
<div class="col-md-12">
<input required class="form-control" id="FromName" name="FromName" style="margin-bottom: 10px;" type="text" value=""/>
</div>
</div>
<div class="col-xs-6">
<label class="col-md-12 control-label" style="text-align: left;" >Email</label>
<div class="col-md-12">
<input required class="form-control" style="margin-bottom: 10px;" id="FromEmail" name="FromEmail" type="text" value=""/>
</div>
</div>
</div>
<label class="col-md-12 control-label" >Message</label>
<div class="col-md-12">
<textarea required class="form-control contact-message" cols="20" id="Message" name="Message" rows="2"></textarea>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-info" value="Submit" />
</div>
</form>
And my JS:
function sendMessage(messageData) {
$.ajax({
async: true,
url: '/api/SendMessageApi',
type: 'POST',
data: messageData,
success: function () {
},
error: function (ex) {
alert('there was an error');
}
});
}
$("#contactForm").submit(function () {
var name = $('#FromName').val();
var email = $('#FromEmail').val();
var message = $('#Message').val();
var messageData = { Name: name, Email: email, Message: message };
sendMessage(messageData);
});
Any help would be much appreciated!
To submit the form after ajax success, you can use:
function sendMessage(messageData) {
$.ajax({
context: this, // set context to the form
async: true,
url: '/api/SendMessageApi',
type: 'POST',
data: messageData,
success: function () {
this.submit(); // submit form on success
},
error: function (ex) {
alert('there was an error');
}
});
}
$("#contactForm").submit(function (e) {
e.preventDefault();
var name = $('#FromName').val();
var email = $('#FromEmail').val();
var message = $('#Message').val();
var messageData = { Name: name, Email: email, Message: message };
sendMessage.call(this, messageData); // set context to the form
});

form submitting twice via ajax POST

Inserting into mysql using php file called via AJAX. Before insert statement php code performs select query to find duplicate records and continue to insert statement.
Issue: When calling php file from ajax. it executed twice and getting response as duplicate record.
well i tried error_log from insert function its called twice.
Trigger point of form validation
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
This is how form submitted after validation:
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
using bootstrapvalidator, Core PHP, mysqli, Chrome Browser.
Actual JS:
$(document).ready(function() {
$php_self_country="<?php echo $_SERVER['PHP_SELF']."?pg=countrycontent"; ?>";
$("#country-content").load($php_self_country,loadfunctions);
$("#country-content").on( "click", ".pagination a", function (e){
e.preventDefault();
$("#country-loading-div").show();
var page = $(this).attr("data-page");
$("#country-content").load($php_self_country,{"page":page}, function(){
$("#country-loading-div").hide();
loadfunctions();
});
});
$("#country-content").on("click","#closebtn",function(e){
e.preventDefault();
$("#country-content").load($php_self_country,loadfunctions);
});
});
function loadfunctions(){
$("[data-toggle='tooltip']").tooltip();
$("#country-content").on("click","#addcountrybtn, #addcountrylargebtn",function(e){
e.preventDefault();
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'addcountry':'Y' },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#country-content").on("click",".tools a",function(e){
e.preventDefault();
var recordid = $(this).attr("record-id");
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'modifycountry':recordid },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
$("#load-modal").on("hide.bs.modal", function () {
window.location.href=$php_self_country_pg;
});
}
function modalvalidation(){
$('#addcountryform').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
[-------Validation part comes here----------]
}
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
}
HTML
this html is called on button click addcountrybtn via AJAX and write in to div load-modal which is in base html file.
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="fa fa-exchange"></i> <?php echo COUNTRYLABEL; ?></h4>
</div>
<div class="modal-body">
<form role="form" method="POST" action="self.php" name="addcountryform" id="addcountryform" class="form-horizontal">
<div class="form-group">
<div class="col-xs-3">
<label for="countryname" class="pull-right">Country Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="countryname" placeholder="Enter Country Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncyname" class="pull-right">Currency Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncyname" placeholder="Enter Currency Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncycode" class="pull-right">Currency Code</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncycode" placeholder="Enter Currency Code">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="forrate" class="pull-right">Foreign Currency Rate<?php echo isset($icon)?$icon:''; ?></label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="forrate" placeholder="Enter Foreign Currency Rate.">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="taxpercent" class="pull-right">Tax %</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="taxpercent" placeholder="Enter Tax Percentage">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer clearfix">
<button type="button" class="btn btn-danger pull-right" id="addcountryformsubmitbtn">Add</button>
</div>
</div>
Note:- in Database point of view code works as expected.
Couple of things that I have seen could possibly be the cause.
If you are using IE, I have seen that perform a GET immediately before doing a POST (to the same URL, with the same data being sent over), so it could be worth trying to check for that on your server (and ignore the GET)
Something else it maybe to add the following to the end of your button click events after the AJAX call (actually, normally I'd put the first line at the top with the prevent default, and the return statement obviously goes very last)...
e.stopImmediatePropagation();
return false;

jquery validation plugin ajax submit a form not working

I use jquery validation plugin to do validation in a bootstrap modal form, when i send the form ,the jquery validation plugin is working but ajax code will do two time and the form cannot send out.
bootstrap form
<form class="contact">
<fieldset>
<div class="modal-body">
<ul class="nav nav-list">
<div class="form-group">
<label for="topic" class="control-label ">topic</label>
<input class="form-control" type="text" name="topic" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="ruser" class="control-label "> ruser: </label>
<input class="form-control" type="text" name="ruser" value="<?php echo $username; ?>" readonly/>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="content" class="control-label ">content:</label>
<textarea class="form-control" name="content" rows="3"></textarea>
<span class="help-block"></span>
</div>
</ul>
</div>
</fieldset>
<button class="btn btn-success" id="submitcontact">ok</button>
</form>
javascript
$(document).ready(function () {
$('form').validate({
rules: {
topic: {
required: true
},
ruser: {
required: true
},
content: {
required: true
}
},
messages: {
topic: {
required: 'enter topic'
},
ruser: {
required: 'enter nuser'
},
content: {
required: 'enter content'
}
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "process.php",
data: $('form.contact').serialize(),
success: function (msg) {
alert("ok!");
if (msg == 'ok') {
alert(msg);
location.reload()
}
},
error: function () {
alert("failure");
}
});
return false;
}
});
$('#submitcontact').click(function () {
$('form.contact').submit();
})
});
How can i fix the problem?
The jsfiddle
You probably need to remove this bit:
$('#submitcontact').click(function(){
$('form.contact').submit();
})
Please see the example:
http://jsfiddle.net/8eoreedb/1/
Use .valid() method:
Description: Checks whether the selected form is valid or whether all selected elements are valid.
Updated Fiddle
$('#submitcontact').on('click', function() {
if ($('form.contact').valid()) {
// Form is valid
$('form.contact').submit();
}
});
Doc: http://jqueryvalidation.org/valid/
Demo: http://jsfiddle.net/8eoreedb/4/

Categories

Resources