ajax submit multiple times - javascript

I have created an application in the php, I am using the bootstrap model to update user details using AJAX. Now there are two forms: first updates the user's details and adds comments to another user. When I try to submit a form to AJAX and I try to submit a form, it does not work, when i use ajaxComplete function then my form data has been submitted successfully, but at the time it submits the form multiple times at the same time.
$(document).ajaxComplete(function() {
$("#add-remarks").on('submit', (function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#add-remarks").attr("action"),
cache: false,
context: this,
data: $("#add-remarks").serialize(), //only input
success: function(data) {
var obj = JSON.parse(data);
$("#add-remarks")[0].reset();
if (obj['msg'] == 'isuccess') {
notification('insert');
} else {
notification('error');
}
}
});
}));
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="card-group-control card-group-control-right" id="accordion-model">
<div class="card">
<form method="post" name="update-user-details" id="update-user-details" action="">
<div class="row">
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">First Name</label>
<input type="text" class="form-control" placeholder="First Name" name="customer_name" id="customer_name">
</div>
</div>
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">Mobile</label>
<input type="text" class="form-control" placeholder="Mobile" name="mobile_number" id="mobile_number">
</div>
</div>
<button type="submit" class="btn bg-blue">Save Changes</button>
</div>
</form>
<form method="post" name="remarks" id="remarks" action="">
<div class="row">
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">Remarks</label>
<input type="text" class="form-control" placeholder="Remarks" name="remarks" id="remarks">
</div>
</div>
<button type="submit" class="btn bg-blue">Save Changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>

Move this piece of code outside of your ajaxComplete() function. You are probably somehow triggering the ajaxComplete function multiple times, causing multiple event listeners for the form submit.
$("#add-remarks").on('submit', (function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#add-remarks").attr("action"),
cache: false,
context: this,
data: $("#add-remarks").serialize(), //only input
success: function(data) {
var obj = JSON.parse(data);
$("#add-remarks")[0].reset();
if (obj['msg'] == 'isuccess') {
notification('insert');
} else {
notification('error');
}
}
});
}));

Related

Ajax form gets submitted twice when i click on submit button second time

Simple bootstrap 5 (with validation) contact form with Ajax call gets executed only when i hit submit button second time and it also save data twice. this form is inside modal form and this behavior happened when i added Ajax function to code..
I am not sure what is stopping form submission successfully after validation, form gets submitted only when i hit submit button second time and it save same data twice.
based on references i used e.stopImmediatePropagation(); but there behavior didnt change
<!-- Modal -->
<div class="modal-form modal fade" id="modal-form" data-bs-backdrop="static" tabindex="-1"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Register you interest</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="form-body">
<div class="row">
<div class="form-holder">
<div class="form-content">
<div class="form-items">
<p>Fill in the details below, we will get back to you!</p>
<form id="contactForm" class="requires-validation" action="sendemail.php" method="POST" novalidate >
<div class="col-md-12 mb-3">
<input class="form-control" type="text" name="name" placeholder="Full Name" required>
<div class="valid-feedback">Full Name field is valid!</div>
<div class="invalid-feedback">Full Name field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<input id="phone" type="tel" name="phone" class="form-control"
onkeypress="return isNumber(event)" required>
<div class="valid-feedback phoneinvalid" id="phoneinvalid"></div>
<div class="invalid-feedback">Phone field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<textarea class="form-control" name="message" id="message" placeholder="Your Message"></textarea>
</div>
<div class="form-button mt-3">
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-success-msg"></div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
JS Part
(function () {
'use strict'
const forms = document.querySelectorAll('.requires-validation')
Array.from(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
console.log("form.checkValidity() "+form.checkValidity());
if (!form.checkValidity()) {
// form.classList.remove('was-validated')
//event.preventDefault();
//event.stopPropagation();
e.stopImmediatePropagation();
form.classList.add('was-validated')
return;
}
else
{
console.log("This line should execute only if Form is validated");
AjaxCallSaveData();
form.classList.add('was-validated')
}
}, false)
})
})();
function AjaxCallSaveData()
{
console.log(" I am AjaxCall Function");
$("form").submit(function (event) {
var formData = {
name: $("#name").val(),
phone: $("#phone").val(),
message: $("#message").val(),
};
$.ajax({
type: "POST",
url: "SaveData.php",
data: formData,
dataType: "json",
encode: true
}).done(function (data) {
console.log(data);
if (!data.success) {
console.log("alert alert-warning");
} else {
console.log("alert alert-success");
$(".form-success-msg").add("display","block");
$("form").html(
'<div class="alert alert-success">' + data.message + "</div>"
);
}
});
event.preventDefault();
});
}

Javascript code returns Unhandled Promise Rejection: AbortError: The operation was aborted

I am trying to run a simple contact form with html and javascript. I am trying to get filled out a contact form and then post the data to api. Upon page load I immediately get an error for Unhandled promise rejection.
HTML is:
<form id="contact-form"method="post" class="form-horizontal contact-form" action="#">
<!-- Honeypot SPAM Protection -->
<input type="text" name="cf[honeypot]" style="display: none">
<!-- END Honeypot SPAM Protection -->
<div class="form-group">
<div class="col-md-6">
<input type="text" name="cf[name]" class="form-control required" placeholder="İsim">
</div>
<div class="col-md-6">
<input type="email" name="cf[email]" class="form-control required email" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input type="url" name="cf[url]" class="form-control url" placeholder="URL">
</div>
<div class="col-md-6">
<input type="text" name="cf[subject]" class="form-control required" placeholder="Konu">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<textarea name="cf[message]" rows="6" class="form-control required" placeholder="Mesaj"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="submit" value="Gönder" class="btn btn-sm btn-block btn-primary">
</div>
</div>
</form>
<script type="text/javascript" src="assets/js/signup.js"></script>
And the javascript code is:
$(document).ready(function() {
$("contact-form").submit(function(e){
e.preventDefault();
var form=this;
var URL = "https://v9jg33e7pa.execute-api.us-east-1.amazonaws.com/beta/sendemail/";
var data = {
name: $(form).find("#cf[name]").val(),
email: $(form).find("#cf[email]").val(),
urlContact: $(form).find("#cf[url]").val(),
subject: $(form).find("#cf[subject]").val(),
message: $(form).find("#cf[message]").val()
};
console.log(data);
if (""===$(form).find("#cf[honeypot]").val()){
$.ajax({
type: "POST",
url: URL,
dataType: "json",
contentType: "application/json",
data: JSON.stringify(data),
success: function () {
// clear form and show a success message
alert("yay");
},
error: function () {
// show an error message
alert("boo");
},
});
}
});
});
But when loading the page I get the following error:
Could not figure out what I am doing wrong?

Laravel 5.2 Modal popup for forget Password displaying 500 internal server Error while running ajax function

I am trying to Check weather email exist or not to send reset password link.
For that am using ajax function but its showing 500 internal server error before runing ajax.
I knw 500 is for token miss match error but do i need token to check email existing or not.
But I think so, with the form tag token is auto generated and then also am using {{ csrf_field() }}
But it showing same error 500 Internal server. Just Help how can resolve this issue and do i need to generate token manually.
Views : login.blade.php
{!! Form::open(array('url' => '/auth/login', 'class' => 'form- login')) !!}
<div class="form-title"> <span class="form-title">Login</span> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Username</label>
<input class="form-control form-control-solid placeholder-no-fix required" type="text" autocomplete="off" placeholder="Email" name="email" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control form-control-solid placeholder-no-fix passwordclass required" type="password" autocomplete="off" placeholder="Password" name="password" />
</div>
<div class="form-actions">
<button type="submit" class="btn red btn-block uppercase clicklogin" style="background-color:#d5ed31 !important;border-radius:4px !important;border:1px solid #ddd;">Login</button>
</div>
<div class="form-actions">
<div class="pull-left">
<label class="rememberme mt-checkbox mt-checkbox-outline">
<input type="checkbox" name="remember" value="1" />
Remember me <span></span> </label>
</div>
<div class="pull-right forget-password-block"> <a class="btn-link" data-target="#modalforget" data-toggle="modal">Forgot Password? </a></div>
</div>
{!! Form::close() !!}
<!-- END LOGIN FORM -->
<!-- BEGIN FORGOT PASSWORD FORM-->
{!! Form::open(array('url'=>'password/reset','class' => 'form-horizontal create_forget_form','method'=>'POST', 'id' =>'forgetdata', 'files' => true)) !!}
{{ csrf_field() }}
<div class="modal fade" id="modalforget" tabindex="-1" data-width="760px" >
<div class="modal-dialog" style="width:760px !important;">
<div class="modal-content" style="background-color:#26344b;padding:20px;border-radius:12px !important;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<div class="form-title"> <span class="form-title">Forget Password</span> </div>
</div>
<div class="modal-body" style="height:auto !important;">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<strong style="color: #ffffec; font-size: large; "> Please enter your email. A password reset link will be sent to this email.</strong>
</div>
</div>
</div>
<div class="row"></div>
<div class="row">
<div class="col-md-10">
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<input class="form-control required" type="email" autocomplete="off" placeholder="Email" id="forget_email" name="forget_email"style="font-size: large;" />
<span class="my-error-class" id="email_status"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" value="Submit" id="submitButton" class="btn green">Submit</button>
<button type="button" value="Cancel" class="btn default red" data-dismiss="modal">Cancel</button>
<button type="reset" value="Clear" class="btn blue">Clear</button>
</div>
</div>
</div>
</div>
</div>
</form>
Ajax function in login.blade.php
<script type="text/javascript">
$('#submitButton').click(function(){
var formdata=new FormData($(this)[0]);
$.ajax({
url:"{{ URL::to('password/reset') }}",
type: 'POST',
data: formdata,
async: false,
cache: false,
contentType: false,
processData: false,
context:this,
dataType: "json",
success: function (returndata)
{
if(returndata == 0)
{
$( '#email_status' ).html('This Email does not Exists');
return false;
}
else
{
$( '#email_status' ).html("");
return false;
}
},
error: function(data)
{
console.log(data);
}
});
});
</script>
Route file:
Route::group(['middleware' => 'auth'], function()
{
Route::post('password/reset','Auth\AuthController#resetPassword');
}
Controller Auth\AuthController#resetPassword:
public function resetPassword()
{
$email =Input::get('forget_email');
$user_email = DB::table('users')->where('email', $email)->whereNull('deleted_at')->first();
if($user_email)
{
return '1';
}
else
{
return '0';
}
}
Screen Shot Of Error
I think you have to write your route outside auth group.
Route::post('password/reset','Auth\AuthController#resetPassword');
The issue is you are using POST request with ajax and for every post request you have to pass the csrf-token with the request like:
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
Put this in your ajax code and everything will be fine.
Or if you want to exclude the specific URI from CSRF verification, go to project/app/Http/Middleware, there is a file VerifyCsrfToken.php in which put the routes list in:
protected $except = [
// route list here
];
All the routes defined here excludes from csrf-token check.

Two AJAX form submissions in a single JS file, only one is working

In the HTML, the forms look identical, just the form ID is changed. I use this JS file to submit the forms using AJAX:
$("#change-password").submit(function(e) {
var url = "http://domain/actions";
$.ajax({
type: "POST",
url: url,
data: $("#change-password").serialize(),
success: function(data) {
$("div.change-password-response").html(data);
}
});
e.preventDefault();
});
$("#change-email").submit(function(e) {
var url = "http://domain/actions";
$.ajax({
type: "POST",
url: url,
data: $("#change-email").serialize(),
success: function(data) {
$("div.change-email-response").html(data);
}
});
e.preventDefault();
});
HTML Part
<div class="col-md-6 col-sm-6 add_bottom_30">
<h4>Schimbare parola</h4>
<form id="change-password" method="post">
<div class="form-group">
<label>Parola veche</label>
<input class="form-control" name="old_password" id="old_password" type="password" autocomplete="off">
</div>
<div class="form-group">
<label>Parola noua</label>
<input class="form-control" name="new_password" id="new_password" type="password" autocomplete="off">
</div>
<div class="form-group">
<label>Confirma parola noua</label>
<input class="form-control" name="confirm_new_password" id="confirm_new_password" type="password" autocomplete="off">
</div>
<input type="hidden" name="action" value="change-password">
<button type="submit" class="btn_1 green">Actualizeaza parola</button>
<div class="change-password-response form-response"></div>
</form>
</div>
<div class="col-md-6 col-sm-6 add_bottom_30">
<h4>Schimbare adresa email</h4>
<form id="change-email" method="post">
<div class="form-group">
<label>Email vechi</label>
<input class="form-control" name="old_email" id="old_email" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Email nou</label>
<input class="form-control" name="new_email" id="new_email" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Confirma email nou</label>
<input class="form-control" name="confirm_new_email" id="confirm_new_email" type="password" autocomplete="off">
</div>
<input type="hidden" name="action" value="change-email">
<button type="submit" class="btn_1 green">Actualizeaza Email</button>
<div class="change-email-response form-response"></div>
</form>
</div>
Now, my problem is that Form 1 is working, Form 2 is not triggering the AJAX and works as normal form. What am I doing wrong?
Check if #change-email has other binded events.
In Firebug, inspect #change-email element and go to Event tab.
In Chrome, inspect that element and go to Event Listeners tab.
You will see all binded events and corresponded callback functions.
If it will not help, try to submit a form manually from Console
Inspect a form, then run
$($0).submit();
If it will work, looks like you have some events on you button.

How to change view in Knockout JS

i have a short question. I am using Knockout JS and having this view and ViewModel:
var LoginViewModel = function () {
var self = this;
self.userName = ko.observable();
self.userPassword = ko.observable();
self.signin = function () {
data = ko.toJSON(self);
$.ajax({
url: "/signin",
type: "post",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data, textStatus, xhr) {
alert(xhr.status);
// If status == 200(OK) change view
},
error: function (jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
}
ko.applyBindings(new LoginViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<div class="container">
<div class="col-md-4 col-md-offset-4" data-bind="visible: isVisible">
<div class="panel panel-default">
<div class="panel-heading" style="text-align: center;">
<strong class="">SEHA</strong>
</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="username" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input class="form-control" required="" type="text" data-bind="value: userName">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-3 control-label">Password</label>
<div class="col-sm-9">
<input class="form-control" required="" type="password" data-bind="value: userPassword">
</div>
</div>
<div class="form-group last">
<div class="col-sm-offset-3 col-sm-9">
<button class="btn btn-success btn-sm" data-bind="click: signin">Sign in</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">
~
</div>
</div>
</div>
</div>
I want now to change the "view" if the user logs in. How can i accomplish that?
I also would to like to select a new view model for the next view. How would i do that?
That are my first steps with javascript / knockout, so please be kind.
If you handle the Server part of your application, you might want to return a Redirect Code 301 and specifying the URL to redirect.
Else, you can handle this Client Side, with the javascript code:
window.location.replace("./Home.html");

Categories

Resources