How to use ajax Post method to submit user input without jQuery - javascript

i am trying to make a subscriber form that submit the form using ajax post method not jQuery. I wrote a code but it is not working properly i think i am doing wrong in sending POST data. here is my code what i have tried so far.
<div id="form" style="max-width:477px">
<div class="imgContainer" id="myImageContainer">
<span onclick="document.getElementById('myLogin').style.display='none'" class="close" title="Close">×</span>
</div>
<div class="loginInfo" id="myLoginInfo">
<label for="Full Name">
<b>Full Name</b>
</label>
<spam class="error" style="color:red">
<i id="nameErr"></i>
</spam>
<input type="text" placeholder="Enter full name" name="name" id="name">
<label for="Email"><b>Email</b></label>
<spam class="error" style="color:red">
<i id="emailErr"> </i>
</spam>
<input type="text" placeholder="Enter your Email" name="email" id="email">
<button onclick="verify()">Subscribe</button>
</div>
</div>
</div>
<script>
function verify(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("email").innerHTML = myObj.email;
document.getElementById("emailErr").innerHTML = myObj.emailErr;
document.getElementById("name").innerHTML = myObj.name;
document.getElementById("nameErr").innerHTML = myObj.nameErr;
}
};
xmlhttp.open("GET", "subs.php", true);
var data="email=" + document.getElementById("email").value + "&name="+document.getElementById("name").value;
xmlhttp.send(data);
}
</script>
and the PHP page looks like this(it works fine when using HTML <Form method="post">
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $name = $emailErr = $nameErr="";
function test($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($_POST["email"])) {
$emailErr=" *This Field is Required";
}else{
$email=test($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){$emailErr = " *Invalid email format";}
if (strlen($email)>60){$emailErr=" *Email cannot be larger than 60 character";}
}
if (empty($_POST["name"])) {
$nameErr=" *This Field is Required";
}else{
$name = test($_POST["name"]);
$name = preg_replace('/\s\s+/', ' ', $name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = " *Only letters and white space allowed";
}
if (strlen($name)>60)
{$nameErr=" *Name cannot be larger than 60 character";}
}
$json['email'] = $email;
$json['emailErr'] = $emailErr;
$json['name'] = $name;
$json['nameErr'] = $nameErr;
$myJSON = json_encode($json);
echo $myJSON;
}
when I hit the subscribe button it gives me null value rather than showing Error message.

xmlhttp.open("GET", "subs.php", true);
Should be
xmlhttp.open("POST", "subs.php", true);
If the PHP code expects a POST request.

Suggest you send ajax with Axios is more clearly and easy than Jquery and pure javascript

Related

How to check if the form on my HTML landing page is working properly on Facebook & Instagram mobile apps?

I have added a form on HTML page which sends me an email after submission.
I want to make sure it works on ALL MOBILES, specially on the Facebook and Instagram mobile apps. I have checked it on my phone and I have used the chrome developer tool.
Is this the best way to have a form on HTML page? Or is there a better way?
The test page: https://www.zidan-dxb.com/test.html
HTML Code:
<form id="my_form2" onsubmit="submitForm2(); return false;">
<p><input class="form" id="n2" placeholder="Name" aria-label="Name" required></p>
<p><input class="form" id="e2" placeholder="Email Address" type="email" aria-label="Email"></p>
<p><input class="form" id="t2" placeholder="Phone" type="tel" aria-label="Phone" required></p>
<textarea class="form" id="m2" placeholder="Write your message here" aria-label="Message" rows="4"></textarea>
<p><input class="formbut" id="mybtn2" type="submit" value="Send"> <span id="status2"></span></p>
</form>
Javascript:
<script>
function _(id) {
return document.getElementById(id);
}
function submitForm2() {
_("mybtn2").disabled = true;
_("status2").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append("n2", _("n2").value);
formdata.append("e2", _("e2").value);
formdata.append("t2", _("t2").value);
formdata.append("m2", _("m2").value);
var ajax = new XMLHttpRequest();
ajax.open("POST", "https://www.zidan-dxb.com/alfurjan/form2.php");
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
if (ajax.responseText == "success") {
_("my_form2").innerHTML = '<p>Thanks ' + _("n2").value + ', your message has been sent.</p>';
} else {
_("status2").innerHTML = ajax.responseText;
_("mybtn2").disabled = false;
}
}
}
ajax.send(formdata);
}
</script>
PHP:
<?php
if( isset($_POST['n2']) && isset($_POST['e2']) && isset($_POST['t2']) && isset($_POST['m2']) ){
$n2 = $_POST['n2']; // HINT: use preg_replace() to filter the data
$e2 = $_POST['e2'];
$t2 = $_POST['t2'];
$m2 = nl2br($_POST['m2']);
$to = "h#zidan-dxb.com";
$from = "z#zidan-dxb.com";
$subject = 'Contact Form Message alfurjan';
$message = '<b>Name:</b> '.$n2.' <br><b>Email:</b> '.$e2.' <br><b>Tell:</b> '.$t2.' <p>'.$m2.'</p>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
if( mail($to, $subject, $message, $headers) ){
echo "success";
} else {
echo "The server failed to send the message. Please try again later.";
}
}
?>
You can test that in Developer Mode present in google chrome.
Ctrl + Shift + I will open up developers tools then press Ctrl + Shift + M and this will open Device Toolbar where you can check your website for different resolutions and devices

Trying to get data from textbox and inserting it into a database

I have a form that is to be used to input information and register an account. The information is entered on the website and when the button 'register' is pressed it is validated by an external JavaScript method and afterwards, a PHP method is called using ajax which should take the information from the text boxes and enter it into the database. I can't seem to get the PHP getting the information working.
<?php
$mysqli = new mysqli('localhost:8080', 'root', null, 'salmonhouse');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO clients (name, surname, email, address, password)
VALUES (?,?,?,?,?)";
$name = $_POST['name'];
$surname = $_POST['surname'];
$email= $_POST['email'];
$address= $_POST['Address'];
$pass= $_POST['Password'];
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sssss", $name, $surname, $email, $address, $pass);
$stmt->execute();
?>
HTML textboxes
<form class="quote">
<div class = inliner>
<label>Name</label>
<input id="name" type="text" placeholder="Name">
</div>
<div class = inliner>
<label>Surname</label>
<input id="surname" type="text" placeholder="Surname">
</div>
<div>
<label>Email</label><br>
<input id="email" type="email" placeholder="Email Address"><br>
</div>
<div>
<label>Address</label><br>
<input id="Address" type="email" placeholder="Home Address"><br>
</div>
<div class = inliner>
<label>Password</label>
<input id="Password" type="text" placeholder="Password">
</div>
<div class = inliner>
<label>Verify Password</label>
<input id="vPassword" type="text" placeholder="Password">
</div>
<br><button class="button_1" type="button" onclick="Validate()">Register</button>
</form>
Calling javascript file from html page
<script type= "text/javascript">
var name = document.getElementById("name").value;
var surname =document.getElementById("surname").value;
var email =document.getElementById("email").value;
var pass=document.getElementById("Password").value;
var passV =document.getElementById("vPassword").value;
var address=document.getElementById("Address").value;
</script>
<script type= "text/javascript" src="asset/js/my_javascript.js"></script>
Actual javascript file
/* eslint-env browser */
/*jslint devel: true */
/* eslint-disable */
function Validate(){
name = document.getElementById("name").value;
surname =document.getElementById("surname").value;
email =document.getElementById("email").value;
pass=document.getElementById("Password").value;
passV =document.getElementById("vPassword").value;
var error = "";
document.getElementById("name").style.borderColor = "white";
document.getElementById("surname").style.borderColor = "white";
document.getElementById("email").style.borderColor = "white";
document.getElementById("Password").style.borderColor = "white";
document.getElementById("vPassword").style.borderColor = "white";
var count= 0;
if(name.length == 0){
document.getElementById("name").style.borderColor = "red";
count =1;
error = error + "Name cannot be empty\n"
}
if(surname.length == 0 ){
document.getElementById("surname").style.borderColor = "red";
count =1;
error = error + "Surname cannot be empty\n"
}
if(email.length == 0 ){
document.getElementById("email").style.borderColor = "red";
count =1;
error = error + "Email cannot be empty\n"
}
if(!(email.includes("#"))){
document.getElementById("email").style.borderColor = "red";
count =1;
error = error + "Email needs to contain an # symbol\n"
}
if(!(email.includes("."))){
document.getElementById("email").style.borderColor = "red";
count =1;
error = error + "Email needs to comtain a .com or similar\n"
}
if(pass!==passV){
document.getElementById("Password").style.borderColor = "red";
document.getElementById("vPassword").style.borderColor = "red";
count =1;
error = error + "Passwords do not match\n"
}
if(!(pass.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%&*()])[0-9a-zA-Z!##$%&*()]{8,}$/))){
document.getElementById("Password").style.borderColor = "red";
document.getElementById("vPassword").style.borderColor = "red";
count =1;
error = error + "Password must be atleat 8 long and contain a LowerCase, UpperCase, Number and a symbol."
}
if(false){
alert("Please correct the following errors highlighted in red\n"+error);
}
else{
alert("Name: " + name + "\nSurname: "+ surname + "\nEmail: "+ email+"\nPassword: "+pass+"\n Succesful Registration");
xmlhttp = new XMLHttpRequest();
var url = "asset/php/inserting.php";
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
/* eslint-enable */
This PHP file is a separate file with just this code. I have tested and if I manually set the variables instead of trying to retrieve them the data is successfully inserted into the database. So from my testing it is simply the retrieval not working. I also tried $_REQUEST['name']
This is the ajax/xmlhttprequest code.
xmlhttp = new XMLHttpRequest();
var url = "asset/php/inserting.php";
xmlhttp.open("POST",url,true);
xmlhttp.send();
My advice would be to use the jQuery library rather than XMLHttpRequest. You will need to include in the <head> section of your HTML a <script> tag to load the jQuery library from some CDN (Content Delivery Network). Also add id="f" to your <form> tag. Then your Ajax call can be as simple as:
$.ajax({
type: "POST",
url: 'asset/php/inserting.php',
data: $('#f').serialize(), // serializes the form's elements.
success: function(msg)
{
alert(msg); // show response from the php script.
}
});
You can attached the variable in ajax call, which you need to get in your php page using & for separating variable and = for assigning value .i,e :
//attaching values to pass
var data = "name=" + name + "&email=" + email + "&surname=" + surname + "&Address=" + Address + "&Password=" + Password;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//if success do something here
alert("save");
}
};
var url = "asset/php/inserting.php";
request.open("POST", url, true);
//send data to php page
request.send(data);

Cannot get a simple XMLHttpRequest to work

I'm struggling to get this to work as part of a larger exercise.
It's pretty simple - a user fills in a form which is sent using an XMLHttpRequest to a processing page. This should return a response below the form.
I had it almost working, but one field wouldn't show... and now nothing. Could this be a cache problem or is a problem with the code.
Here's the form:
<div id="miniContact">
<label for="yourName">Your Name</label>
<input type="text" name="yourName" id="yourName"><br>
<label for="phone">Your Phone</label>
<input type="text" name="phone" id="phone"><br>
<input type="text" name="reqd" id="reqd"><br>
<label for="email">Your Email</label>
<input type="email" name="email" id="email"><br>
<label for="type">Your vehicle type</label>
<input type="text" name="type" id="type">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
Javascript:
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var yourName = document.getElementById("yourName").value;
var phone = document.getElementById("phone").value;
var reg = document.getElementById("reg").value;
var srv = document.getElementById("reqd").value;
var email = document.getElementById("email").value;
var type = document.getElementById("type").value;
var vars = "yourName="+yourName+"&phone="+phone+"&reg="+reg+"srv="+service+"email="+email+"&type="+type;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
...and the php file (my_parse_file.php):
<?php
echo 'Thank you '. $_POST['yourName'] . ' ' . $_POST['service'] . ', says the PHP file';
$user_name = $_POST['yourName'];
$reg = $_POST['reg'];
$email = $_POST['email'];
$srv = $_POST['srv'];
$phone_number = $_POST['phone'];
$vehicle = $_POST['type'];
?>

Ajax contact form not working in website

I'm just a beginner and trying to implement ajax contact form with php mailing script. But when I click on Submit nothing happens and nothing appears.
Below is my codes.
HTML
<form id="contactform" class="contact-form text-center" role="form">
<!-- IF MAIL SENT SUCCESSFULLY -->
<h6 class="success">
<span class="olored-text icon_check"></span> Your message has been sent successfully.</h6>
<!-- IF MAIL SENDING UNSUCCESSFULL -->
<h6 class="error">
<span class="colored-text icon_error-circle_alt"></span> E-mail must be valid.</h6>
<input id="cf-name" type="text" name="cf-name" placeholder="Your Name">
<input id="cf-email" type="email" name="cf-email" placeholder="Your Email">
<input id="cf-address" type="text" rows="7" name="cf-address" placeholder="Your Home Address">
<input id="cf-phone" type="text" rows="7" name="cf-phone" placeholder="Your Phone Number">
<input type="submit" class="button alt" value="Submit" id="submit" name="submit" data-style="expand-left"/>
</form>
Javascript
// Function for email address validation
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
/* =================================
CONTACT FORM
=================================== */
$("#contactform").submit(function (e) {
e.preventDefault();
var name = $("#cf-name").val();
var email = $("#cf-email").val();
var address = $("#cf-address").val();
var message = $("#cf-phone").val();
var dataString = 'name=' + name + '&email=' + email + '&address=' + address + '&phone=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
}
if (isValidEmail(email) && (message.length > 1) && (address.length > 1) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function () {
$('.success').fadeIn(1000);
$('.error').fadeOut(500);
}
});
}
else {
$('.error').fadeIn(1000);
$('.success').fadeOut(500);
}
return false;
});
PHP
<?php
// Get values from jquery
$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$to = "name#email.com";
$subject = "New Email Subscriber";
$message = " Name: " . $name . "\r\n\r\n Email: " . $email . "\r\n\r\n Address: " . $address . "\r\n\r\n Phone: " . $phone;
$from = "ContactForm";
$headers = "From:" . $from . "\r\n";
$headers .= "Content-type: text/plain; charset=UTF-8" . "\r\n";
if (#mail($to, $subject, $message, $headers)) {
echo "success";
} else {
echo "invalid";
}
Can someone please fix this code? I don't what's wrong with it.
Thanks in advance.
It may have nothing to do with Ajax but the php native mail function; I recommend use something like phpMailer since they are much more reliable than native function.

Ajax/Jquery issue pushing data to backend

Firstly I'm not sure if missing anything in my code other than the problems in my functions, but i digress. I'm new to jquery so I'm having difficulty setting up a registration page. In the form I'm trying to check for valid entries as well as checking the queries in the back-end using php. I set up 2 files one is an html file and the other is a php file. Using ajax the function was supposed to call the php file, but I cant seem to get it working and I'm wondering if I should just put all the code in the same file. Furthermore I'm unsure if the functions are even working at all because its not returning any status. I will post the code for the two files below. Any hints or tips would be greatly appreciated.
The HTML file without css
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Register</title>
<link rel="stylesheet" href="assets/css/reset.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<script src="assets/js/jquery.min.js"> </script>
<script src="assets/js/main.js"> </script>
<div class="pen-title">
<h1>Registration Form</h1></div>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass").value;
var p2 = _("pass2").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else
{
_("submit").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "registration.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("submit").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1);
}
}
</script>
<!-- Form Module-->
<div class="module form-module">
<div class="form">
</div>
<div class="form">
<h2>Create an account</h2>
<form method="post" name="signupform" id="signupform" onsubmit="return false;">
<input type="text" id="username" onfocus="emptyElement('status')" placeholder="Username" maxlength="50"/>
<input type="password" id="pass" onfocus="emptyElement('status')" placeholder="Password" maxlength="10"/>
<input type="password" id="pass2" onfocus="emptyElement('status')" placeholder="Confirm Password" maxlength="10"/>
<input type="email" id="email" onfocus="emptyElement('status')" placeholder="Email Address" maxlength="50"/>
<!-- <input type="tel" name="telephone" placeholder="Phone Number" maxlength="10"/> -->
<button type="submit" onclick="signup()" name="submit">Register</button>
</form>
</div>
</div>
</body>
</html>
The PHP file
<?php
// Connects to your Database
$host="myhost"; // Host name
$username="myuser"; // Mysql username
$password="mypass"; // Mysql password
$db_name="mydbname"; // Database name
$con = mysqli_connect("$host", "$username", "$password", "$db_name") or die(mysql_error());
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($con, $_POST['e']);
$p = $_POST['p'];
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($con, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($con, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
//$cryptpass = crypt($p);
//include_once ("php_includes/randStrGen.php");
//$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p' ,'$ip',now(),now(),now())";
$query = mysqli_query($con, $sql);
$uid = mysqli_insert_id($con);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
//if (!file_exists("user/$u")) {
// mkdir("user/$u", 0755);
//}
}
}
?>
Your javascript code has many errors. Like you used _ instead of $ and your element Ids is wrong. They are not include #. So I have organized your code with your logic. Bu it is not a real question or it is not a true way to learn.
HTML
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Register</title>
<link rel="stylesheet" href="assets/css/reset.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!--script src="assets/js/main.js"> </script-->
<div class="pen-title">
<h1>Registration Form</h1></div>
<script>
function emptyElement(x){
$('#' + x).text("");
}
function signup(){
var un = $("#username").val();
var em = $("#email").val();
var p1 = $("#pass").val();
var p2 = $("#pass2").val();
if(un == "" || em == "" || p1 == "" || p2 == "")
{
$('#status').text("Fill out all of the form data");
}
else if(p1 != p2)
{
$('#status').text("Your password fields do not match");
}
else
{
$.ajax({
type: "POST",
url: "registration.php",
dataType: "json",
data : { u: un, p:p1, e:em },
cache: !1,
beforeSend: function(){
$("#submit").hide();
$('#status').text('please wait ...');
},
complete: function(){
$("#submit").show();
},
success: function(answer){
if(answer.result == "successful")
{
$("#status").html(answer.text);
}
else
{
$("#status").html(answer.result);
}
},
error: function(answer){
$("#status").text(answer);
}
});
}
/*
var ajax = ajaxObj("POST", "registration.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
$("submit").style.display = "block";
} else {
window.scrollTo(0,0);
$("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1);
*/
}
</script>
<!-- Form Module-->
<div class="module form-module">
<div class="form">
</div>
<div class="form">
<h2>Create an account</h2>
<form method="post" name="signupform" id="signupform" onsubmit="return false;">
<input type="text" id="username" onfocus="emptyElement('status')" placeholder="Username" maxlength="50"/>
<input type="password" id="pass" onfocus="emptyElement('status')" placeholder="Password" maxlength="10"/>
<input type="password" id="pass2" onfocus="emptyElement('status')" placeholder="Confirm Password" maxlength="10"/>
<input type="email" id="email" onfocus="emptyElement('status')" placeholder="Email Address" maxlength="50"/>
<!-- <input type="tel" name="telephone" placeholder="Phone Number" maxlength="10"/> -->
<button type="submit" onclick="signup()" name="submit">Register</button>
<div id="status"></div>
</form>
</div>
</div>
</body>
</html>
registration.php
<?php
$answer = new stdClass;
if(isset($_POST))
{
$answer->result = "successful";
$answer->text = "";
foreach($_POST as $key => $value)
{
$answer->text .= $key . ": " . $value . "<br />";
}
}
else
{
$answer->result = "Error";
$answer->text = "Error Message";
}
echo json_encode($answer);
?>
This registration.php is an example for you. You can rewrite with your logic.
You should use $answer object for response.
$answer->result is status of repsonse
$answer->text is response
I hope it will help you.

Categories