PHP Registration Form not processing AJAX data - javascript

I may be being stupid, but I am trying to process a registration form using an AJAX call to a PHP page. My PHP page is working perfectly on it's own, but when I try to post the form data to the PHP page through AJAX nothing happens.
This is my AJAX call:
$(document).ready(function ($) {
$("#register").submit(function(event) {
event.preventDefault();
$("#message").html('');
var values = $(this).serialize();
$.ajax({
url: "http://cs11ke.icsnewmedia.net/DVPrototype/external-data/register.php",
type: "post",
data: values,
success: function (data) {
$("#message").html(data);
}
});
});
});
This is the form:
<div id="registerform">
<form method='post' id='register'>
<h3>Register</h3>
<p>Fill in your chosen details below to register for an account</p>
<p>Username: <input type='text' name='username' value='' /><br />
Password: <input type='password' name='password' ><br />
Repeat Password: <input type='password' name='repeatpassword'></p>
<input name='submit' type='submit' value='Register' >
<input name='reset' type='reset' value='Reset'><br /><br />
</form>
<div id="message"></div>
</div>
And this is my PHP page:
<?php function clean_string($db_server = null, $string){
$string = trim($string);
$string = utf8_decode($string);
$string = str_replace("#", "&#35", $string);
$string = str_replace("%", "&#37", $string);
if (mysqli_real_escape_string($db_server, $string)) {
$string = mysqli_real_escape_string($db_server, $string);
}
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return htmlentities($string);
}
function salt($string){
$salt1 = 'by*';
$salt2 = 'k/z';
$salted = md5("$salt1$string$salt2");
return $salted;
}
?>
<?php
//form data
$submit = trim($_POST['submit']);
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$repeatpassword = trim($_POST['repeatpassword']);
// create variables
$message = '';
$s_username = '';
//connect to database
{databaseconnection}
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
if(!$db_server){
//error message
$message = "Error: could not connect to the database.";
}else{
$submit = clean_string($db_server, $_POST['submit']);
$username = clean_string($db_server, $_POST['username']);
$password = clean_string($db_server, $_POST['password']);
$repeatpassword = clean_string($db_server, $_POST['repeatpassword']);
//check all details are entered
if ($username&&$password&&$repeatpassword){
//check password and repeat match
if ($password==$repeatpassword){
//check username is correct length
if (strlen($username)>25) {
$message = "Username is too long, please try again.";
}else{
if (strlen($password)>25||strlen($password)<6) {
//check password is correct length
$message = "Password must be 6-25 characters long, please try again.";
}else{
mysqli_select_db($db_server, $db_database);
// check whether username exists
$query="SELECT username FROM users WHERE username='$username'";
$result= mysqli_query($db_server, $query);
if ($row = mysqli_fetch_array($result)){
$message = "Username already exists. Please try again.";
}else{
//insert password
$password = salt($password);
$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($db_server, $query) or die("Registration failed. ".
mysqli_error($db_server));
$message = "Registration successful!";
}
}
}
}else{
$message = "Both password fields must match, please try again.";
}
}else{
$message = "You must fill in all fields, please try again.";
}
}
echo $message;
mysqli_close($db_server);
?>
Apologies for all the code. I feel I may be making a stupid mistake but I don't know why the data isn't being posted or returned.
Thanks in advance!

Notice: This is more a comment than an answer but this is more readable since it includes code.
== EDIT ==
I Checked your code on http://cs11ke.icsnewmedia.net/DVPrototype/#registerlogin, your form doesn't have a id assigned to it
First: use your console...do you see an XMLHTTPREQUEST in your console?
What are the responses/headers etc? I can't stress this enough: use your console and report back here!!!
Next up the overly complicated ajax call...dumb it down to:
$('#register').submit(function(){
$('#message').html('');
$.post("http://cs11ke.icsnewmedia.net/DVPrototype/external-data/register.php",
$(this).serialize(),
function(response){
console.log(response);
$('#message').html(response);
}
);
return false;
});
In your PHP put this on top to check whether anything at all came through:
die(json_encode($_POST));

Please use Firebug or any other tool, to checḱ if the AJAX-script is called, what is its answer and if there are any errors in the script

My form is not submitting data to my database.
This is the PHP code:
<?php require 'core.inc.php'; ?>
<?php require 'connection.inc.php'; ?>
<?php
if(isset($_POST['username']) && isset($_POST['password']) &&
isset($_POST['password_again']) && isset($_POST['firstname']) &&
isset($_POST['surname'])){
$username = $_POST['username'];
$password = $_POST['password'];
$hashed_password = sha1($password);
$password_again = sha1('password again');
$username = $_POST['firstname'];
$password = $_POST['surname'];
//check if all fields have been filled
if(!empty($username)&& !empty($password) && !empty($password_again) &&
!empty($firstname)&& !empty($surname)){
if($password != $password_again){
echo 'Passwords do not match.';
} else {
//check if user is already registered;
$query = "SELECT username FROM user WHERE username = {$username} ";
$query_run = mysqli_query($connection, $query);
if (mysqli_num_rows ($query_run)==1){
echo 'User Name '.$username.' already exists.';
} else {
//register user
$query = "INSERT INTO `user` VALUES ('', '".$username."',
'".$password_hashed."','".$firstname."','".$surname."',)";
}
if($query_run = mysqli_query($connection, $query)){
header('Location: reg_succed.php');
} else {
echo 'Sorry we couldn\'t register you at this time. try again later';
}
}
}
} else {
echo 'All fields are required';
}
?>
<h2>Create New User</h2>
<form id="form" action="<?php echo $current_file ?>" method="POST">
<fieldset title="Login details" id="frame">
<legend>USER LOGIN DETAILS</legend>
<label>User Name:</label><br/>
<input type="text" name = "username" id = "username" value="<?php if(isset($username)){ echo $username; } ?>" maxlength="50" placeholder="Enter your Username" required/><br/>
<label>First Name:</label><br/>
<input type="text" name="firstname" id = "firstname" value="<?php if(isset($firstname)){ echo $firstname;} ?>" maxlength="50" placeholder="Enter your Firstname" required/><br/>
<label>Surname:</label><br/>
<input type="text" name="surname" id="surname" value="<?php if(isset($surname)) {echo $surname;} ?>" maxlength="50" placeholder="Enter your Surname" required/><br/>
<label>Password:</label><br/>
<input type="password" name="password" id="password" maxlength="50" placeholder="Enter your Password" required/><br/>
<label>Password Again:</label><br/>
<input type="password" name="password_again" id="password again" maxlength="50" placeholder="Enter your Password" required/><br/>
<input type="submit" name = "register" id = "register" value="Register">
</fieldset>
</form>
connection code
<?php
require_once("constants.php");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS, DB_NAME);
if (!$connection) {
die("Database connection failed: " . mysqli_error($connection));
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
?>
core.inc.php code
<?php
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];
if(isset( $_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])){
$http_referer = $_SERVER['HTTP_REFERER'];
}
?>

Related

Login redirect using jquery

i'll be glad if anyone can help out am working on a login system using jquery but i encounter a problem
what i want to achieve is user filling out their details on the login page and i'll process it using jQuery at the back end without reloading the page, i have achive that but the problem now is when the details they provide and the details in the database is correct i want to redirect them to another page
here is my login form
<form class="form-login" id="loginmyForm" method="post">
<input class="input input_auth" type="text" name="loginemail" id="loginemail" placeholder="E-mail" required />
<span id="loginError_username" class="error error-opacit"></span>
<input class="input input_auth" type="password" name="loginpassword" id="loginpassword" placeholder="Password" required />
<span id="loginError_password" class="error error-opacit"></span>
<input type="hidden" name="source" value="login" id="source">
<button class="btn pulse input_auth" type="button" id="submitFormData" onclick="loginSubmitFormData();" value="Submit">Login</button>
<div class="forgot-password">
<a id="forgotPass" href="#" class="link-btn open-modal" data-openModal="modal-recovery">Forgot your password?</a>
</div>
Here is jquery code
<script type="text/javascript">
function loginSubmitFormData() {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
var source = $("#source").val();
$.post("authlogin.php", { loginemail: loginemail, loginpassword: loginpassword },
function(data) {
$('#loginresults').html(data);
$('#loginmyForm')[0].reset();
});
}
</script>
And here is the login authentication authlogin.php
<?php
session_start();
include 'config/info.php';
// get the details from form
$email=$_POST['loginemail'];
$password = stripslashes($_REQUEST['loginpassword']);
$password = mysqli_real_escape_string($conn,$password);
$sql="SELECT * FROM user_info WHERE email='".$email."'";
$result = mysqli_query($conn,$sql);
$Countrow = mysqli_num_rows($result);
if ($Countrow == 1) {
$fetchrow = mysqli_fetch_assoc($result);
$loginpassword = $fetchrow['password'];
// Verify the password here
if (password_verify($password, $loginpassword)) {
$_SESSION['email'] = $email;
//setcookie('username', $adminID, time() + (86400 * 30), "/");
$date = date('Y-m-d H:i:s');
$ActivityStmt = "INSERT INTO login_activity (`email`, `last_login`, `browser`, `os`, `ip_address`) VALUES('".$email."', '".$date."', '".$gen_userBrowser."', '".$gen_userOS."', '".$gen_userIP."')";
$ActivityResult = mysqli_query($conn, $ActivityStmt);
echo 'Login Successfully! Click to proceed';
exit();
}
else{
echo 'Incorrect Password';
exit();
}
}
else{
echo 'User does not exit';
exit();
}
?>
I have tried using
header('Location: account');
and
window.location.href = "account";
after the session is saved but none is working, please who can help me on how to get this done
You should try this jQuery Code and PHP Code by replacing them in your code section, It will definitely work for you:
<script type="text/javascript">
function loginSubmitFormData() {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
var source = $("#source").val();
$.post("authlogin.php", { loginemail: loginemail, loginpassword: loginpassword },
function(data) {
var data = jQuery.parseJSON( data );
console.log(data);
$('#loginresults').html(data.message);
if(data.redirect_url){
window.location.href = data.redirect_url;
}
$('#loginmyForm')[0].reset();
});
}
</script>
<?php
session_start();
include 'config/info.php';
// get the details from form
$email=$_POST['loginemail'];
$password = stripslashes($_REQUEST['loginpassword']);
$password = mysqli_real_escape_string($conn,$password);
$sql="SELECT * FROM user_info WHERE email='".$email."'";
$result = mysqli_query($conn,$sql);
$Countrow = mysqli_num_rows($result);
if ($Countrow == 1) {
$fetchrow = mysqli_fetch_assoc($result);
$loginpassword = $fetchrow['password'];
// Verify the password here
if (password_verify($password, $loginpassword)) {
$_SESSION['email'] = $email;
//setcookie('username', $adminID, time() + (86400 * 30), "/");
$date = date('Y-m-d H:i:s');
$ActivityStmt = "INSERT INTO login_activity (`email`, `last_login`, `browser`, `os`, `ip_address`) VALUES('".$email."', '".$date."', '".$gen_userBrowser."', '".$gen_userOS."', '".$gen_userIP."')";
$ActivityResult = mysqli_query($conn, $ActivityStmt);
$message = 'Login Successfully!';
$response = array(
'message' => $message,
'redirect_url' => 'https://www.example.com',
);
exit();
}
else{
$message = 'Incorrect Password';
$response = array(
'message' => $message
);
exit();
}
}
else{
$message = 'User does not exit';
$response = array(
'message' => $message,
);
exit();
}
echo json_encode( $response);
?>

PHP Ajax not responding

In the username availability check I created two pages: register.php and registercontrol.php controlling it. I check the database connection its on work. Everything (all statements, insertin data into db) that was previously created on a single php page. But when ajax validates other inputs its duplicates the html content and shows the error inside of it instead of showing error messages in a just single html element.
So I seperated it into two pages but now ajax not shows any error and responds. Here is my work:
registercontrol.php
<?php
require('../includes/config.php');
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username must be at least 6 alphanumeric characters';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
$errorun[] = 'This username already in use';
}
}
}
?>
register.php
<script type="text/javascript">
$(document).ready(function(){
$("#username").keyup(function(event){
event.preventDefault();
var username = $(this).val().trim();
if(username.length >= 3){
$.ajax({
url: 'registercontrol.php',
type: 'POST',
data: {username:username},
success: function(response){
// Show response
$("#uname_response").html(response);
}
});
}else{
$("#uname_response").html("");
}
});
});
</script>
<form id="register-form" class="user" role="form" method="post" action="registercontrol.php" autocomplete="off">
<input type="text" name="username" id="username" class="form-control form-control-user" placeholder="Username" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="2" required>
<div id="uname_response" ></div>
</form>
we need to print the response in registercontrol.php so that we can get response in your register.php
Change your code as below
<?php
require('../includes/config.php');
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
echo 'Your username must be at least 6 alphanumeric characters';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
echo 'This username already in use';
}
}
}
?>
You need to return or echo something from registercontrol.php
<?php
require('../includes/config.php');
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username must be at least 6 alphanumeric characters';
echo json_encode($infoun);
exit;
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
$errorun[] = 'This username already in use';
echo json_encode($errorun);
exit;
}
echo $row[username];
exit;
}
}
?>

Form is not posting / running the script

I am using a register script but by some reason this script is not working.
First of all here is my <html> form:
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<legend>Member Registration</legend>
<p><label>Username:</label><input name="username" type="text" maxlength="20" <?php if(isset($error)) {echo "value='$username'";} ?> /></p>
<p><label>Password:</label><input name="password" type="password" maxlength="20" /></p>
<p><label>Confirm Password:</label><input name="password2" type="password" maxlength="20" /></p>
<p><label>Email:</label><input name="email" type="text" maxlength="255" <?php if(isset($error)) {echo "value='$email'";} ?> /></p>
<p><input type="submit" name="submit" value="Register"></p>
</form>
After clicking on the submit button the script needs to get posted. Before adding the values to the database the php script should do a check:
if (strlen($username) < 3){
$error[] = 'User name must be between 3 and 20 characters.';
}
When I enter just 1 character also this is not checked. When I click on the submit button the script returns into its first state.
Why is this happening? I have set the reporting of errors on, but also when I do that I dont get any error message.
How can I fix this problem?
Here is my full PHP code:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'db';
$conn = mysqli_connect ($dbhost, $dbuser, $dbpass);
$conn = mysqli_select_db ($conn, $dbname);
if(!$conn){
die( "Sorry! There seems to be a problem connecting to our database. Please give us a few minutes to remedy the problem. Thank you.");
}
function errors($error){
if (!empty($error))
{
$i = 0;
while ($i < count ($error)){
echo '<span class="warning">'.$error[$i].'</span>';
$i ++;
}
}
if (isset($_POST['submit'])){
$username = trim($_POST['username']);
if (strlen($username) < 3){
$error[] = 'User name must be between 3 and 20 charactors.';
}
if(!get_magic_quotes_gpc()){
$POST[] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$check = mysqli_query($conn, "SELECT username FROM users WHERE username ='".$usercheck."'")or die(mysqli_error());
$check2 = mysqli_num_rows($check);
if ($check2 != 0) {
$error[] = 'Sorry, the username <b>'.$_POST['username'].'</b> is already in use.';
}
$password = trim($_POST['password']);
if (strlen($password) < 5) {
$error[] = 'password Must be between 5 and 20 characters.';
}
if ($_POST['password'] != $_POST['password2']) {
$error[] = 'Your passwords did not match.';
}
if (!get_magic_quotes_gpc()) {
$_POST[] = addslashes($_POST['email']);
}
$emailcheck = $_POST['email'];
$hash = md5( rand(0,1000) );
$emailcheck1 = mysqli_query($conn, "SELECT email FROM members WHERE email = '".$emailcheck."'")or die(mysqli_error());
$emailcheck2 = mysqli_num_rows($emailcheck1);
if ($emailcheck2 != 0) {
$error[] = 'Sorry, the email address <b>'.$_POST['email'].'</b> is already in use, Please choose another email address.';
}
if (!$error ) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(!get_magic_quotes_gpc())
{
$username = addslashes($username);
$password = addslashes($password);
$email = addslashes($email);
}
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
$email = mysqli_real_escape_string($email);
$username = strip_tags($username);
$password = strip_tags($password);
$email = strip_tags($email);
$username = ucwords(strtolower($username));
$email = strtolower($email);
$insert1 = "INSERT INTO members (username, password, email) VALUES ('$username', md5('$password'), '$email')";
$result1 = mysqli_query($insert1) or die('Error : ' . mysqli_error());
}
}
}
?>

Creating update user profile page using PHP MySql

I have managed to go ahead with my user update page and it all seems to be fine at the form I had it reading the current details from logged in user when i clicked submit it says submit successful, then I am stuck with this page can't go back, I don't know if it worked and cannot see any error messages or any that i can see.
I am very new to coding so sorry if any silly mistake i missed out on... someone help me please....
Here is my PHP
<?php
include_once("php_includes/check_login_status.php");
session_start();
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
else {
echo "You have not signed in";
}
// Initialize any variables that the page might echo
$firstname = "";
$surname = "";
$u = "";
$weight = "";
$height = "";
// Make sure the _GET username is set, and sanitize it
if(isset($_GET["u"])){
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
header("location: index.php");
exit();
}
// Select the member from the users database table
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// check if the user exists in the database
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
exit();
}
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$firstname = $row["firstname"];
$surname = $row["surname"];
$weight = $row["weight"];
$height = $row["height"];
$profile_id = $row["id"];
$u = $row["u"];
}
// this is the calculation of the BMI index
//$BMI = ($weighteight / ($heighteight * $heighteight))* 10000;
if($firstname =="" || $surname == ""|| $weight == "" || $height == ""){
echo "The form submission is missing values.";
exit();
} else {
$p_hash = md5($p);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (firstname, surname, weight, height)
VALUES('$fn','$sn','$w','$h')";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// 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);
}
// Email the user their activation link
$to = "$e";
$from = "k1003140#kingston.ac.uk";
$subject = 'studentnet.kingston.ac.uk/k1003140';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
?>
Here is my Javascript code
<script>
function signup(){
var u = _("username").value;
var fn = _("firstname").value;
var sn = _("surname").value;
var w = _("weight").value;
var h = _("height").value;
var e = _("email"). value;
var status = _("status");
if(fn == "" || sn == "" || w == "" || h == ""|| g == ""){
status.innerHTML = "Fill out all of the form data";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").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("fn="+fn+"&sn="+sn+"&w="+w+"&h="+h+);
}
}
here i added some more of my code to see the HTML
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<form name="signupform" id="signupform" onsubmit="return false;">
<div id="usernamecss"><?php echo $u; ?></div>
<p><b>Is the viewer the page owner, logged in and verified? <?php echo $isOwner; ?></b></p>
<p>First Name: <input type="text" name="firstname" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$firstname?>'></p>
<p>Surname: <input type="text" name="surname" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$surname?>'></p>
<p>Weight: <input type="text" name="weight" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$weighteight?>'></p>
<p>Height: <input type="text" name="height" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$heighteight?>'></p>
<button id="signupbtn" onclick="signup()">Create Account</button>
</div>
</form>
<?php include_once("template_pageBottom.php"); ?>
<span id="status"></span>
</body>
i can't write comment so i will write here
U should use session_start(); at the first line of the page and this may cause some problem try it
session_start();
include_once("php_includes/check_login_status.php");
As I can see you are doing a POST in your ajax but are reacting to GET in your php.
Try to change:
if(isset($_GET["u"])){
to:
if(isset($_POST["u"])){
or:
if(isset($_REQUEST["u"])){

How do I perform 2 AJAX requests on one form submit?

Short version:
I have code to insert a forms contents into a database
I have code to send the form data to Salesforce as a lead
Both of these work fine ALONE (If I change the form "action" to either of the PHP scripts) -- but when I attempt to combine them into 1 PHP script, the form invalidates and I can't figure out why.
Here's the code for inserting into DB:
<?php
include ".db_config.php";
/* open a connection to the database */
$link = connect_db();
/* grab all of the required fields */
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$pcode = $_POST['pcode'];
$terms = $_POST['terms'];
$news = $_POST['news'];
$facebookConnection = '0';
/* check to make sure it's valid email address */
$email = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$language = $_POST['language'];
/* check to see if this was a facebook connection */
$facebookID = '';
if(isset($_POST['facebookID'])){
$facebookID = $_POST['facebookID'];
}
/* check to see if this signature connected to Facebook */
if($facebookID != ""){
$facebookConnection = '1';
}
/* set the true/false flag for the terms and conditions agreement. */
if ($terms == 'terms'){
$terms = 1;
}
else{
$terms = 0;
}
/* set the true/false flag for the updates sign up */
if($news =='news'){
$news = 1;
}
else {
$news =0;
}
$success='';
$error='';
// Check to see if the email exists already in the database
$query = "select count(*) as counting from signedUsers where eMailAddress ='$email'";
$result = do_query($query);
$emailIncluded = '0';
/* get the number of rows from the table where this email address is. */
while($row = mysql_fetch_array($result))
{
/* if there is 1 or more row, then the email exists. */
if ($row["counting"] > 0)
{
$emailIncluded = '1';
}
}
/* if the email address doesn't exist, save it and return 'success' */
if ($emailIncluded == '0'){
$insert = "insert into signedUsers (FirstName, LastName, eMailAddress, PostalCode, ToC,eMailUpdates, language, facebookID, FacebookConnection) values('$firstName','$lastName','$email', '$pcode', $terms, $news, '$language', '$facebookID', $facebookConnection)";// Do Your Insert Query
if(mysql_query($insert)) {
$success='1';
} else {
$error='failed insert';
}
}
/* if the email address exists, return 'error' to be dealt with on the front end that explains it. */
else {
$error = 'email exists';
$success = '';
}
$arr = array(
'success'=>$success,
'error'=>$error
);
if ($success == '1')
{
header('Content-Type: application/json');
$arr = array(
'success'=>$success,
);
echo json_encode($arr);
}
else
{
header('HTTP/1.1 500 Internal Server');
header('Content-Type: application/json');
//die('ERROR');
// or:
die(json_encode(array('message' => 'ERROR', code => $error)));
}
mysql_close($link);
?>
Here's the code to send to sailesforce:
<?php
$req = "&lead_source=" . urlencode($_GET["1"]);
$req .= "&first_name=" . urlencode($_GET["2"]);
$req .= "&last_name=" . urlencode($_GET["3"]);
$req .= "&zip=" . urlencode($_GET["4"]);
$req .= "&email=" . urlencode($_GET["5"]);
$req .= "&debug=" . urlencode("0");
$req .= "&oid=" . urlencode("00Di0000000fnSP");
$req .= "&retURL=" . urlencode("#");
$req .= "&debugEmail=" . urlencode("sam.stiles#orangesprocket.com");
$header = "POST /servlet/servlet.WebToLead?encoding=UTF-8 HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: www.salesforce.com\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.salesforce.com', 80, $errno, $errstr, 30);
if (!$fp) {
echo "No connection made";
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
echo $res;
}
}
fclose($fp);
?>
Again, these both work INDIVIDUALLY, bot not together in the same PHP file.
Here's the form & the AJAX:
//Setup contact form validation
jQuery('#petition-form').validate({
rules: {
firstName: "defaultInvalid",
lastName: "defaultInvalid",
email: "defaultInvalid",
email: "emailValid",
emailConfirm: "defaultInvalid",
emailConfirm: "emailValid",
pcode: "postalcode"
},
messages: {
firstName: "",
lastName: "",
email: "",
emailConfirm: "",
pcode: "",
terms: ""
},
errorLabelContainer: '#message',
onkeyup: false,
onfocusout: false,
onclick: false,
submitHandler: function(form){
//Serialize the form data
//Serialize the form data
var formData = jQuery('#petition-form').serialize();
//Send the form data to the script
jQuery.ajax({
type: 'POST',
url: '/resource/php/signThePetition.php',
data: formData,
dataType: 'json',
error: contactFormErrorMsg,
success: contactFormSuccessMsg
});
//Stop the form from refreshing the page on submit
return false;
}
});
});
//Contact form error messages
function contactFormErrorMsg() {
jQuery('#message').show();
jQuery('[name="emailConfirm"]').val('This email has already signed the petition. Thank you.');
return false;
/* this means that the email address already exists */
}
//Contact form success messages
function contactFormSuccessMsg() {
jQuery('input, select').removeClass('error').removeClass('valid');
jQuery('#petition-2').fadeOut();
jQuery('#petition-3').fadeIn();
resetForm(jQuery('#petition-form'));
}
// ]]>
</script>
<form name="petition-form" id="petition-form" action="/resource/php/sendEmail_contact.php" method="post">
<p id="message">There was an error in the form below. Please fix it before proceeding.</p>
<input type="text" name="firstName" placeholder="First name*" class="required short pad">
<input type="text" name="lastName" placeholder="Last name*" class="required short"><br />
<input type="text" name="email" id="email" placeholder="Email*" class="required email"><br />
<input type="text" name="emailConfirm" placeholder="Confirm email*" class="required email" equalTo="#email"><br />
<input type="text" name="pcode" placeholder="Postal code*" class="required short pad"><br />
<input type="checkbox" name="terms" value="terms" class="required"><span class="terms">I have read and agree to the terms and conditions</span><br />
<input type="checkbox" name="news" value="news" checked="checked">Send me updates and action alerts from Partners for Mental Health
<input type="hidden" name="language" id="language" value="en_US" class="required" ><br />
<input type="hidden" name="facebookID" id="facebookID" value="" class="required" >
<div id="form-buttons">
<button type="submit" value="Submit" name="submit" class="black-button">Submit</button>
</div>
</form>
Are you outputting HTTP headers twice when you combine the scripts?
Incidentally, there's no reason you can't fire off jQuery.ajax() twice in a row, once to each script.

Categories