//i write a code to send message from form to my gmail but i get the following error failed to load resource the server responded with a status of 405
//(method not allowed)
HTML
<form class="contact-form">
<input type="text" name="" id="name" /> <br />
<input type="email" name="" id="email" /> <br />
<input type="text" name="" id="subject" /> <br />
<textarea name="" id="message" cols="30" rows="10"></textarea> <br />
<input type="submit" class="submit" value="Submit" />
</form>
JS
const contactForm = document.querySelector(".contact-form");
let fullName = document.getElementById("name");
let email = document.getElementById("email");
let subject = document.getElementById("subject");
let message = document.getElementById("message");
contactForm.addEventListener("submit", (e) => {
e.preventDefault();
let formData = {
name: fullName.value,
email: email.value,
subject: subject.value,
message: message.value,
};
let xhr = new XMLHttpRequest();
xhr.open("POST", "/");
xhr.setRequestHeader("content-type", "application/json");
xhr.onload = function () {
// error happens here
console.log(xhr.responseText);
if (xhr.responseText == "success") {
alert("email sent");
fullName.value = "";
email.value = "";
subject.value = "";
message.value = "";
} else {
alert("Something went wrong!");
}
};
xhr.send(JSON.stringify(formData));
});
Related
I am trying to implement a Contact from with custom Captcha using PHPmailer. The contact form works fine. The PHPmailer works fine as well. To avoid a lot of spam letters, I decided to implement custom Captcha, the problem is that the emails go anyway captcha is correct or incorrect.
<h4 class="sent-notification"></h4>
<form id="myForm">
<p>
<label>Name<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="name" type="text" name="name" required>
</p>
<p>
<label>Company<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="subject" type="text" name="company" required>
</p>
<p>
<label>Email<span style="color:#ff0000; margin-left:5px;">*</span></label>
<input id="email" type="email" name="email" required>
</p>
<p class="full">
<label>Message<span style="color:#ff0000; margin-left:5px;">*</span></label>
<textarea id="body" name="message" rows="5" required></textarea>
</p>
<div class="contain">
<input type="text" id="capt" readonly="readonly">
<div id="refresh"> <img src="assets/img/icons/refresh.png" alt="refresh" width="50px" onclick="cap()"></div>
<input type="text" id="textinput" placeholder="Refresh to type Captcha" required>
<button onclick="validcap()">Check</button>
</div>
<p>
<button class="full" onclick="sendEmail()" value="Send An Email">Submit</button>
</p>
</form>
Script for PHPmailer
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
var textinput = $("#textinput");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body) && isNotEmpty(textinput)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val(),
textinput: textinput.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>
Script for Captcha
<script type="text/javascript">
function cap() {
var alpha=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V'
,'W','X','Y','Z','1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var a=alpha[Math.floor(Math.random()*62)];
var b=alpha[Math.floor(Math.random()*62)];
var c=alpha[Math.floor(Math.random()*62)];
var d=alpha[Math.floor(Math.random()*62)];
var e=alpha[Math.floor(Math.random()*62)];
var f=alpha[Math.floor(Math.random()*62)];
var sum=a + b + c + d + e + f;
document.getElementById("capt").value=sum;
}
function validcap() {
var string1 = document.getElementById('capt').value;
var string2 = document.getElementById('textinput').value;
if (string1 == string2){
alert("Form is validated Succesfully");
return true;
}
else {
alert("Please enter a valid captcha");
return false;
}
}
</script>
I am having problems while using Javascript SMTP to send emails.I first tried in PHP but it didn't work so I chose JavaScript,I have been looking this for a week.
MY HTML CODE:
<head>
<link rel="stylesheet" href="style.css">
<script src="app.js"></script>
<script src="https://smtpjs.com/v3/smtp.js"></script>
</head>
<body>
<div class="container">
<form id="contact" method="post">
<h3>Checkout</h3>
<h4>Get your reply with in 24 hours!</h4>
<fieldset>
<input placeholder="Full Name" type="text" name="name" id="name" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<input placeholder="Email Address" type="email" name="email" id="email" tabindex="2" required>
</fieldset>
<fieldset>
<input placeholder="Phone Number" type="text" name="subject" id="subject" tabindex="3" required>
</fieldset>
<fieldset>
<textarea placeholder="Type your Address Here...." name="message" id="message" tabindex="5" required></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending" onclick="sendemail(this.form)">Submit</button>
</fieldset>
</form>
</div>
</body>
MY JAVASCRIPT CODE:
function sendemail(form) {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var subject = document.getElementById("subject").value;
var address = document.getElementById("message").value;
Email.send({
Host: "smtp.gmail.com",
Username : "shaheermkhan786#gmail.com",
Password : "xxxxxxx", // My Password
To : 'crispytntoffical#gmail.com',
From : "Sender Email " + email,
Subject : "Phone Number " + subject,
Body : "Address " + address,
}).then(
message => alert("Order has been placed successfully")
);
}
Use this code as SMTP.js:
/* SmtpJS.com - v3.3.2 */
var Email = { send: function (a) { return new Promise(function (n, e) { a.nocache = Math.floor(1e6 * Math.random() + 1), a.Action = "Send"; var t = JSON.stringify(a); Email.ajaxPost("https://smtpjs.com/v3/smtpjs.aspx?", t, function (e) { n(e) }) }) }, ajaxPost: function (e, n, t) { var a = Email.createCORSRequest("POST", e); a.setRequestHeader("Content-type", "application/x-www-form-urlencoded"), a.onload = function () { var e = a.responseText; null != t && t(e) }, a.send(n) }, ajax: function (e, n) { var t = Email.createCORSRequest("GET", e); t.onload = function () { var e = t.responseText; null != n && n(e) }, t.send() }, createCORSRequest: function (e, n) { var t = new XMLHttpRequest; return "withCredentials" in t ? t.open(e, n, !0) : "undefined" != typeof XDomainRequest ? (t = new XDomainRequest).open(e, n) : t = null, t } };
I have this form and I want to use its information to create a product using my API but it creates a empty object in my Mongo database. I´ve tried to enter pre defined information and it worked
<form id="form">
<label>Nome do Produto</label> <br />
<input type="text" id="name" name="name" required /><br />
<label>Quantidade do Produto</label> <br />
<input type="number" id="quantity" name="quantity" required /><br />
<label>Descricao</label><br /><br />
<input type="textbox" id="description" name="description" required /><br />
<button id="button">Criar</button>
<div id="result"></div>
</form>
<script>
var button = document.getElementById("button");
button.addEventListener("click", (event) => {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log("Test");
}
};
xhttp.open("POST", `http://localhost:3000/apiv1/products`, true);
xhttp.setRequestHeader("Accept", "application/json");
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(
JSON.stringify({
name: req.body.name,
description: req.body.description,
quantity: req.body.quantity,
})
);
});
How can I take value results from this form?
<form name="forma" method="post" action="index.php" id="dunja" >
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" />
</p>
</form>
And, JS is:
function sakupiPodatke(form){
var delovi = [];
var elementi = form.elements;
for(var i=0; i<elementi.length; i++){
var element = elementi[i];
var naziv = encodeURIComponent(element.name);
var vrednost = encodeURIComponent(element.value);
delovi.push(naziv + "=" + vrednost);
}
return delovi.join("&");
}
var teloZahteva = sakupiPodatke(document.forma);
console.log(teloZahteva);
also Php file is simple:
<?php
$ime = $_POST["txtIme"];
$email = $_POST["txtEmail"];
?>
so...my question is how to read variable "teloZahteva" from JS in console.log?
Your code is running when the page first loads, before the user has had a chance to fill in the form. So it will display empty values in the console.
Put the code in an event listener that runs when the user clicks the submit button.
document.getElementById("dunja").addEventListener("submit", function(e) {
e.preventDefault();
var teloZahteva = sakupiPodatke(e.target);
console.log(teloZahteva);
});
function sakupiPodatke(form) {
var delovi = [];
var elementi = form.elements;
for (var i = 0; i < elementi.length; i++) {
var element = elementi[i];
var naziv = encodeURIComponent(element.name);
var vrednost = encodeURIComponent(element.value);
delovi.push(naziv + "=" + vrednost);
}
return delovi.join("&");
}
<form name="forma" method="post" action="index.php" id="dunja">
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" />
</p>
</form>
This displays the form values in the console instead of sending the form to PHP.
After my code I wrote this code and it says:
Uncaught ReferenceError: createXHR is not defined
function formPost(url, form, callback){
var xhr = createXHR();
var data = sakupiPodatke(form);
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
var status = xhr.status;
if ((status >= 200 && status < 300) || status === 304){
callback(xhr.responseText);
}else{
alert("Greskica!");
}
}
};
xhr.send(data);;
}
function procesOdgovora(odgovor){
alert(odgovor);
}
formPost("index.php", document.forma, procesOdgovora);
<form name="forma" method="post" action="index.php" id="dunja" >
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" onclick="handleSubmit()" />
</p>
</form>
handleSubmit(){
var ime =getElementById('ime').value;
var mail =getElementById('mail').value;
}
I am trying to submit a form without doing a hard refresh but my page is refreshing. I tried putting action=“javascript:void(0);" in the form tag but that didn't work. I also cannot use jquery.
Work Flow that causes error:
Submitting a form that is supposed to send some information to a php file.
Page gets directed to another page that doesn't exist.
function toggle_visibility(id){
var e = document.getElementById(id);
if(e.style.visibility == 'hidden'){
e.style.visibility = 'visible';
}
else{
e.style.visibility = 'hidden';
}
}
function createAjaxRequestObject() {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
// Create the object
return httpRequest;
}
function sendTicket() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var email = document.getElementById("email").value;
var subject = document.getElementById("subject").value;
var msg = document.getElementById("msg").value;
var encFirst = encodeURIComponent(firstName);
var encLast = encodeURIComponent(lastName);
var encEmail = encodeURIComponent(email);
var encsubject = encodeURIComponent(subject);
var encmsg = encodeURIComponent(msg);
var info = "firstName="+encFirst+"&lastName="+encLast+"&email="+encEmail+"&subject="+encsubject+"&msg="+encmsg;
var http3 = createAjaxRequestObject();
if (http3.readyState == 4) {
if (http3.status == 200){
var result = JSON.parse(http3.responseText);
console.log(result);
}
}
http3.open("POST", "send_mail.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
</script>
Welcome!
View My Tickets
Submit Ticket
Change my Password
Full Name
Email
Subject
Your Message *
You should change the type of you input from submit to button so the sendTicket() will be triggered, else the form will be submited before reached your sendTicket() function so it should be :
<input type="button" value="Submit" onclick="sendTicket();" />
Instead of :
<input type="submit" value="Submit" onclick="sendTicket();" />
Hope this helps.
function sendTicket() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var email = document.getElementById("email").value;
var subject = document.getElementById("subject").value;
var msg = document.getElementById("msg").value;
var encFirst = encodeURIComponent(firstName);
var encLast = encodeURIComponent(lastName);
var encEmail = encodeURIComponent(email);
var encsubject = encodeURIComponent(subject);
var encmsg = encodeURIComponent(msg);
var info = "firstName="+encFirst+"&lastName="+encLast+"&email="+encEmail+"&subject="+encsubject+"&msg="+encmsg;
console.log(info);
}
<h1>Welcome! </h1>
<div id="buttons">
<button class="myButton" onclick="showTickets(); toggle_visibility('table');">View My Tickets</button>
<button class="myButton" onclick="toggle_visibility('Submit');">Submit Ticket</button>
<button class="myButton" onclick="toggle_visibility('changePassword');">Change my Password</button>
</div>
<div id = "table"> </div>
<div id = "Submit">
<form id = "emailForm" action="javascript:void(0);">
<ul class="form-style-1">
<li><label>Full Name <span class="required">*</span></label><input type="text" name="firstName" class="field-divided" placeholder="First" id="firstName" /> <input type="text" name="field2" class="field-divided" placeholder="lastName" id = "lastName" /></li>
<li>
<label>Email <span class="required">*</span></label>
<input type="email" name="email" class="field-long" id= "email" />
</li>
<li>
<label>Subject</label>
<input type="text" name="subject" class="field-divided" placeholder="Subject" id="subject" />
</li>
<li>
<label>Your Message <span class="required">*</span></label>
<textarea name="msg" id="msg" class="field-long field-textarea"></textarea>
</li>
<li>
<input type="button" value="Submit" onclick="sendTicket();" />
</li>
</ul>
</form>
</div>
<br><br><br><br><br><br><br><br>