I have following Code. But the String in the Database is empty. Why does it not work to get the string from the input field?
HTML
<div id="todo">
<h2>Todo Liste</h2>
<form method="get">
<input type="text" name="username" placeholder="name" required>
<input type="text" class="inputField" name="inputData" id="myInput" placeholder="title" required><br><br>
<span onclick="newElement(); sendData(this.value)" class="addBtn">Add</span><br><br>
</form>
JavaScript
function sendData(str) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xmlhttp.open("GET", "saveData.php?q=" + str);
xmlhttp.send();
}
To get the Value on the html page:
<p>Response from PHP <span id="txtHint"></span></p>
to bring the data in the html
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
document.getElementById("myUL").appendChild(li);
}
and i want to get the data of the text, a user typed in. this is where i fail.
My idea was
console.log(document.getElementsByClassName("inputField"));
How can I get the element?
Related
I'm pretty new coder and only touched on JavaScript, but I'm trying to submit a form and get back the data as part of my school work, but according to google's DevTool its not saving into google's local storage, any help?
function submit() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var feedback = document.getElementById("feedback").value;
localStorage.setItem("name", name);
localStorage.setItem("email", email);
localStorage.setItem("feedback", feedback);
return true;
}
function init() {
var name = localStorage.getItem("name");
var email = localStorage.getItem("email");
var feedback = localStorage.getItem("feedback");
document.write("passed value = " + name);
document.write("passed value = " + email);
document.write("passed value = " + feedback);
}
HTML
<form action="form.html" method="get" onsubmit="submit()">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit" onclick="submit()">
</fieldset>
</form>
</section>
<script src="form.js" type="text/javascript"></script>
You have created a very pesky and hard to find bug there!
No it's not the event doubling in <input type="submit" value="Submit" onclick="submit()"> <input type="submit" value="Submit" onclick="submit()">
even though it can be considered a bad practice
Spot it?
it's submit()!
Try this and submit the form
<form action="form.html" method="get" onsubmit="alert(getAttributeNames()); submit()">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit" onclick="submit()">
</fieldset>
</form>
</section>
Surprised eh? You haven't defined getAttributeNames() anywhere yet it works! How is that you ask??
This is because it is one of many inbuilt DOM method that every html element inherits. Now you get the idea what happened when you used onsubmit="submit()" It didn't call the submit() function you wrote instead it called the inbuilt submit (form's native) method that submits it to server and once it submits obviously it won't do any localstorage business
The fix is simple just use names that won't collide with the built-in(s). Or you can also use addEventListener() because in that you can tell browser explicitly "no, use this function that I've written not the inbuilt one, please"
Here is a fixed version I just changed the name of your function
<form action="form.html" method="get" onsubmit="submit2()">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit" onclick="submit()">
</fieldset>
</form>
</section>
<script>
function submit2() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var feedback = document.getElementById("feedback").value;
localStorage.setItem("name", name);
localStorage.setItem("email", email);
localStorage.setItem("feedback", feedback);
return true;
}
function init() {
var name = localStorage.getItem("name");
var email = localStorage.getItem("email");
var feedback = localStorage.getItem("feedback");
document.write("passed value = " + name);
document.write("passed value = " + email);
document.write("passed value = " + feedback);
}
</script>
The thing is that localstorage cannot store objects, but you could always store json formatted objects as a string and parse it later whenever you want to you the data!
And also the form submission should be stopped before it refreshes the page! just by adding the return false on the onsubmit event.
<form action="form.html" method="get" id="myForm">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<script>
var myForm = document.querySelector("form#myForm");
myForm.onsubmit = function(){
const data = {};
const dataToFetch = this.querySelectorAll("input, textarea, button, select");
for(let element of dataToFetch){
if( element && element.tagName && element.name )
data[element.name] = element.value;
}
let jsonData = JSON.stringify( data );
localStorage.setItem("formData", jsonData);
alert("Data stored to localStorage itemName:'formData'");
return false;
}
</script>
I use a function for this so I can call it at any time.
// add to local storage
const addToLocalStorageObject = function (name, key, value) {
// Get the existing data
let existing = localStorage.getItem(name);
// If no existing data, create an object
// Otherwise, convert the localStorage string to an object
existing = existing ? JSON.parse(existing) : {};
// Add new data to localStorage object
existing[key] = value;
// Save back to localStorage via stringify
localStorage.setItem(name, JSON.stringify(existing));
};
// retrieve from local storage
const retrieveFromLocalStorageObject = function (name) {
let data = localStorage.getItem(name);
// read the localStorage item and convert it to an object
return data ? JSON.parse(data) : null;
};
Then call addToLocalStorageObject('name', name);
And retrieveFromLocalStorageObject('name');
NB: I did not write the above functions but I have found them extremely useful.
I have data like this.
js file
var numbers = 1234
Html file.
<label>Name</label>
<input type="text" class="form-control" name="name" id = "name">
<label>Id</label>
<input type="text" class="form-control" name="id" id = "id">
Requirement is:
whenever I enter my name in the first input box I want to display numbers from a javascript file into Id input box.
can we do with ajax call?
How to do that?
If I am not wrong, you want to insert a number into id textbox if you write something into name field, I am going to give you a sample example below:
Note: you don't need ajax call for the event handling.
var numbers = 1234;
function myFunction() { //Modify this by your requirement
var x = document.getElementById("id");
if(document.getElementById("name").value != '') {
x.disabled = true;
x.value = numbers;
} else {
x.disabled = false;
x.value = '';
}
}
<label>Name</label>
<input type="text" class="form-control" name="name" id = "name" onkeyup="myFunction()">
<label>Id</label>
<input type="text" class="form-control" name="id" id = "id">
I hope this help >
Your JS File Function:
function keypressCustom(){
var enteredName = $("#nameFieldID").val();
var IDValue = '';
//Your Ajax Call Here
$.ajax({url: "text_call_url", type: 'POST', // http method
data: { enteredName: enteredName }, success: function(result_id_value_from_ajax){
IDValue = result_id_value_from_ajax;
$("#idField").val(IDValue);
}});
}
Your Html >
<label>Name</label>
<input type="text" class="form-control" name="name" id="nameFieldID" onkeypress="keypressCustom()" value=''>
<label>Id</label>
<input type="text" class="form-control" name="id" id="idField" 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'];
?>
My form doesn't get submitted although I see the alert "Your message was sent!". Can anyone tell me what's wrong? Here're the codes I have written. I have a table called messages in my database to insert form data entered from HTML form. Thanks!
HTML file
<form action="javascript:contactSubmit();" name="front_home_contact">
<div class="front_home_details_field">
<input type="text" placeholder="Full Name" name="home_contact_field" required pattern="[A-z ]+"/>
</div>
<div class="front_home_details_field">
<input type="text" placeholder="Phone Number" name="home_contact_field" required pattern="0[0-9]{9}" maxlength="10"/>
</div>
<div class="front_home_details_field">
<input type="email" placeholder="E-mail" name="home_contact_field" required/>
</div>
<div class="front_home_details_field">
<input type="text" placeholder="Subject" name="home_contact_field" required pattern="[A-z s]+"/>
</div>
<div class="front_home_details_field" style="height:151px;">
<textarea placeholder="Message" name="home_contact_field" aria-invalid="false" required></textarea>
</div>
<input type="submit" value="Send" name="home_contact_field"/>
</form>
Javascript .js file
function contactSubmit(){
document.front_home_contact.setAttribute("novalidate","true");
var elems = document.getElementsByName("front_home_contact"); //or
var xhrx = (window.XMLHttpRequest)? new XMLHttpRequest(): new activeXObject("Microsoft.XMLHTTP");
var data = new FormData();
data.append("func","insertMsg");
data.append("arg",elems);
alert("Your message was sent!");
/*xhrx.onreadystatechange = function(){
if(xhrx.readyState==4 && xhrx.status==200){
reportSection.innerHTML= xhrx.responseText.trim();
httpComplete +=1;
if (httpComplete == 3) elem.style.display="block";
}
}*/
xhrx.open('post','insertMessages.php',true);
xhrx.send(data);
for (i = 0; i< elems.length;i++){
elems[i].value="";
}
}
PHP file (insertMessages.php)
<?php
include "config.php";
$function = $_POST['func'];
if ($function == "insertMsg"){
$query = "INSERT INTO `messages`(`SenderName`, `PhoneNumber`, `Email`, `Subject`, `Message`) VALUES ('".$_POST['args'][0]."');";
if(mysqli_query($con,$query)){
echo "<script type='text/javascript'>alert('OK');</script>";
}
else{
echo "<script type='text/javascript'>alert('error');</script>";
}
}
?>
Directly you can not display alert() from ajax response.
Define onreadystatechange and define the action you want to perform based on your response.
Directly don't pass script in php response.
Pass success / error (if possible just use JSON in sending response) and after receiving in response just check the value and perform action you want to perform.
like,
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if( this.responseText=="success"){
alert('OK');
}else{
alert('error');
}
}
};
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>