ajax function starts after second click - javascript

I have a form connected with ajax request. I use validation jquery plugin for form check.
So, when i click to submit button ajax call not work. After clicking submit button again it's working.
Why is this happening?
Here is my form
<form action="" id="anyQuestion" class="form-row">
#csrf
<input type="hidden" name="slug" value="{{$page->slug}}">
<div class="form-group col-12">
<input type="text" name="name" placeholder="name" class="form-control">
</div>
<div class="form-group col-6">
<input type="text" name="email" placeholder="mail" class="form-control">
</div>
<div class="form-group col-6">
<input type="text" name="phone" placeholder="phone" class="form-control">
</div>
<button class="submit-button mb-4 mt-2 w-100">submit</button>
</form>
And my ajax function with validation
$('#anyQuestion').validate({
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
minlength: 10
}
},
submitHandler: function () {
var anyQuestionForm = $('#anyQuestion');
anyQuestionForm.submit(function (e) {
// e.preventDefault();
$.ajax({
type: 'post',
url: '/xhr/anyquestion',
data: anyQuestionForm.serialize(),
success: function (data) {
if( data == 'ok' ){
Swal.fire({
position: 'top-end',
type: 'success',
showConfirmButton: false
})
console.log(data);
document.getElementById("anyQuestion").reset();
}
},
error: function (data) {
Swal.fire({
type: 'error',
})
},
});
});
}
});

These two lines:
var anyQuestionForm = $('#anyQuestion');
anyQuestionForm.submit(function (e) {
are in your submit handler, but they are what set up the submit handling in the first place. So, it seems your first button click is calling submitHandler, which is then setting up your form's submit event handler so that another click will submit the AJAX request.
They should be in a document.ready() function:
$(function(){
var anyQuestionForm = $('#anyQuestion');
anyQuestionForm.submit(function (e) { . . .
});
Or, since you have your submit callback already inside your submitHandler, you may not even need the submit callback and just go with:
submitHandler: function () {
$.ajax({
type: 'post',
url: '/xhr/anyquestion',
data: anyQuestionForm.serialize(),
success: function (data) {
if( data == 'ok' ){
Swal.fire({
position: 'top-end',
type: 'success',
showConfirmButton: false
})
console.log(data);
document.getElementById("anyQuestion").reset();
}
},
. . .

Related

Enable browser autocomplete when submitting a form via ajax

After googling for a while I can't found a good answer for my problem.
I have a form that is displayed using a modal windows (bootbox for instance). This form is submitted using ajax post, but the browser can't store input values (autocomplete) so that it can display these values when showing this form again.
function openModal(view) {
var buttons = {};
buttons.success = {
label: "Salvar",
className: "btn-primary",
callback: function() {
var $form = box.find("form");
var valuesToSubmit = $form.serialize();
$.ajax({
type: "POST",
url: $form.attr('action'),
data: valuesToSubmit,
dataType: "json"
}).success(function(response) {
box.modal('hide');
if (successCallback) {
successCallback();
}
}).error(function(response) {
box.find(".modal-body").html(response.responseText);
enableBasicControls(box);
if (errorCallback) {
errorCallback();
}
});
return false;
}
};
buttons.danger = {
label: "Cancelar",
className: "btn-danger"
};
box = bootbox.dialog({
title: title,
animate: false,
message: view,
onEscape: function() {},
buttons: buttons,
size: "large"
});
}
<form asp-action="Create">
<input asp-for="Id" type="hidden" />
<input asp-for="ConsultaId" type="hidden" />
<div class="row">
<input data-focus="true" data-select="true" class="form-control" type="number" data-val="true" data-val-required="The QtdEmbalagens field is required." id="QtdEmbalagens" name="QtdEmbalagens" value="1">
</div>
<div class="row">
<input rows="4" class="form-control" type="text" id="Observacao" name="Observacao" value="">
</div>
</form>
I resolve this problem submitting to a fake page using iframe:
<iframe name="myframe" id="frame1" src="Create" style="display: none;"></iframe>
<form asp-action="Create" target="myframe">
<input asp-for="Id" type="hidden" />
....
function openModal(view) {
var buttons = {};
buttons.success = {
label: "Salvar",
className: "btn-primary",
callback: function () {
var $form = box.find("form");
var url = $form.attr('action');
$form.attr('action', "about:blank");
$form.submit();//======================== fake
var valuesToSubmit = $form.serialize();
$.ajax({
type: "POST",
url: url, //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "json"
...

Getting Internal Server Error (500) - CodeIgniter

In my CodeIgniter project I need to insert data into db table, I am having
Internal server error (500)
issues to add data to database using Ajax.
My Ajax code is below,
$("#rsvp_form").validate({
rules: {
uname: {
required: true,
minlength: 8
},
uemail: "required",
umessage: {
required: true,
maxlength: 100
}
},
messages: {
uname: {
required: "Please enter your name",
minlength: jQuery.validator.format("At least 8 characters required!")
},
uemail: "Please enter your email",
umessage: {
maxlength: jQuery.validator.format("Please enter no more than 100 characters!")
},
},
// ajax request
submitHandler: function (form) {
var formData = {
'user_name': $('input[name=uname]').val(),
'user_email': $('input[name=uemail]').val(),
'user_wish': $('input[name=umessage]').val()
};
// loader
$(".loader").show();
// ajax request
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/Welcome/create_wish",
data: formData,
dataType: "json",
success: function (data) {
// if send data successfull
if (data.status === 'success') {
$(".loader").hide();
$(form).fadeOut("slow");
setTimeout(function () {
$(".form-success").show("slow");
}, 300);
// if send data something wrong
} else if (data.status === 'error') {
$(".loader").hide();
$(form).fadeOut("slow");
setTimeout(function () {
$(".form-error").show("slow");
}, 300);
}
}
});
return false;
}
});
My Welcome Controller function is below : ,
public function create_wish() {
$this->load->model("model_wishes");
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_wish' => $this->input->post('umessage')
);
$this->model_wishes->createWish($data);
}
model_wishes Model is here,
function createWish($data) {
$this->db->insert("wishes", $data);
}
welcome_message View is,
<form id="rsvp_form" action="">
<div class="row">
<div class="form-group col-md-6">
<label for="post-name">Name</label>
<input autocomplete='name' type="text" class="form-control" id="uname" name="uname" required />
</div>
<div class="form-group col-md-6">
<label for="post-email">Email</label>
<input autocomplete='email' type="email" class="form-control" id="uemail" name="uemail" required/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 margin-b-2">
<label for="post-message">Message</label>
<textarea class="form-control" id="umessage" rows="5" name="umessage"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 text-left mb-0">
<button id="btn-create" type="submit" class="button-medium btn btn-default fill-btn">Post Wish</button>
</div>
</div>
When Post Wish button is clicked getting XHR failed loading: POST and an error
POST http://localhost/CodeIgniterProj/index.php/Welcome/create_wish 500 (Internal Server Error)
Please let me know what actually force to internal server error, and how could I fix this Issue.
You are using wrong post input, please check below updated code
public function create_wish() {
$this->load->model("model_wishes");
$data = array(
'user_name' => $this->input->post('user_name'),
'user_email' => $this->input->post('user_email'),
'user_wish' => $this->input->post('user_wish')
);
$this->model_wishes->createWish($data);
}
Hope this will help you :
Your submitHandler code should be like this :
submitHandler: function (form)
{
var formData = $(form).serialize();
$(".loader").show();
console.log(formData);
$.ajax({
type: "POST",
url: "<?=site_url('Welcome/create_wish'); ?>",
data: formData,
dataType: "json",
success: function (data) {
alert(data);
}
});
}
And your controller create_wish should be like this :
public function create_wish()
{
$this->load->model("model_wishes");
$user_name = $this->input->post('uname'));
$user_email = $this->input->post('uemail');
$user_wish = $this->input->post('umessage');
$data = array(
'user_name' => $user_name,
'user_email' => $user_email,
'user_wish' => $user_wish
);
$this->model_wishes->createWish($data);
$response = array('status' => 'success');
echo json_encode($response);
}
Instead of base_url use the site_url
site_url('Welcome/create_wish')

Redirection after successful form submit

I have a form which should submit data after pressing the submit button. After tagging a few input fields as required the form always shows me when there is no input in the required field after pressing the submit button - so far, so good.
What I would like to realize is that there is a redirection to another page if the submission was successful. If there are some empty required fields the form should show me, without redirecting me to another page.
By now I have the following code:
Submit button:
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="submityes" id="submityes" class="btn btn-danger">Submit</button>
</div>
</div>
Also I have the following js function to submit the form and to redirect me to another page:
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
The problem I have right now is that I will always be redirected to the "submit_resolved.php" page, whether all required fields are complete or not.
How can I solve this problem? I only want to be redirected when all required fields are not empty.
You should bind to the submit event, not click event:
UPDATED TO MATCH THE COMMENTS
$(function () {
var submityesClicked;
//catch the click to buttons
$('#submityes').click(function () {
submityesClicked = true;
});
$('#submitno').click(function () {
submityesClicked = false;
});
$('#webform').submit(function (e) {
e.preventDefault();//prevent the default action
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
window.location.replace(submityesClicked ? "/submit_resolved_yes.php" : "/submit_resolved_no.php");
},
error: function () {
alert("error");
}
});
});
});
The submit event is triggered only if the form is valid.
Note that the submit event is triggered by the form but the click event is triggered by the input element.
Do redirection on complete. Not on success
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
//window.location.replace("/submit_resolved.php");
},
complete: function () {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
I assume you are validating form in process.php so, you have to return error if validation fail from process.php like this.
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
check this link: Return errors from PHP run via. AJAX?
Hope this may be helpful to you.
The simplest thing you can do is to add "required" attribute to you input elements.Example:
<form action="/action_page.php">
Username: <input type="text" name="usrname" required>
<input type="submit">
</form>
It's a HTML5 attribute, so no JavaScript required. And it is supported by all major browsers. Check this link:
http://caniuse.com/#search=required
Anyway, you shouldn't rely just on front-end verification. Check those inputs on back-end, too.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<form action="">
Username: <input type="text" id="usrname" required>
<button type="button" name="submityes"
id="submityes" class="btn btn-danger">Submit</button>
</form>
</div>
function isValid(){
var usrname = $("#usrname").val();
if(usrname == ""){
return false;
}
return true;
}
$(function () {
$('#submityes').submit(function () {
if(isValid() == true){
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
alert("success");
window.location.replace("/submit_resolved.php");
},
});
}else{
alert("error");
}
});
});

Form submit issues using jQuery and Ajax

Actually I have 2 questions about form submit using jQuery and Ajax.
Currenlty, I am validating a login form using jQuery/Ajax request. I want to disabled the login submit button after logged in successfully completed. So that I am using following .js code but it's not disabled the submit button.
Questions
a) what is the issue in my js code ? why it's not disable the login submit button after logged in successfully ?
b) Using jQuery/Ajax for login is safe for security ? If not what I need to to and Should I add server side validation too ?
Thanks a lot :)
.js code for login :
// Login form
function login_form (element,event){
e= $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
url: 'login_process',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('#login_bottom').val('Validating...');
$("#login_bottom").attr("disabled", true);
},
success: function (data) {
$('.validation_msg').html(data);
$('#login_bottom').val('LOGIN');
$("#login_bottom").attr("disabled", false);
if(data == '<div class="alert alert-success"><strong>Successfully logged!.</strong></div>') {
$('#login_form')[0].reset();
$("#login_bottom").attr("disabled", true);
}
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
Login Process php page :
It's return following message after successfully logged :
if(login($email, $user_pwd) == true) {
echo '<div class="alert alert-success">';
echo '<strong>Successfully logged!.</strong>';
echo '</div>';
}
Html form :
<div class="container bellow-nav">
<div class="row">
<div class="col-md-6 content-area">
<h3>Login</h3>
<hr/>
<form role="form" method="post" id="login_form">
<div class="form-group">
<label for="email">Email addresse</label>
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" name="pwd" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="hidden" name="_token" value="<?php echo $form_token; ?>">
<input type="submit" name="submit" value="LOGIN" class="btn btn-booking" id="login_bottom" onclick="login_form(this,event);" >
</div>
<div class="form-group validation_msg">
</div>
<div class="fomr-group">
<label for=""><p>Forgot password?</p></label> |
<label for=""><p>Don't have an account? <a href="signup">Join now</p></label>
</div>
</form>
</div>
</div><!--main row-->
</div><!--main container end-->
One reason could be that the data may have some leading or trailing spaces.
You can extract only the text message from the data and use that for comparison
if ($(data).text().trim() == 'Successfully logged!.') {
$('#login_form')[0].reset();
$("#login_bottom").prop("disabled", true);
} else {
$("#login_bottom").prop("disabled", false);
}
For the second part, I assume the server side login is using a secured cookie to store the authentication information is so yes it is secured.
Use json response insted of HTML
Login Process php page : It's return following message after successfully logged :
if(login($email, $user_pwd) == true) {
echo json_encode(['message'=>'Success'])
}
$.ajax({
url: 'login_process',
type: 'POST',
dataType: 'JSON',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('#login_bottom').val('Validating...');
$("#login_bottom").attr("disabled", true);
},
success: function (data) {
$('.validation_msg').html(data);
$('#login_bottom').val('LOGIN');
$("#login_bottom").attr("disabled", false);
if(data.message == 'Success') {
$('#login_form')[0].reset();
$("#login_bottom").attr("disabled", true);
}
},
data: formData,
cache: false,
contentType: false,
processData: false
});
First and for most, YOU MUST ADD SERVER SIDE VALIDATIONS. JavaScript can be disabled on the browser and your validations will be disabled when that happens. Javascript can also be edit on the browser and your validations will be useless js validations is only good for user friendly feeling and not for security.
All you have to do is set the disabled attribute to disabled value
$("#login_bottom").attr("disabled","disabled");
However I don't think you are going inside that if. you should console log something and make sure you are passing the if statement.

Jquery Validation : Submit button have to be clicked twice for form submission (fire fox)

I am using jquery validation plugin for US ZIPCODE CHECK ,its working fine,
but I have to push the submit button TWICE to get the form submitted,
Note : if I press enter that it submits the form properly, but it doesnt work with click event
I already have checked this stackoverflow answers but they didnt helped me out
Why do you have to submit twice before jQuery Validate submitHandler is triggered?
jquery validate need to click submit twice to submit form
jQuery using .on and .validate must submit form twice to validate
Below is my Javascript code
var ans;
$(document).ready(function(e)
{
jQuery.validator.addMethod("zipcode", function(e)
{
$.ajax(
{
url: "http://zip.elevenbasetwo.com",
cache: false,
async: false,
dataType: "json",
type: "GET",
data: "zip=" + $("#zip").val(),
success: function()
{
ans = true;
},
complete: function()
{
ans = true;
},
error: function()
{
ans = false;
}
}
);
return ans;
});
$("#register-form2").validate({
debug: true,
onkeyup: false,
rules: {
zip: {
required: true,
zipcode: true,
minlength: 5
},
email: {
required: true,
email: true
}
},
messages: {
zip: {
required: "Please enter a USA zip code",
zipcode: "Please enter a valid USA zip code"
},
// zip: "Please enter a valid USA zip code.",
email: "Please enter a valid email address."
},
submitHandler: function(form)
{
alert('hi');
form.submit();
}
});
});
Please mark that if I dont use ajax function in my custom method than it just works fine, but i am not able to solve it.
below is my HTML code
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post" class="wpcf7-form" id="register-form2" novalidate>
<input name="email" required id="email" type="text" placeholder="Email*">
<input type="text" name="zip" id="zip" required size="40" maxlength="15" placeholder="Zip code* (USA only)">
<input name="Form_submit" class="btn btn-primary wpcf7-form-control wpcf7-submit" id="Submit" value="Sign-up" type="submit">
</form>

Categories

Resources