downloading pdf using jquery after submit function - javascript

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.

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

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

Remove the required attribute after the sucees of form submission

I have a form on click of submit the input box is highlighted with the red color border if it is empty. Now i have jquery ajax form submission on success of the form i will display a message "data submitted" and i will reset the form so all the input fields will be highlighted in red color. Now i want to empty the fields after the success of form submission and it should not be highlighted in red color.
HTML
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
}
else {
var ins_date = new Date($.now()).toLocaleString();
var parms = {
name: $("#name").val(),
email: $("#email").val(),
inserted_date: ins_date
};
var url2 = "http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data) {
console.log('Submission was successful.');
$(".alert-success").removeClass("d-none");
$(".alert-success").fadeTo(2000, 500).slideUp(500, function() {
$(".alert-success").slideUp(500);
});
$('.index-form')[0].reset();
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container index-form" id="index-validation" novalidate>
<input class="form-control" type="text" id="name" name="name" placeholder="Your name" required>
<input class="form-control" type="email" id="email" name="email" placeholder="Email Address" required>
<div class="invalid-feedback">Please Enter a Valid Email Id.</div>
<input type="submit" id="submit" class="btn btn-default btn-lg btn-block text-center" value="Send">
</form>
I'm not clear with your question, Do you want to reset form or remove the error class. But anyways I'll try solving out both :
SCRIPT
<script type="text/javascript">
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
} else {
var ins_date=new Date($.now()).toLocaleString();
var parms = {
name : $("#name").val(),
email : $("#email").val(),
inserted_date:ins_date
};
var url2="http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
//if you are removing specific property from class
$(".alert-success").css('display', 'none');
$(".alert-success").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-success").slideUp(500);
});
$("form")[0].reset();
console.log(data);
}, error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
</script>
Jquery doesn't support any method such as reset() of javascript, So you can trigger javascript's reset() method.
Feel free to ask doubts if stuck. Happy coding....!!!!!
$(this.('.index-form').find("input[type=text]").val("");
You can just empty the form value by giving the .val() as empty, you have to give this on after your ajax response.
and also instead of using fade in and fade out just try to use hide and show function both may work like same.

POST via Ajax does not work correctly

I looked now through a various number of StackOverflow pages and other websites - but can't find the correct solution for my problem. I try to post two values over to a php page via Post:
loginframe.php:
<form class="signin">
<input type="username" id="inputUsername" class="control" placeholder="Username" required autofocus>
<input type="password" id="inputPassword" class="control" placeholder="Password" required>
<div id="remember" class="checkbox">
<label>
<input type="checkbox" value="remember-me">Remember me
</label>
</div>
<button class="btn-login" type="submit" value="login" id="btn-login">Sign in</button>
</form>
My js:
$(document).ready(function(){
$("#btn-login").click(function(){
var username = $("#inputUsername").val();
var password = $("#inputPassword").val();
$.ajax(
{
type: "POST",
url: 'login.php',
data: {
user: username,
pass: password
},
success: function(result)
{
$("#result").html(result);
}
});
});
});
My login.php
<?php
if(isset($_POST['user']) && isset($_POST['pass']))
{
echo $_POST['user'];
echo $_POST['pass'];
} else {
include 'loginframe.php';
}
This login.php is just to check now if the data is passed. That is absolutely not the case. It always opens loginframe.php...
I can't find the error - I appreciate your help! Thank you a lot.
Use prevent default method.
$(document).ready(function(){
$("#btn-login").click(function(event){
event.preventDefault(); // this one prevents the default submission of the form
var username = $("#inputUsername").val();
var password = $("#inputPassword").val();
$.ajax(
{
type: "POST",
url: 'login.php',
data: {
user: username,
pass: password
},
success: function(result)
{
$("#result").html(result);
}
});
});
});

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