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);
Related
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
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+"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'];
?>
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.
I'm working on converting a jQuery ajax request into plain JavaScript just so I know how to do it both ways. What I'm trying to do is pass a JSON object from my PHP script into my JavaScript file and display the values of the JSON object on the page.
I'm just beginning to dive into AJAX and I've gotten the jQuery version to work on my own easily enough, but I'm having difficult with the plain JavaScript version. For the plain JavaScript part, I'm following along with a JavaScript book that I have. That's why the code structure may seem different.
Also, I'm aware there are no real security implementations and that is fine. This is just for my own learning purposes.
Here is the HTML:
<body>
<h3>Grab the location of a person in the database below</h3>
<form action="ajax/name.php" method="POST" name="ajaxForm" id="ajaxForm">
<label for="name">Name: </label>
<input type="text" id="name" name="name">
<input type="submit" id="name-submit" name="name-submit" value="Grab">
</form>
<div id="results">
<label for="location">Location: </label>
<input type="text" name="name-data" id="name-data" disabled>
</div>
<div id="insert">
<h3>Insert a new person with a new location below</h3>
<form action="ajax/name.php" method="POST" name="insForm" id="insForm">
<label for="name">Name: </label>
<input type="text" name="ins-name" id="ins-name">
<label for="location">Location: </label>
<input type="text" name="ins-location" id="ins-location">
<input type="submit" id="ins-submit" name="ins-submit" value="Insert">
</form>
<div id="insresults_name"></div>
<div id="insresults_loc"></div>
</div>
<script src="js/ajax.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/global.js"></script>
</body>
Here is my jQuery code that works fine:
$('document').ready(function() {
var locForm = $('#ajaxForm');
var insForm = $('#insForm');
locForm.submit(function() {
$.ajax({
type: 'POST',
url: locForm.attr('action'),
data: locForm.serialize(),
success: function (response) {
$('#name-data').val(response);
}
});
return false;
});
insForm.submit(function() {
$.ajax({
type: 'POST',
url: insForm.attr('action'),
data: insForm.serialize(),
dataType: 'json',
success: function (response) {
$('#insresults_name').text('Name: ' + response[0]);
$('#insresults_loc').text('Location: ' + response[1]);
}
});
return false;
});
});
Here is my PHP Script:
<?php
if (isset($_POST['name'])) {
require '../db/connect.php';
$conn = new Con();
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare('SELECT * FROM names WHERE name=:name');
$stmt->bindParam(':name', $name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo (isset($result['location'])) ? $result['location'] : 'That name isn\'t listed';
}
if (isset($_POST['ins-name']) && isset($_POST['ins-location'])) {
require '../db/connect.php';
$conn = new Con();
$name = filter_input(INPUT_POST, 'ins-name', FILTER_SANITIZE_STRING);
$loc = filter_input(INPUT_POST, 'ins-location', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare('INSERT INTO names (name, location) VALUES (:name, :loc)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':loc', $loc);
try {
$stmt->execute();
$result = $stmt->rowCount();
if ($result) {
$stmt = $conn->prepare('SELECT * FROM names WHERE name=:name');
$stmt->bindParam(':name', $name);
$stmt->execute();
$res = $stmt->fetch(PDO::FETCH_ASSOC);
$val = array();
$val[0] = $res['name'];
$val[1] = $res['location'];
echo json_encode($val);
} else {
echo 'Fail';
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . '';
}
}
?>
And here is the plain JavaScript that I've come up with, but doesn't work:
function getData() {
'use strict';
var name = document.getElementById('ins-name').value();
var location = document.getElementById('ins-location').value();
var url = document.getElementById('ins-name').getAttribute('action');
if ((name.length > 0) && (location.length > 0)) {
var ajax = getXMLHttpRequestObject();
ajax.ononreadystatechange = function () {
if (ajax.readyState == 4) {
// Check the status code:
if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)) {
// if ajax.responseText isn't empty
if (ajax.responseText) {
var arr = Array();
arr = JSON.parse(responseText);
document.getElementById('insresults_name').innerHTML('Name: ' + arr[0]);
document.getElementById('insresults_loc').innerHTML('Location: ' + arr[1]);
} else {
alert('Something went wrong!');
}
} else {
alert('Bad Status Code!');
}
}
};
ajax.open('POST', '../ajax/name.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data = 'name=' + encodeURIComponent(name) + 'location=' + encodeURIComponent(location);
ajax.send(data);
return false;
} else {
alert('Please complete the form!');
}
}
function init() {
'use strict';
if (document && document.getElementById) {
var form = document.getElementById('insForm');
form.onsubmit = getData;
}
}
window.onload(init);
I have two database tables, guestlist and attendance
On one HTML page, I have a window.onload script that I want to check the guestlist via AJAX. If the firstname AND lastname in the url query appear in the guestlist table, then load the page. If not, load an error message.
When the page is properly loaded, the firstname and lastname are pre-populated in two input fields. The user completes the rest of the form and clicks submit, inserting their firstname and lastname into the attendance table.
If the firstname and lastname already appear in the attendance table, load an error message. If the firstname AND lastname to not appear in the attendance table, submit the form information to the attendance table.
When it comes to Ajax, I am not the bright bulb in the pack. This is the code I currently have:
HTML
<body>
<div id="formDiv">
<form id="partyForm" name="party" action="party_insert" method="post">
<h1>Welcome to The Party</h1>
<input name="first_name" id="firstname" class="input" type="text" maxlength="99" placeholder="First Name"><br/>
<input name="last_name" id="lastname" class="input" type="text" maxlength="99" placeholder="Last Name"><br/>
<input name="costume" id="costume" class="input" type="text" maxlength="999" placeholder="What are you supposed to be?"><br/>
<div id="buttonDiv">
<a class="button" id="submit" style="cursor:pointer;">SUBMIT</a>
</div>
</form>
</div>
<script>
window.onload = function () {
var fname_init = decodeURIComponent(getUrlVars()["fname"]);
var lname_init = decodeURIComponent(getUrlVars()["lname"]);
if(fname_init !== "undefined" && lname_init !== "undefined"){
var newString = 'fname='+encodeURIComponent(fname_init)+'&lname='+encodeURIComponent(lname_init);
$.ajax({
type: "GET",
url: "guestList.php",
data: newString,
success: function(){
alert("ON THE LIST");
$('#firstname').val(fname_init);
$('#lastname').val(lname_init);
},
error: function(){
alert("NOT ON THE LIST");
window.location = 'error1.html?fname='+encodeURIComponent(fname_init)+'lname='+encodeURIComponent(lname_init);
}
})
}
}
$("#submit").click(function() {
validate();
});
function submit(){
var fname = $("#firstname").val();
var lname = $("#lastname").val();
var cost = $("#costume").val();
var dataString = 'fname='+encodeURIComponent(fname)+'&lname='+encodeURIComponent(lname)+'&cost='+encodeURIComponent(cost);
$.ajax({
type: "POST",
url: "partyEntry.php",
data: dataString,
success: function() {
alert("ENJOY THE PARTY");
clearForms();
}
});
}
function validate(){
if ($("#firstname").val() == ""){
alert("Please Enter your First Name");
} else {
if ($("#lastname").val() == ""){
alert("Please Enter your Last Name");
}else{
if ($("#costume").val() == ""){
alert("You have to have a costume to be eligible for this raffle");
}else{
submit();
}
}
}
}
function clearForms() {
$('#partyForm')[0].reset();
}
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
</body>
guestList.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "party";
$link = mysql_connect($host, $user, $password);
mysql_select_db($database);
//SURVEY INFORMATION
$fname = mysql_real_escape_string($_REQUEST['fname']);
$lname = mysql_real_escape_string($_REQUEST['lname']);
$checkClient = "SELECT * FROM guestlist WHERE first_name = ".$fname." AND last_name = ".$lname;
mysql_query($checkClient) or die(mysql_error());
mysql_close($link);
?>
partyEntry.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "party";
$link = mysql_connect($host, $user, $password);
mysql_select_db($database);
//SURVEY INFORMATION
$fname = mysql_real_escape_string($_REQUEST['fname']);
$lname = mysql_real_escape_string($_REQUEST['lname']);
$cost = mysql_real_escape_string($_REQUEST['cost']);
$addClient = "INSERT INTO attendance (first_name, last_name, costume) VALUES ('$fname','$lname', '$cost')";
mysql_query($addClient) or die(mysql_error());
mysql_close($link);
?>
The error I am getting is that even though a name is not on the guestlist, it will still show that they are ON THE LIST. So I must be doing something wrong in the Ajax call to guestlist.php, but I have no idea what. I also am having problems scripting out an ajax call to check if the guest has already been put into the attendance table.
Like I said in my comment you will have to return a value from the guestList.php, something like this should work:
$checkClient = "SELECT * FROM guestlist
WHERE first_name = ".$fname." AND
last_name = ".$lname;
$result = mysql_query($checkClient);
$count = mysql_num_rows($result);
mysql_close($link);
// output 1 or 0 stating if the user is on the list or not
echo ($count ? 1 : 0);
exit();
Then in your ajax callback you would do a check like:
success:function(e) {
alert((e == 1 ? "User is on list" : "User isn't on list"));
According to the REST principle, responding to a POST request with HTTP 200 means that the resource is successfully created. You can respond with a HTTP 400 and also provide detailed information about the error in text/html/json/xml format.
Try doing this,
Add the folowing code,
$query = mysql_query($addClient) or die(mysql_error());
if(mysql_num_rows($query) > 0)
{
header('HTTP/1.1 500 Internal Server Error');
echo 'this is an error message';
}
The php script will never throw an error at least you try to execute an invalid query. The query is executed without any error because it is well formatted so and error won't be throw because you are not getting rows from the database.