Enable browser autocomplete when submitting a form via ajax - javascript

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"
...

Related

Javascript function to validate form by ASP.NET Core Jquery validation

I'm trying to validate an ASP.NET Core form without refreshing the page by ASP.NET Core JQuery validation (the one provided in the project). The validation is working properly when I post the form normally. But I want to post the form with AJAX, so I run the preventDefault() js function to do the submission manually by ajax. But it seems that this function is breaking the validation (The one that works without refresh). It means that even if the form has errors, it submits!
This is my cshtml file:
#page
#model Baunity.Web.Pages.Dash.EditProfileModel
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<p id="verificationAlert" style="display: none !important;" class="alert alert-success">text</p>
#section Scripts {
#{
await Html.RenderPartialAsync ("_ValidationScriptsPartial");
}
}
<form method="post">
<input asp-for="Email" />
<label asp-for="Email"></label>
<span asp-validation-for="Email"></span>
<br />
<input asp-for="Username" />
<label asp-for="Username"></label>
<span asp-validation-for="Username"></span>
<br />
<input asp-for="Password" />
<label asp-for="Password"></label>
<span asp-validation-for="Password"></span>
<br />
<input asp-for="ConfirmPassword" />
<label asp-for="ConfirmPassword"></label>
<span asp-validation-for="ConfirmPassword"></span>
<br />
<input asp-for="FirstName" />
<label asp-for="FirstName"></label>
<span asp-validation-for="FirstName"></span>
<br />
<input asp-for="LastName" />
<label asp-for="LastName"></label>
<span asp-validation-for="LastName"></span>
<br />
<div id="verificationForm" style="display: none !important;">
<input asp-for="VerificationCode" />
<label asp-for="VerificationCode"></label>
<span asp-validation-for="VerificationCode"></span>
</div>
<div asp-validation-summary="ModelOnly"></div>
<br />
FIX DOING OTHER STUFF LIKE SETTING VALUES AT BACKEND
<input type="submit" id="submit" onclick="SubmitForm(this.parentElement, event)" />
</form>
<p>#ViewData["DONE"]</p>
site.js
let isVerificationEmailSent = false;
function SubmitForm(frm, caller) {
debugger;
if (!isVerificationEmailSent) {
caller.preventDefault();
}
else {
return;
}
var fdata = new FormData();
var emailData = $('#Email').val();
fdata.append("Email", emailData);
var usernameData = $('#Username').val();
fdata.append("Username", usernameData);
var passwordData = $('#Password').val();
fdata.append("Password", passwordData);
var confirmPasswordData = $('#ConfirmPassword').val();
fdata.append("ConfirmPassword", confirmPasswordData);
var firstNameData = $('#FirstName').val();
fdata.append("FirstName", firstNameData);
var lastNameData = $('#LastName').val();
fdata.append("LastName", lastNameData);
let isSuccess = true;
$.ajax(
{
type: frm.method,
url: frm.action,
headers:
{
"XSRF-TOKEN": $("input[name='__RequestVerificationToken']").val()
},
data: fdata,
processData: false,
contentType: false,
statusCode: {
912: function (responseObject, textStatus, jqXHR) {
$("#verificationForm").show();
$("#verificationAlert").show();
isVerificationEmailSent = true;
},
},
success: function (data) {
alert(data);
isSuccess = true;
},
error: function (data) {
if (!isSuccess) {
alert('ERROR' + data);
}
}
})
}
I've tried to use valid() & validate() function in jquery, but it gave me error. I want a method similar to these two.
If you don't wanna use submit button to submit the form, Why do you set the type="submit"? You can just set the button like:
<button type="button" onclick="SubmitForm(this.parentElement)">submit</button>
In this case, You don't need to use event.preventDefault() anymore.
set an id for the form:
<form method="post" Id="Form">...</form>
Then in your js code:
let isVerificationEmailSent = false;
function SubmitForm(frm) {
$('#Form').validate();
if ($('#Form').valid() === true) {
var fdata = new FormData();
var emailData = $('#Email').val();
fdata.append("Email", emailData);
var usernameData = $('#Username').val();
fdata.append("Username", usernameData);
var passwordData = $('#Password').val();
fdata.append("Password", passwordData);
var confirmPasswordData = $('#ConfirmPassword').val();
fdata.append("ConfirmPassword", confirmPasswordData);
var firstNameData = $('#FirstName').val();
fdata.append("FirstName", firstNameData);
var lastNameData = $('#LastName').val();
fdata.append("LastName", lastNameData);
let isSuccess = true;
$.ajax(
{
type: frm.method,
url: frm.action,
headers:
{
"XSRF-TOKEN": $("input[name='__RequestVerificationToken']").val()
},
data: fdata,
processData: false,
contentType: false,
statusCode: {
912: function (responseObject, textStatus, jqXHR) {
$("#verificationForm").show();
$("#verificationAlert").show();
isVerificationEmailSent = true;
},
},
success: function (data) {
alert(data);
isSuccess = true;
},
error: function (data) {
if (!isSuccess) {
alert('ERROR' + data);
}
}
})
}
}

downloading pdf using jquery after submit function

in this code from https://www.codingsnow.com/2021/01/create-php-send-email-contact-form.html
<center>
<h4 class="sent-notification"></h4>
<form id="myForm">
<h2>Send an Email</h2>
<label>Name</label>
<input id="name" type="text" placeholder="Enter Name">
<br><br>
<label>Email</label>
<input id="email" type="text" placeholder="Enter Email">
<br><br>
<label>Subject</label>
<input id="subject" type="text" placeholder=" Enter Subject">
<br><br>
<p>Message</p>
<textarea id="body" rows="5" placeholder="Type Message"><textarea><!--textarea tag should be closed (In this coding UI textarea close tag cannot be used)-->
<br><br>
<a id="linkID" href="#" >
<button type="button" class="btn btn-primary" onclick="sendEmail()" value="Send An Email"
>Submit</button>
</a>
</form>
</center>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('.sent-notification').text("Message Sent Successfully.");
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() == "") {
caller.css('border', '1px solid red');
return false;
} else
caller.css('border', '');
return true;
}
</script>
when I click the submit button, I want to download a pdf called "./sales.pdf" only when the submit is a success
this is what i tried to change in the code in the script, i have added $('#linkID').attr({target: '_blank', href : url}); but this does not give any result, nothing downloads
also in phpmailer...if i try to add three forms on the same page, they all stop working..is it related to script integrity?
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
var url = "./Sales.pdf";
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name:email.val(),
email: email.val(),
subject: body.val(),
body: body.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('#linkID').attr({target: '_blank', href : url});<<<<<----this
}
});
}
Since jQuery 3.0, success: function does no more work as it has been suppressed, see https://api.jquery.com/jquery.ajax/ .
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use
jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
But you can use this arrangement for the new sendMail():
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendMail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val()
}
})
.done(function(response) {
//alert(response.status);
$('#myForm')[0].reset();
$('#linkID').attr({target: '_blank', href : "./sales.pdf", download: "download"});
$('#linkID')[0].click();
})
;
}
}
When you press submit, after sending mail, sales.pdf will be automatically downloaded.

How post input value of an element by name with jQuery and ajax

I have to post the forms with post method in jquery, what is the correct syntax?
The modules a, b, c are multiple.
I have to send everything via post and receive the response via alert.
This is my code:
<input type="text" name="type">
<input type="text" name="model">
<input type="text" name="a[]">
<input type="text" name="b[]">
<input type="text" name="c[]">
<input type="text" name="a[]">
<input type="text" name="b[]">
<input type="text" name="c[]">
$('#start').click(function(){
var type = $('input[name=type]').val()
var model = $('input[name=model]').val()
var a = [];
$('input[name="a[]"]').each(function() {
a.push($(this).val());
});
var b = [];
$('input[name="b[]"]').each(function() {
b.push($(this).val());
});
var c = [];
$('input[name="c[]"]').each(function() {
c.push($(this).val());
});
var send = .....({
type:type:,model:model,a:a,b:b,c:c
});
$.ajax({
url: '.post.php',
type: 'POST',
data: {send:send},
success: function(data) {
//alert(data);
}
});
Try something like:
var send = function() {
return {
type:type,
model:model,
a:a,
b:b,
c:c
};
});
$.ajax({
url: 'post.php',
type: 'POST',
data: {send:send()},
success: function(data) {
alert(data);
}
});

ajax function starts after second click

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();
}
},
. . .

Magento newsletter ajax request returns null

I am trying to send a newsletter subscription request to Magento, but It returns null and nothing happens.
I've searched around and found very different URLs to post the request. And also grabbed the code from the file from base template.
In fact, maybe I am not sending the correct parameters or whatever.
This is the code in use:
<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
<input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
<button type="submit" id="ajax-newsletter-submit" title="CADASTRAR"
class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>
</div>
</form>
Javascript:
var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');
$j(function() {
$j("#ajax-newsletter-submit").click(function() {
var email =$j("#newsletter").val();
var url=$j(".url").val();
var dataString = 'email='+ email;
if(email=='') {
$j("#newsletter").focus();
} else {
var a = email;
var filter = /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
if(filter.test(a)){
$j.ajax({
type: "POST",
url: url,
data: dataString,
success: function(){
alert('Assinatura realizada com sucesso!');
$j("#newsletter").val('');
}
});
} else {
$j("#newsletter").focus();
}
}
return false;
});
});
Try this code,
var val_form = new VarienForm('your form id');
jQuery("#your form id").submit(function(e)
{
if (val_form.validator && val_form.validator.validate())
{
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Failure');
}
});
this.reset(); //form field reset
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}
});

Categories

Resources