Getting XMLHttpRequest erros on ajax Post - javascript

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
});

Related

MS Edge: form submitted even if return false

I got a strange problem when creating a login form for a website I create for work. I know it has been posed a million times but my case only breaks in Edge.
Principle is: I have a form with username and password. When submitting the form user and pass is validated and logged in in ajax (and returns error if so). If valid it redirects to the main user. (simple, no?)
Problem is that the page is refreshed anyway even if the form have return: false, but only in Microsoft Edge. It works on Chrome, IE (even in document mode 10) and Firefox with no problems.
Code in action:
<!-- jQuery + validate plugins are already loaded -->
<form id="loginform" method="post" class="">
<div class="navbar-login panel">
<div class="panel-heading">
<h4 class="panel-title">Connexion au cours</h4>
</div>
<div class="panel-body">
<div id="login-warning"></div>
<div class="form-group col-md-12">
<input class="form-control" style="width: 100%;" placeholder="Adresse email" name="LOGIN_EMAIL" type="email">
</div>
<div class="form-group col-md-12">
<input class="form-control" style="width: 100%;" placeholder="Mot de passe" name="LOGIN_PASSWORD" type="password">
</div>
</div>
<div class="panel-heading text-right" style="display: table;width: 100%;">
<button type="submit" style="float: right;display: inline-block;" class="btn btn-info">Connexion</button>
</div>
</div>
</form>
JS:
$("#loginform").validate({
debug: false,
rules: {
LOGIN_EMAIL: {
required: true,
email: true
},
LOGIN_PASSWORD: {
minlength: 6
}
}
});
$("#loginform").submit(function(e){
var f = $(this);
if(f.valid()){
$.ajax({
url: "req/ajx_login.php",
type:"POST",
cache: false,
async: false,
data: f.serialize(),
success: function(data, status, xhr){
// data is "success" if successed, anything else if failed
if(data == "success"){
location = "/cours";
}else{
$("#login-warning").html(data);
}
}
});
}
return false;
});
Can someone help? Thanks for future answers.

prevent form POST redirect from happening, but still keep bootstrap validation

So I have a form that I want to submit via AJAX. I use bootstrap, bootstrap material design, jquery and PHP codeigniter on the back-end.
Here is my problem: I want the html5/bootstrap validation to work, but I want the POST request to be sent via AJAX and not via redirect. Hence event.preventDefault() isn't an option... or so I think.
Any help is apreciated, thanks!
Here is my JS
$(document).ready(function(){
$.material.init();
$(".submit_form").click(function(event){
if ($('.reservation_form')[0].checkValidity()){
$('.app_loading').fadeIn('fast');
var input=$('.reservation_form :input');
var values = {};
var i=0;
console.log(input);
input.each(function() {
if (i==5){
values[i] = $(this).val();
}
else{
values[i] = $(this).val();
i++;
}
});
console.log(values);
jQuery.ajax({
type: "POST",
url: "https://code-igniter-blog-asergey91.c9users.io/index.php/reservation/make_reservation",
dataType: 'json',
data: {
email: values[0],
first_name: values[1],
last_name: values[2],
tel: values[3],
size: values[4],
start: values[5],
},
success: function(){
},
fail: function(){
$('.app_loading').fadeOut('fast');
$('.error_capacity').fadeIn('fast');
}
});
}
else{
$('.app_loading').fadeIn('fast');
$('.app_loading').fadeOut('fast');
}
});
});
Here is my HTML
<div class='container-fluid'>
<div class='row'>
<div class='col-xs-10 col-xs-offset-1 col-md-8 col-md-offset-2 col-lg-4 col-lg-offset-4'>
<div class='well customer_input'>
<form class="form-horizontal reservation_form">
<fieldset>
<legend class='text-center'>Make a Reservation</legend>
<div class='text-center'>Opening Hours:<br>Mon-Sat<br>8:00 AM - 8:00 PM</div>
<div class="form-group">
<label for="inputEmail" class="col-md-2 control-label">Email</label>
<div class="col-md-10">
<input type="email" class="form-control" id="inputEmail" placeholder="Email" required>
</div>
</div>
<div class="form-group">
<label for="inputFirstName" class="col-md-2 control-label">First Name</label>
<div class="col-md-10">
<input type="text" class="form-control" id="inputFirstName" placeholder="First Name" required>
</div>
</div>
<div class="form-group">
<label for="inputLastName" class="col-md-2 control-label">Last Name</label>
<div class="col-md-10">
<input type="text" class="form-control" id="inputLastName" placeholder="Last Name" required>
</div>
</div>
<div class="form-group">
<label for="inputTel" class="col-md-2 control-label">Tel(+32)</label>
<div class="col-md-10">
<input type="tel" class="form-control" id="inputTel" placeholder="Telephone Number" required>
</div>
</div>
<div class="form-group">
<label for="inputParty" class="col-md-2 control-label">Party Size</label>
<div class="col-md-10">
<select id="inputParty" class="form-control" required>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputTime" class="col-md-2 control-label">Date+Time</label>
<div class="col-md-10">
<input type="datetime-local" class="form-control" id="inputTime" required>
</div>
</div>
<div class='app_loading text-center'>
<br>
<img src='../../assets/img/loading-dots.gif'>
</div>
<div class="form-group app_submit">
<div class='text-center'>
<button type="submit" class="btn btn-primary btn-raised submit_form">Submit</button>
</div>
</div>
</fieldset>
</form>
<div class="alert alert-dismissible alert-danger error_capacity">
<button type="button" class="close" data-dismiss="alert">×</button>
Sorry, this is an error message
</div>
</div>
</div>
</div>
<div class='row'>
<div class='col-xs-8 col-xs-offset-2 col-md-6 col-md-offset-3 col-lg-4 col-lg-offset-4'>
<div class='well customer_success'>
<h1 class='text-center'><span class='glyphicon glyphicon-ok'></span><br><br>Your Reservation Has Been Made<br><br>Thank You<br></h1>
</div>
</div>
</div>
</div>
Jquery Forms will be useful in this case. This will submit your form with Ajax without redirection.
Sample code:
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
// bind to the form's submit event
$('#myForm2').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
// formData is an array; here we use $.param to convert it to a string to display it
// but the form plugin does this for you automatically when it submits the data
var queryString = $.param(formData);
// jqForm is a jQuery object encapsulating the form element. To access the
// DOM element for the form do this:
// var formElement = jqForm[0];
alert('About to submit: \n\n' + queryString);
// here we could return false to prevent the form from being submitted;
// returning anything other than false will allow the form submit to continue
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
// for normal html responses, the first argument to the success callback
// is the XMLHttpRequest object's responseText property
// if the ajaxSubmit method was passed an Options Object with the dataType
// property set to 'xml' then the first argument to the success callback
// is the XMLHttpRequest object's responseXML property
// if the ajaxSubmit method was passed an Options Object with the dataType
// property set to 'json' then the first argument to the success callback
// is the json data object returned by the server
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
Try to use
$( "form" ).submit(function( event ) {
event.preventDefault();
});
Remember you don't have to listen for click on any form submit button because any button in the form will submit it automatically as this is its default behavior
try adding
return false;
$(".submit_form").click(function(event){
if ($('.reservation_form')[0].checkValidity()){
$('.app_loading').fadeIn('fast');
var input=$('.reservation_form :input');
var values = {};
var i=0;
console.log(input);
input.each(function() {
if (i==5){
values[i] = $(this).val();
}
else{
values[i] = $(this).val();
i++;
}
});
console.log(values);
jQuery.ajax({
type: "POST",
url: "https://code-igniter-blog-asergey91.c9users.io/index.php/reservation/make_reservation",
dataType: 'json',
data: {
email: values[0],
first_name: values[1],
last_name: values[2],
tel: values[3],
size: values[4],
start: values[5],
},
success: function(){
},
fail: function(){
$('.app_loading').fadeOut('fast');
$('.error_capacity').fadeIn('fast');
}
});
}
else{
$('.app_loading').fadeIn('fast');
$('.app_loading').fadeOut('fast');
}
return false;

Ajax function reloads the page with some parameter on response

I am working on an application where user submit his/her information in tabs...
After .onclick() function, data is submitted to action and saved correctly and returned "success" successfully redirect user to login page...
I have returned two responses so far, "success" and "fail"
But the problem really is, when returning "false"...console.log shows the response correctly, although the work i'd like to perform on "fail" isn't really working..and page reloads with some parameters(i will show it in snapshot)....
Html
<form class="form-horizontal" id="default" name="myform">
<fieldset title="Step1" class="step" id="default-step-0">
<div class="form-group">
<label class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="email" class="form-control" id="Email1" required>
<label id="err1" class="col-lg-6 control-label" "></label>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" name="password1" class="form-control" id="password1" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Confirm Password</label>
<div class="col-lg-10">
<input type="password" name="confirmpassword1" class="form-control" id="confirmpassword1" required>
<label id="passMatch" class="col-lg-6 control-label""></label>
</div>
</div>
</fieldset>
<fieldset title="Step 2" class="step" id="default-step-1">
//some other input fields on 2nd tab
</fieldset>
<input type="button" class="finish btn btn-danger" value="Save" id="btnSubmitAll" />
</form>
Ajax
<script>
$("#btnSubmitAll").click(function (event) {
event.preventDefault();
var Email = $('#Email1').val();
var password = $('#password1').val();
var confirmpassword = $('#confirmpassword1').val();
$.ajax({
type: "POST",
url: '#Url.Action("Submit", "Home")',
dataType: "JSon",
async: false,
data: {"Email": Email, "password": password, "confirmpassword": confirmpassword},
success: function (data) {
if (data == "success")
{
window.location.href = '#Url.Action("login","Home")';
console.log(data);
}
else {
$('#err1').html("Email Exist");
console.log(data);
}
},
error: function (data, jqXHR, exception) {
//some errors in if/else if/else
}
}
});
});
</script>
Please remember, when data == "success", all things go right(returns success after successfull record insertion), but when "fail" returned, console shows it correctly but label not updated with the message and also the whole page reloads with some parameters from the form inputs as can be seen below...
InAction
if (objIdHelper.IsUserExist(Email))
{
return this.Json ("fail");
}
else
{
//some process
return this.Json ("success");
}
I am surely missing some logic or doing something stupid, please help....
Any kind of help will be appreciated...thanks for your time
Check for the argumet passed in the success callback..Also note that you have wrong understanding for error callback. It wont execute if there are any errors in success callback conditions. It is to handle network errors.
Your if statement if (data == "success") uses data instead of data1 like the function specifies.

PHP Post on Bootstrap submitHandler

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}

Posting data using AJAX while using knockout bindings

I am finding it difficult to send data to the controller through Ajax post since the object to be sent to the controller cannot be used within the ajax post because of the structure of my code.I am using knockout for data-binding the click event of the Update button.
This is my code
$(document).ready(function () {
var provider = function () {
var self = this;
self.providerID = ko.observable(providerEditInfo.ProviderID);
self.firstName = ko.observable(providerEditInfo.FirstName);
self.lastName = ko.observable(providerEditInfo.LastName);
self.contactEmail = ko.observable(providerEditInfo.ContactEmail);
self.NPI = ko.observable(providerEditInfo.NPI);
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: { providerForUpdate }, -- Cant send this
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
self.cancelEdits = function () {
if (confirm("Are you sure you want to Cancel?")) {
window.location.href = "/Provider/ShowTheListOfProviders";
}
};
}; //End of Constructor.
var providerForUpdate = new provider();
ko.applyBindings(providerForUpdate);
});
On the clck of Update Button,I am calling the 'updateProviderDetails' method.
HTML
#model Greenway.Demo.DataAccess.Entity.Provider
<body>
<div class="container">
<h1 class="col-sm-offset-2">Edit Provider Details:</h1>
<br />
<form class="form-horizontal" role="form" id="editProviderDetailsForm">
<div class="form-group">
<label class="col-sm-2 control-label labelfont">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" autofocus="autofocus" placeholder="Enter the First Name" id="firstName" name="firstName" data-bind="value:firstName , event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Last Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Enter the Last Name" id="lastName" name="lastName" data-bind="value:lastName ,event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group text-center">
<button type="Submit" data-bind="click: updateProviderDetails" class="btn btn-primary">Update</button>
<button type="button" data-bind="click: cancelEdits" class="btn btn-primary">Cancel</button>
</div>
</form>
</div>
</body>
<script type="text/javascript">
var providerEditInfo = #Html.Raw(Json.Encode(Model));
</script>
<script type="text/javascript" src="../../App_Scripts/Shared/Functions.js"></script>
Could someone guide me on how I can send the data to the controller with this code structure.I can't put updateProviderDetails outside the constructor because otherwise, I can't bind it.
Use ko.toJSON to serialize your view model to json:
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
This is also in the Knockout Tutorial

Categories

Resources