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'];
?>
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 am trying to insert a new product through a form with javascript into database in grapqhl server and also that product should be displayed in zonaB with javascript ,but i am getting the error 400 bad request. Could someone tell me where is the mistake
here is html code
'''
<form id="formular" action="#" method="POST">
<label>Numar produs:</label>
<input type="text" id="nr">
<label>Denumire produs:</label>
<input type="text" id="nume" ><br>
<label>Categorie produs: </label>
<input type="text" id="categorie"> <br>
<label>Descriere: </label>
<input type="text" id="descriere"><br>
<label>Imagine:</label>
<input type="text" id="imagine"><br>
<label> Pret:</label>
<input type="text" id="pret"><br>
<label> Disponibil:</label>
<input type="text" id="stoc"><br>
<button onmouseover="insereaza1()"> Insereaza</button>
</form>
<script>
var $id = $('#nr').val()
var $name = $('#nume').val()
var $id_categorie = $('#categorie').val()
var $descriere = $('#descriere').val()
var $imagine = $('#imagine').val()
var $pret = $('#pret').val()
var $stoc = $('#stoc').val()
function insereaza1() {
creareProdus={"query":"mutation{createProduct($id:ID!, $name:String, $id_categorie:ID,
$descriere:String, $imagine:String, $pret:Float, $stoc:Boolean){createProduct(id:$id,
name:$name, category_id:$id_categorie, description:$descriere, picture:$imagine,
price:$pret, available:$stoc){product{id }}}}"}
setari={url:"http://localhost:3000",
type:"POST",
data:creareProdus,
contentType:"application/json",
success:vizualizareProdus}
$.ajax(setari)
}
function vizualizareProdus(){
var x = document.getElementById("formular").method
document.getElementById("zonaB").innerHTML = x
}
</script>
</body>
</html>
'''
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 am trying to pass multiple variables from two different windows into the same PHP script. Is this possible? If not, what would be the best course of action?
Thanks
verifyemail.html
<script type = "text/javascript" src = "js/js_functions.js"> </script>
<form method="post" onsubmit = "return testAjax();" />
<input type="email" placeholder="email" name="email" required maxlength = "50"><br>
<input type="email" placeholder="re-enter email"name="reemail" required maxlength = "50"><br>
<input type="submit" value="Verify Email">
</form>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
signup.html:
<script type = "text/javascript" src="js/js_functions.js"></script>
<form method="post" onsubmit="return ajaxTest();"/>
<input type="text" placeholder="username" name="username" required = "required" maxlength = "15"><br>
<input type="password" placeholder="password" name="password" required = "required" pattern = "(?=.*\d)(?=.*[A-Z]).{10,}"><br>
<input type="password" placeholder="re-enter password"name="repassword" required = "required"><br>
<p class = "passwordreq">Password must:</p>
<input type="submit" value="sign up"> <input type="button" value="go back" onclick="window.location='index.html'">
</form>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
js_functions
var username, password;
function setUsrandPass(form)
{
if(form.password.value != form.repassword.value)
{
alert("Passwords do not match");
}
else {
username = form.username.value;
password = form.password.value;
window.location = 'verifyemail.html';
}
return false;
}
function ajaxTest()
{
if(form.email.value != form.reemail.value)
{
alert("Emails do not match");
}
else
$.ajax({
type: 'GET',
url: 'signup_script.php',
data: {usr: username, pass: password, em: form.email.value},
});
return false;
}
php script:
<?php
include 'profile_Functions.php';
$username = $_GET['usr'];
$password = $_GET['pass'];
$email = $_GET['em'];
echo "got here!";
createUser($username,$password,$email);
?>
This is not possible with things from separate pages. They need to be making the same request to the PHP script to provide both data.
You may be able to circumvent this by writing with PHP to some sort of datastore, i.e. a file or a database, then you wait for the other script to write as well, and then PHP can do any processing it needs.
I am using $.ajax to insert and update a database. I have a <form> on a webpage, and the $.ajax looks like this:
$('.submit-create-customer').on('click touchstart', function() {
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
var confirm_email = $('#confirm_email').val();
var phone = $('#phone').val();
var address = $('#address').val();
var address_2 = $('#address_2').val();
var city = $('#city').val();
var state = $('#state').val();
var zipcode = $('#zipcode').val();
var formData = "first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&confirm_email=" + confirm_email + "&phone=" + phone + "&address=" + address + "&address_2=" + address_2 + "&city=" + city + "&state=" + state + "&zipcode=" + zipcode;
$.ajax({ // Start the PHP submission
url : "/resources/submit.php?action=createCustomer",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR) { //data - response from server
alert('success');
},
error: function(data, textStatus, jqXHR) {
alert('failure');
}
});
});
HTML:
<form class="validate">
<div class="col-md-6">
<input class="form-control input-md validate-name" id="first_name" name="first_name" minlength="2" type="text" placeholder="First Name">
<input class="form-control input-md validate-name" id="last_name" name="last_name" minlength="2" type="text" placeholder="Last Name">
<input class="form-control input-md validate-email" id="email" name="email" minlength="2" type="text" placeholder="Email">
<input class="form-control input-md validate-email" id="confirm_email" name="confirm_email" minlength="2" type="text" placeholder="Confirm Email">
<input class="form-control input-md validate-phone" id="phone" name="phone" type="text" placeholder="Phone">
</div>
<div class="col-md-6">
<input class="form-control input-md validate-address" id="address" name="address" type="text" placeholder="Address">
<input class="form-control input-md validate-address" id="address_2" name="address_2" type="text" placeholder="Address Line 2">
<input class="form-control input-md validate-name" id="city" name="city" type="text" placeholder="City">
<select class="form-control input-md validate-select" id="state" name="state">
<option value="-1" disabled selected>State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<input class="form-control input-md validate-zipcode" id="zipcode" name="zipcode" type="text" placeholder="Zipcode">
</div>
<button class="btn btn-md submit-create-customer" disabled>Submit</button>
</form>
The URL returns either true or false. After I get the alert, the same webpage that I made the request from gets reloaded with a bunch of URL parameters. It looks something like this:
/customers.php?first_name=Trevor&last_name=Hutto&email=this%40that.com&confirm_email=this%40that.com&phone=1234567891&address=1234+Memory+Lane&address_2=Apt.+1131&city=New+York&state=NY&zipcode=12345
Why is this happening when I have declared the request type as POST? Also, isn't the point of AJAX to be asynchronous and make request in the background? Why is the page reloading?
My guess is that since you don't prevent the normal action from firing the browser runs your code and after that behaves the way it would normally.
Try changing:
$('.submit-create-customer').on('click touchstart', function() {
// Other code
To:
$('.submit-create-customer').on('click touchstart', function(e) {
e.preventDefault();
// Other code
Edit: Also, if this is a form, I can highly recommend the jQuery.form plugin (http://malsup.com/jquery/form/).
One more thing, if this is indeed a form, don't hook a click event to the submit button, instead hook a submit event to the actual form. This way users can submit the form in any way and it will still be handled with ajax.
I think it'd help if you showed your HTML as well.