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,
})
);
});
Related
//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));
});
I am trying to send form data as json to my device (with XMLHttpRequest).
My form have multiple required fields, and should not submit if mandatory fields are empty. But form data sends even field empty!
I searched, and add event.preventDefault(); but it's not work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>first assignment</title>
<script>
function curlcheck() {
event.preventDefault();
event.stopImmediatePropagation();
var user_id = document.getElementById("user_id").value;
var pass = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/submit_test";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "ProgMode": user_id, "pass": pass }));
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("ajax_res").innerHTML = this.responseText;
console.log("success");
}
}
}
</script>
</head>
<body>
<div class="somebox"></div>
<ul>
<h3>Team 1 Online Exam System</h3>
</ul>
<form action="" method="POST">
<div name="form header" class="formhead">
<h1>Welcome</h1>
<p><span id="loginerr" class="err_alert"></span></p>
</div>
<div class="login_box">
<lable for="user_id">User ID</lable>
<input type="text" placeholder="Enter User ID" id="user_id" required>
<label for="password">Password</label>
<input type="password" placeholder="Enter Password" id="password" required>
<button id="but" type="submit" onclick="curlcheck(); return false">Login</button>
</div>
</form>
<div class="footer">
</div>
</body>
</html>
In HTML5, you do not need to check it by yourself, you can call the reportValidity() method to do the validation.
function curlcheck(form){
var user_id = document.getElementById("user_id");
var pass = document.getElementById("password");
if (user_id.reportValidity() && pass.reportValidity()){
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/submit_test";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "ProgMode": user_id.value, "pass": pass.value }));
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("ajax_res").innerHTML = this.responseText;
console.log("success");
}
}
}
return false;
}
<form action="" method="POST" onclick="return curlcheck(this);">
<div name="form header" class="formhead">
<h1>Welcome</h1>
<p><span id="loginerr" class="err_alert"></span></p>
</div>
<div class="login_box">
<lable for="user_id">User ID</lable>
<input type="text" placeholder="Enter User ID" id="user_id" required>
<label for="password">Password</label>
<input type="password" placeholder="Enter Password" id="password" required>
<button>Login</button>
</div>
</form>
If required data empty then return false from curlcheck function.
<script>
function curlcheck(event) {
event.preventDefault();
event.stopImmediatePropagation();
var user_id = document.getElementById("user_id").value;
var pass = document.getElementById("password").value;
if (user_id === "" || pass === "") {
return false; //or show required message
}
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/submit_test";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "ProgMode": user_id, "pass": pass }));
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("ajax_res").innerHTML = this.responseText;
console.log("success");
}
}
}
</script>
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'm new to web development and stucked at sending data to server. I have registration form and i want to send this data to server. I can send data from form tag using action and method attribute but it will return response in next page. So i read somewhere i have to use ajax to send data. I tried but i cannot send and capture data using script.
This is my reponse
{"success":true}
Html code
<div class="form">
<div class="formdetail">
<h3>Individual Registration</h3>
<label for="fname"> Name</label><br>
<input type="text" size="40" id="name" name="name" placeholder="Enter your name.." required><br><br>
<label for="phonenumber">Mobile Number</label>
<br/>
<input id="mobileno" size="40" name="mobileno" type="tel" size="20" maxlength="13" placeholder="Enter your mobile number..." type="number" required><br><br>
<label for="email">Email-Id</label><br>
<input type="text" size="40" id="email" name="email" placeholder="Enter your email-id..." required><br><br>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" name="dob" onclick="mydate();" hidden />
<input type="button" Value="Date of Birth" onclick="mydate();" />
<script>
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("dob").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("dob").value=dt+"/"+mn+"/"+yy
document.getElementById("dob").hidden=false;
document.getElementById("dt").hidden=true;
}
</script>
<br><br>
<label for="address">Address</label><br>
<input type="text" id="address" size="40" name="address" placeholder="Enter your address..." required><br><br>
<label for="country">Country</label><br>
<input type="text" id="country" size="40" name="country" placeholder="Enter your country name....." required><br><br>
<label for="State">State</label><br>
<input type="text" id="state" size="40" name="state" placeholder="Enter your state name....." required><br><br>
<label for="city">City</label><br>
<input type="text" id="city" size="40" name="city" placeholder="Enter your city name....." required><br><br>
<input type="hidden" name="category" value="Individual">
<input type="submit" value="Submit" id="someInput" onclick="ajax_post()"><br>
<p class="small">Institute Registraion</p>
</div>
</div>
</form>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "https://smilestechno.000webhostapp.com/Register.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if (hr.readyState == 4 && hr.status == 200) {
var resp = console.log(response);
if (resp == "true") {
}
}
hr.send("name="+ name + "&mobileno=" + mobileno + "&email=" + email + "&dob=" + dob + "&address=" + address + "&city=" + city + "&state=" + state + "&country=" + country );
document.getElementById("status").innerhtml = "processing";
}
you can not send variable in this format.
var vars = name+mobileno+email+dob+address+city+state+country;
Params must have a format like:
hr.send("fname=Henry&lname=Ford");
Code you need:
hr.send("name=" + name + "&monbileno=" + mobileno + ... );
You can use jquery to use ajax in a simple way.
Reference:
xmlhttprequest https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
jquery ajax https://www.w3schools.com/jquery/jquery_ref_ajax.asp
Use jquery, it makes it easier. This is how it should be using just the fname and email as an example with jquery ajax:
<form name="myForm" id="myForm" action="myActionUrl" method="POST">
<input type="text" name="fname" id="fname">
<input type="email" name="email" id="email">
<input type="submit" value="Submit">
</form>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$("#myForm").on("submit", function(event){
event.preventDefault(); //this prevents the form to use default submit
$.ajax({
method: "POST",
url: $(this).attr("action"), //this will use the form's action attribute
data: {fname: $("#fname").val(), email: $("#email").val()},
success: function(responseData){
//do something here with responseData
}
});
});
</script>
Please replace the "myActionUrl" part with the url/file that processes your data.
The file can be some basic php file which stores the data into some database and returns or echoes something back so that you can use it within the "responseData" on the ajax success function.
Hope this helps!
Please call function like this
onclick="ajax_post()"
not
onclick="ajax_post"
You used getElementById but selected a name attribute
have to use
getElementById('fname').value;
not
getElementById('name').value;
hey i would recommend using jquery to accomplish this task.
this isthe client script
script type="text/javascript" src='jquery.js'></script>
<!-- download the lates version -->
<script type="text/javascript">
ajax_post(){
var url = "https://smilestechno.000webhostapp.com/Register.php";
var name = $("#name").val();
var mobileno = $("#mobileno").val();
var email = $("#email").val();
var dob = $("#dob").val();
var address = $("#address").val();
var city = $("#city").val();
var state = $("#state").val();
var country = $("#country").val();
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'json',
'url':url,
'data':{name:name,mobileno:mobileno,email:email,dob:dob,address:address,city:city,state:state,country},
'success': function (data) {
tmp = data;
}
});
return tmp; // you can access server response from this tmp variable
}
Server side
<?php
//get items as post inputs
print_r($_POST[]);
echo $_POST['name'];
?>
I couldn't find any deep guide to ajax, especially for a php server side.
I currently try only to post the data to the PHP and test it before trying my luck with dumping to SQL.
Worked on it for 2 days, still not working. Guess it's a good time to head to stock overflow:
html+js:
<script>//send data scripts
var formNode = document.querySelector("#customerRegiForm");
var formData = new FormData(formNode);
var request = new XMLHttpRequest();
request.open("POST", "php/formSubmission.php", true);
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200){
document.getElementById("testing").innerHTML = request.responseTexts;
}
};
request.send(formData);
</script>
<form class="regiForm" id="customerRegiForm" onsubmit="return formValidation()">
<div>
Name: <input type="text" id="firstName" name="firstname" class="" required />
Family Name: <input type="text" id="lastName" name="lastname" class="" required />
</div>
<div>
Email: <input type="email" class="" id="email" name="email "required />
</div>
<div>
Phone Number: <input type="text" id="phone" name="phone" class="" required />
</div>
<div>
Country: <select name="country" class="countries" id="countryId" style="width: 100px">
<option value="">Select Country</option>
</select>
State: <select name="state" class="states" id="stateId">
<option value="">Select State</option>
</select>
City: <select name="city" class="cities" id="cityId">
<option value="">Select City</option>
</select>
</div>
<div>
Address: <input type="text" name="address" /><br />
</div>
<button type="submit">Submit</button>
</form>
<p id="testing"></p>
<?php
/**
* Created by PhpStorm.
* User: user
* Date: 17-Sep-16
* Time: 14:50
*/
echo $_POST['email'];
?>
also, any recommendations for videos and books in the subject?
I don't know if it's just a typo from your real code, but
request.responseTexts
should be
request.responseText
(the final "s" is not ok)
There are few things you need to change in your code, such as:
Look at the following <input> element,
<input type="email" class="" id="email" name="email "required />
^^^^^^^^^^^^^
Can you see that extra space after email? That's why on the PHP side, echo $_POST['email']; won't work. This <input> element should be like this:
<input type="email" class="" id="email" name="email" required />
Look at this JavaScript statement here,
document.getElementById("testing").innerHTML = request.responseTexts;
^^^^^^^^^^^^^^^^^^^^^
It should be,
document.getElementById("testing").innerHTML = request.responseText;
Look the the top <form> element,
<form class="regiForm" id="customerRegiForm" onsubmit="return formValidation()">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
But I see no formValidation() function in your code. Create a function named formValidation() and make sure you return false from that function, otherwise the form will get submitted each time you hit the submit button. So, your script should be like this:
<script>
function formValidation(){
var formNode = document.querySelector("#customerRegiForm");
var formData = new FormData(formNode);
var request = new XMLHttpRequest();
request.open("POST", "post.php", true);
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200){
document.getElementById("testing").innerHTML = request.responseText;
}
};
request.send(formData);
return false;
}
</script>