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.
Related
I have an HTML form and I'm wondering how I can set that info when submitted to the variables in my js file.
HTML
<input id="column-left" type="text" name="first-name" placeholder="First Name"/>
<input id="column-right" type="text" name="last-name" placeholder="Last Name"/>
<input id="input-field" maxlength="16" type="text" name="number" placeholder="Card Number"/>
<input id="column-left" maxlength="4" type="text" name="expiry" placeholder="MM / YY"/>
<input id="column-right" maxlength="3" type="text" name="cvc" placeholder="CCV"/>
(Leaving out unimportant info)
JS
var order_info = {name: "your name", // your first and last name
email: "your#email.com", // your email
phone: "5555555555", // your phone number
address1: "123 street lane", // your street address
address2: "apartment 1", // leave blank if you dont have one
zip_code: "00000", // your zip code
city: "New York", // city
state_code: "NY", // state code, if you dont know this then look it up son
country: "USA" // only two options, "USA" or "CANADA"
};
I need to set the info from the form into these fields.
One of many ways to get values from html form tag to Javascript object.
document.querySelector("#myForm").addEventListener("keyup", function(){
var data = {};
var inputs = document.querySelectorAll('input');
inputs.forEach(input => {
data[input.name] = input.value;
});
document.querySelector("#text").innerText = JSON.stringify(data);
});
document.querySelector("#myForm").dispatchEvent(new Event('keyup'));
<form id="myForm">
<input value="Niklesh" type="text" name="first_name" placeholder="First Name"/>
<input value="Raut" type="text" name="last_name" placeholder="First Name"/>
<input value="" type="text" name="email" placeholder="Email"/>
<div id='text'></div>
</form>
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var card = document.getElementById("card").value;
var expire = document.getElementById("expire").value;
var cvc = document.getElementById("cvc").value;
var order_info = {
fname: fname ? fname : '',
lname: lname ? lname : '',
card: card ? card : '',
expire: expire ? expire : '',
cvc: cvc ? cvc: ''
}
console.log(order_info);
<input id="fname" type="text" name="first-name" value="sourav" placeholder="First Name"/>
<input id="lname" type="text" name="last-name" value="singh" placeholder="Last Name"/>
<input id="card" maxlength="16" type="text" name="number" value="" placeholder="Card Number"/>
<input id="expire" maxlength="4" type="text" name="expiry" value="08/12" placeholder="MM / YY"/>
<input id="cvc" maxlength="3" type="text" name="cvc" value="111" placeholder="CCV"/>
First you should define a unique ID to each input you have, then get the value of this ID using javascript document.getElementById('ID').value or using jQuery $('ID').val().
Second part, you must match your number of inputs with your array.
Now you have an array of data, do what ever you want to do with it.
document.getElementById("save").addEventListener("click", function() {
var order_info = {
firstName: document.getElementById('first-name').value,
lastName: document.getElementById('last-name').value,
number: document.getElementById('number').value,
expiry: document.getElementById('expiry').value,
cvc: document.getElementById('cvc').value,
};
console.log(order_info);
});
<input id="first-name" type="text" name="first-name" placeholder="First Name"/>
<input id="last-name" type="text" name="last-name" placeholder="Last Name"/>
<input id="number" maxlength="16" type="text" name="number" placeholder="Card Number"/>
<input id="expiry" maxlength="4" type="text" name="expiry" placeholder="MM / YY"/>
<input id="cvc" maxlength="3" type="text" name="cvc" placeholder="CCV"/>
<button id="save">Save Data</button>
if you want to serialise data;
var order_info = $('form').serializeArray();
if you want to use formdata :
var fd = new FormData();
var order_info = $('form').serializeArray();
$.each(order_info,function(key,input){
fd.append(input.name,input.value);
});
Using the DOM (Document Object Model) you can access the values of the HTML components.
For example, given your code, you can lookup the element by its "id":
var lastname = document.getElementById("column-right");
var cardnumber = document.getElementById("input-field");
... etc
You can also lookup the element by using the value of its "name" attribute:
var lastname = document.getElementsByName("last-name");
var cardnumber = document.getElementsByName("number");
Tip: You normally do this when the page is loaded (event "onload") and if the values are received by the same page, it needs to implement typically the scenario of the first load as well (where the values are null, not initialized).
Javascript references:
https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp
https://www.w3schools.com/jsref/met_document_getelementbyid.asp
You can use JQuery .serializeArray() method to do so.
like this:
var x = $("form").serializeArray();
You should get Key:Value pairs of all the text fields and their values by doing so.
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 have 2 input boxes.
When I input a value into the first one, the javascript function checkMyKad() is triggered.
checkMyKad() gets value in first input box, edits it, and alerts new value.
I want new to be set into second input box. How do I get new value to be shown in 2nd input box?
<div class="form-group" style="color:#0000FF; margin-left:160px;" >
<input type="text" placeholder="Please input value" id="myKadC" maxlength="4" size="10" onchange="checkMyKad()" required>
<input type="text" id="newVal" maxlength="20" size="20"/>
</div>
javascript function
function checkMyKad() {
var mykadC = $('#myKadC').val();
var newVal='Value is : '+'-'+mykadC;
alert(newVal);
$('#newValId').val(newVal);
}
You seem to target the wrong id, it should be $('#newVal')
function checkMyKad() {
var mykadC = $('#myKadC').val();
var newVal='Value is : '+'-'+mykadC;
alert(newVal);
$('#newVal').val(newVal);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group" style="color:#0000FF; margin-left:160px;" >
<input type="text" placeholder="Please input value" id="myKadC" maxlength="4" size="10" onchange="checkMyKad()" required>
<input type="text" id="newVal" maxlength="20" size="20"/>
</div>
You have $('#newValId') instead of $('#newVal')
target id is wrong.
$('#newValId').val(newVal); -> $('#newVal').val(newVal);
Personally I would do something like this:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="form-group" >
<h3>Pure JavaScript</h3>
<input type="text" placeholder="Please input value" maxlength="4" size="10" onchange="checkMyKad(this)" required>
<input type="text" maxlength="20" size="20"/>
</div>
<div class="form-group" >
<h3>Using jQuery</h3>
<input type="text" placeholder="Please input value" maxlength="4" size="10" onchange="checkMyKadJQuery(this)" required>
<input type="text" maxlength="20" size="20"/>
</div>
<script type="text/javascript">
function checkMyKad(element) {
let oldValue = element.value;
let newValue = 'Value is : -'+oldValue;
alert(newValue);
element.nextElementSibling.value = newValue;
}
function checkMyKadJQuery(element) {
let oldValue = $(element).val();
let newValue = 'Value is : -'+oldValue;
alert(newValue);
$(element).next().val(newValue);
}
</script>
Doing it like that would allow the functions to be reused.
I'm attempting to build an object of the input values in the form below, then log that object to the console; but it the values are not being retrieved properly.
What is wrong with my code?
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.getElementsByClassName('personName').value;
var personEmail = document.getElementsByClassName('personEmail').value;
var personMessage = document.getElementsByClassName('personMessage').value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" class="personName" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success" id="inputHorizontalSuccess" class="personEmail" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" class="personMessage" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
You have multiple Ids:
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" id="personName" placeholder="Name">
You can either remove inputHorizontalSuccess.
Or add a name and get value from it instead, incase you must have inputHorizontalSuccess.
This should do it:
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess1" name="personName" placeholder="Name">
<input type="email" class="form-control form-control-success" id="inputHorizontalSuccess2" name="personEmail" placeholder="name#example.com">
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess3" name="personMessage" placeholder="Your Message">
var personName = document.querySelector('[name="personName"]').value;
var personEmail = document.querySelector('[name="personEmail"]').value;
var personMessage = document.querySelector('[name="personMessage"]').value;
I recommend you read this question on how to get value from the DOM.
How do I get the value of text input field using JavaScript?
Only the first class attribute in an element definition is applied. This means that when you write the following:
<input type="text" class="form-control form-control-success" ... class="personName" placeholder="Name">
The later "class" attribute will not apply. This means that the element cannot be selected by this class.
Document.getElementsByClassName returns a live HTMLCollection even if there is only a single element. This means that when you write:
var personName = document.getElementsByClassName('personName').value;
There is no value property in the live HTMLCollection returned by the call to Document.getElementsByClassName, so it will return undefined.
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.getElementsByClassName('personName')[0].value;
var personEmail = document.getElementsByClassName('personEmail')[0].value;
var personMessage = document.getElementsByClassName('personMessage')[0].value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success personName" id="inputHorizontalSuccess" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success personEmail" id="inputHorizontalSuccess" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success personMessage" id="inputHorizontalSuccess" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
However, you should probably use ID's instead of classes and Element#querySelector, to avoid conflict:
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.querySelector('#personName').value;
var personEmail = document.querySelector('#personEmail').value;
var personMessage = document.querySelector('#personMessage').value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success" id="personName" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success" id="personEmail" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success" id="personMessage" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
The user is supposed to be able to enter an address in the form and the Javascript will open a new window with the directions. But when the button is pressed, nothing happens. Can someone tell me what I'm doing wrong?
Javascript:
function ShowDirections() {
var street = document.getElementById('street').value;
var city = document.getElementById('city').value;
var state = document.getElementById('state').value;
var zip = document.getElementById('zip').value;
var from = street + ', ' + city + ', ' + state + ' ' + zip;
var url = "http://maps.google.com/maps?f=d&hl=en&saddr=" + from + "&daddr=1530+Commercial+Street%2c+East+Weymouth%2c+MA+02189";
window.open(url, 820, 700);
}
HTML:
<label for="street">Address or Intersection:</label>
<input name="street" type="text" id="street" />
<label for="city">City:</label>
<input name="city" type="text" id="city" />
<label for="state">State/Province:</label>
<input name="state" type="text" maxlength="2" id="state" />
<label for="zip">Zip/Postal Code:</label>
<input name="zip" type="text" maxlength="10" id="zip" />
<input type="button" value="Get Directions" onclick="javascript:ShowDirections();" />
javascript: isn't an acceptable action for form tags. It needs to be a URL. Take it all out of the form and place a handler on the submit button (as a button) and you might be closer.
you can use onsubmit to call javascript function