Contact form validation with php using ajax and jQuery - javascript

I am new to php and jQuery but I managed to create a contact form that I send to my email address using jQuery ajax and php.
I have a small problem. My contact form is only sent if the user fills in all the entries directly. If for example, he writes an invalid email, there is the validation (client side) that is displayed and if he writes a valid email, the contact form is not sent anymore.
I think it's because of my isValid variable. If I understand correctly, I have defined a ValidateInputs function with some validations. And when there is no error, IsValid is set to true. I guess when I send the data to php via ajax, I set the isValid to true but I am probably missing something
Hope I am clear
Any help?
My javascript code:
$(document).ready(function() {
$('#contactForm').on('submit', function(event) {
event.preventDefault();
validateInputs()
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
if(isValid) {
$.ajax({
url: url,
type: type,
data: data,
});
console.log('send')
} else{
console.log('not sent')
}
return false;
});
});
var isValid = true;
function validateInputs() {
var nameValue = $('#name').val();
var emailValue = $('#email').val();
var subjectValue = $('#subject').val();
var messageValue = $('#message').val();
const regex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (nameValue == '' ) {
$('#error').html('This field is required');
isValid = false;
} else if(nameValue.length < 3) {
$('#error').html('Name needs to be at least 3 characters');
isValid = false;
}
else {
$('#error').html('');
//$('.inputbox').css('border', 'solid 1px green');
}
if (emailValue == '' ) {
$('#errorMail').html('This field is required');
isValid = false;
} else if (!$('#email').val().match(regex)) {
$('#errorMail').html('Please enter a valid email address');
isValid = false;
}
else {
$('#errorMail').html('');
}
if (subjectValue == '' ) {
$('#errorSubject').html('This field is required');
isValid = false;
}
else {
$('#errorSubject').html('');
}
if (messageValue == '' ) {
$('#errorMessage').html('This field is required');
isValid = false;
} else if (messageValue.length < 20) {
$('#errorMessage').html('Name needs to be at least 20 characters');
isValid = false;
}
else {
$('#errorMessage').html('');
}
return isValid
}
And this is my PHP code:
<?php
if(isset($_POST['submit'])){
$mailto = "contact#statsmap.ch"; //Send the email to this address
//All the inputs informations
$mailfrom = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = "NAME: " .$name. "\r\n\n". "Wrote the following Message:" ."\r\n". $_POST['message'];
$message = $_POST['message'];
$headers = "From: ". $mailfrom;
$sendMail = mail($mailto, $message, $headers); // Send mail to website owner
}
?>

Related

What is the array output type here

On line 24 where I test if the test2[1] == "invalid" never works it always goes to the else and takes me to the next page. I think test2[1] just isn't a string but I don't know what else it would be please help
function login() {
var email = document.getElementById("email").value;
var passW = document.getElementById("password").value;
if (email == "" || passW == "") {
alert("Please enter a valid email or password.");
} else {
var myXMLRequest = new XMLHttpRequest();
myXMLRequest.onload = openWorkout;
var url = "assignment10.php?em=" + email + "&pass=" + passW;
myXMLRequest.open("POST", url, true);
myXMLRequest.send();
}
}
function openWorkout() {
var invalid = "invalid";
var step = this.responseText;
var test = step.split(",");
var test2 = test[0].split(":");
console.log(step);
console.log(test);
console.log(test2[1]);
if (test2[1] == "invalid") {
alert("The email or password you entered is invalid. Please try again.");
} else {
window.location = "#workoutPage";
}
}
<?php
//TASK 1: MAKE A CONNECTION TO THE DATABASE, DISPLAY ERROR FOR FAILED CONNECTIONS
//(FOR GODADDY) NOTE: $mysqli = new mysqli("127.0.0.1", "username", "password", "database", 3306);
$mysqli = new mysqli("localhost", "User", "1234", "ass10");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//CHECK IF EMAIL AND ENTERED PASSWORD VALID (LOGIN PAGE [first part of open workout checks login password])
$entEmail = $_GET['em'];
$entPassword = $_GET['pass'];
$sql = "SELECT * FROM membership_table WHERE Email = $entEmail, Password = $entPassword";
$result = $mysqli->query($sql);
if($result->num_rows == 0) {
$data = "invalid";
} else {
$data = "valid";
}
//Pass to JSON
$json = array(
"data" => $data,
"Email" => $entEmail,
"Password" => $entPassword
);
header("Contenttype:Application/json");
print(json_encode($json));
?>
here are the console.log outputs on lines 21 - 23
assignment10.js:21 {"data":"invalid","Email":"q","Password":"1"}
assignment10.js:22 (3) ["{"data":"invalid"", ""Email":"q"", ""Password":"1"}"]
assignment10.js:23 "invalid"
You're returning JSON from your PHP, so process it as that using JSON.parse, rather than trying to split the string apart:
var response = JSON.parse(this.responseText);
var test = response.data;
if (test == 'invalid') {
...
Note the issue with your current code is that test2[1] is literally "invalid", including the double quotes, so for your test to work you'd need to use
if (test2[1] == '"invalid"') {
Here's a snippet to demonstrate the code using the output of console.log(step) from your question:
const responseText = '{"data":"invalid","Email":"q","Password":"1"}';
var response = JSON.parse(responseText);
var test = response.data;
if (test == 'invalid') {
console.log('Invalid!');
} else {
console.log('Valid!');
}

PHP Ajax Callback responseText Error

As I was coding I encountered an absolute annoying error when callbacking the responseText from PHP.
Now the issue is that, when I run the fpass.php file, and fill out the data, everything works except when callbacking the responseText, for example if it prints out MAIN_FPASS_USER_NO_MATCH from the PHP file it should change the _('status').innerHTML to a different text of my choice, and not what the PHP printed. Some ideas for what I missed in my code?
JS Script:
function fpass(){
var e = _("email").value;
if(e == ""){
_("status").innerHTML = "Type in your email address</br></br>";
} else {
_("fpassbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "/fpass.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == 'MAIN_FPASS_SUCCESS'){
_("fpassform").innerHTML = '<h3>Step 2. Check your email inbox in a few minutes</h3><p>You can close this window or tab if you like.</p>';
} else if(ajax.responseText == "MAIN_FPASS_USER_NO_MATCH"){
_("fpassbtn").style.display = "none";
_("status").innerHTML = "Sorry that email address is not in our system";
} else if(ajax.responseText == "MAIN_FPASS_EMAIL_FAILURE"){
_("fpassform").innerHTML = "Mail function failed to execute";
} else if (ajax.responseText == "MAIN_FPASS_EXISTS") {
_("fpassform").innerHTML = "already fpass";
} else {
_("status").innerHTML = ajax.responseText;
}
}
}
}
ajax.send("e="+e);
}
JS Functions:
// getElementById Function
function _(x){
return document.getElementById(x);
}
// emptyElement Function
function emptyElement(x){
_(x).innerHTML = "";
}
Ajax Functions:
function ajaxObj(meth, url){
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//x.send(data);
return x;
}
// END Ajax Object
// Start Ajax Return
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
HTML Code:
<span id="status"></span>
<form id="fpassform" onsubmit="return false;">
<input id="email" type="text" placeholder="Email" onfocus="emptyElement('status')" maxlength="88">
<button id="fpassbtn" onclick="fpass()">Reset</button></br>
</form>
PHP Code:
// AJAX CALLS THIS CODE TO EXECUTE
if(isset($_POST['e'])){
include_once("vendor/db.php");
$e = $mysqli->real_escape_string($_POST['e']);
$usql = "SELECT * FROM users WHERE useremail='$e' AND activated='1' LIMIT 1";
$uresult = $mysqli->query($usql);
$unumrows = $uresult->num_rows;
if($unumrows == 1){
$fpsql = "SELECT * FROM forgotpass WHERE useremail='$e' LIMIT 1";
$fpresult = $mysqli->query($fpsql);
$fpnumrows = $fpresult->num_rows;
if($fpnumrows == 0) {
if($fetch = $uresult->fetch_array(MYSQLI_FETCH_ASSOC)){
$u = $fetch["username"];
$e = $fetch['useremail'];
$pn = $fetch['userphone'];
$fpkey = substr(md5(uniqid($u)), 0, 14);
$sql = "INSERT INTO `forgotpass` (username,useremail,userphone,fpkey)
VALUES ('$u','$e','$pn','$fpkey') ";
if($mysqli->query($sql)) {
$to = "$e";
$from = "auto_responder#yoursite.com";
$headers ="From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \n";
$subject ="yoursite Temporary Password";
$msg = 'MSG here';
if(mail($to,$subject,$msg,$headers)) {
echo 'MAIN_FPASS_SUCCESS';
exit();
} else {
echo 'MAIN_FPASS_MAIL_FAILURE';
exit();
}
}
}
} else {
echo 'MAIN_FPASS_EXISTS';
exit();
}
} else {
echo 'MAIN_FPASS_USER_NO_MATCH';
exit();
}
exit();
}

How form validation/ data limitation of a vehicle_number and date using codeigniter

i dont include here the form input Etc. because my code is working.
i want a form validation like this query is to select delivery table if "vehicle 1" appears on the database 5 times and on the same delivery date. alert an error that Vehicle 1 need to have a delivery 5 times only on that date."
DATABASE:
vehicle_name | delivery_date
vehicle 1 8/29/2016
vehicle 1 8/29/2016
vehicle 1 8/29/2016
vehicle 1 8/29/2016
vehicle 1 8/29/2016
on the 6th input
input: vehicle 1
input: 8/29/2016
there is no problem in my inputs. i just want a validation that you cannot add any delivery anymore if "vehicle 1" exist 5 times on delivery table on 8/29/2016. HOW WILL I CODE THAT?"
Controller
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('client_firstname') == '')
{
$data['inputerror'][] = 'client_firstname';
$data['error_string'][] = 'First name is required';
$data['status'] = FALSE;
}
if($this->input->post('client_lastname') == '')
{
$data['inputerror'][] = 'client_lastname';
$data['error_string'][] = 'Last name is required';
$data['status'] = FALSE;
}
if($this->input->post('client_contact') == '')
{
$data['inputerror'][] = 'client_contact';
$data['error_string'][] = 'Customer contact is required';
$data['status'] = FALSE;
}
if($this->input->post('client_address') == '')
{
$data['inputerror'][] = 'client_address';
$data['error_string'][] = 'Address is required';
$data['status'] = FALSE;
}
if($this->input->post('tracking_no') == '')
{
$data['inputerror'][] = 'tracking_no';
$data['error_string'][] = 'Tracking number is required';
$data['status'] = FALSE;
}
if($this->input->post('vehicle_id') == '')
{
$data['inputerror'][] = 'vehicle_id';
$data['error_string'][] = 'Vehicle Assignation Required';
$data['status'] = FALSE;
}
if($this->input->post('delivery_status') == '')
{
$data['inputerror'][] = 'delivery_status';
$data['error_string'][] = 'Delivery status is required';
$data['status'] = FALSE;
}
if($this->input->post('delivery_date') == '')
{
$data['inputerror'][] = 'delivery_date';
$data['error_string'][] = 'Delivery Date is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
Model
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
on my script
function add_delivery()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Delivery'); // Set Title to Bootstrap modal title
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo base_url('index.php/delivery/ajax_add')?>";
$('#btnSave').text('Add Delivery');
} else {
url = "<?php echo base_url('index.php/delivery/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
alert('Successfully Added');
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('Save Delivery'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('Save Delivery'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
In Model
function getVeichleCount($vehicle_name, $delivery_date)
{
$query = $this->db->query("SELECT count(id) FROM table_name WHERE vehicle_name = '$vehicle_name' AND delivery_date = $delivery_date ");
$result = $query->result_array();
return $result;
}
In Callback function
$count = $this->model_name->getVeichleCount($vehicle_name, $delivery_date)[0];
if ($count >= 5) {
# count already have 5 records
# your error goes here
}

how to check username and password through url by using javascript

i am developing hybrid application by using intel xdk tool and jquery mobile framework for UI. i am trying to implement login function which means i just type username and password and click submit button. while cliking button i am calling javascript function for checking username and password whether it is correct or not. this is my javascript function for login
var user, pwd ;
var xmlHttp = null;
var val;
$("#Login").click(function(event){
event.preventDefault();
user = $("#username").value() ;
pwd = $("#password").value() ;
validateForm();
});
function validateForm() {
var url ="http://schoolsmartconnect.com/android/parent_login.php?key=agile89rise98&username="+user+"&password="+pwd;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ProcessRequest;
xmlHttp.open( "POST", Url, true );
xmlHttp.send( null );
if (val == "1") {
window.location = "page2.html";
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
function ProcessRequest()
{
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 )
{
if ( xmlHttp.responseText == "1" )
{
var val = xmlHttp.responseText;
}
}
}
this is my severside PHP script
<?php
require_once 'db.php';
$user = base64_decode($_REQUEST['username']);
$pass = base64_decode($_REQUEST['password']);
$key = $_REQUEST['key'];
$password = md5($pass);
if($key=="agile89rise98"){
//echo $password;
$query = mysql_query("SELECT * FROM puserprofile WHERE username ='$user' AND password = '$password' and Status=1");
$rownum = mysql_num_rows($query);
if(0 < $rownum)
{
echo 1;
}
else
{
$query2 = mysql_query("SELECT * FROM puserprofile WHERE username ='$user' and Status=1");
$rownum2 = mysql_num_rows($query2);
if(0 == $rownum2) {
$query3 = mysql_query("SELECT * FROM puserprofile WHERE password = '$password' and Status=1");
$rownum3 = mysql_num_rows($query3);
if (0 == $rownum3) {
echo 0;
}
else if(!preg_match('/^[A-Za-z]{1}[A-Za-z0-9]{5,31}$/', $user){
echo "username invalid";
}
else {
echo "Invalid username";
}
} else {
$query3 = mysql_query("SELECT * FROM puserprofile WHERE password = '$password' and Status=1");
$rownum3 = mysql_num_rows($query3);
if (0 == $rownum3) {
echo "Invalid password";
} else {
echo 0;
}
}
}
}
?>
My Requirement:-
i am sure my php script is correct, but In my javascript function i have to send my username and password request to server and get response also, if my response is equal to "1" then it redirect appropriate page otherwise it should display error messages
For your need, why don't you just retrieve username and password from the input fields instead of getting them from the url.
It will be easy enough to get the values from the input fields and validate them.
Do something like this
<input type="text" id="user"/>
<input type="password" id="pwd"/>
<input type="submit" id="submit"/>
And in the script, do this
var user, pwd ;
$("#submit").click(function(event){
event.preventDefault();
user = $("#user").value() ;
pwd = $("#pwd").value() ;
validateForm();
});
UPDATE
Now the script will look like this
var user, pwd ;
var xmlHttp = null;
var val;
$("#Login").click(function(event){
event.preventDefault();
user = $("#username").value() ;
pwd = $("#password").value() ;
validateForm();
});
function validateForm() {
var url ="http://schoolsmartconnect.com/android/parent_login.php?key=agile89rise98&username="+user+"&password="+pwd;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = ProcessRequest;
xmlHttp.open( "GET", url, true );
xmlHttp.send( null );
}
function ProcessRequest()
{
if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 )
{
if ( xmlHttp.responseText === "1" )
{
var val = xmlHttp.responseText;
if (val == "1") {
window.location = "page2.html";
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
}
}

AJAX Sends back entire page instead of result

I am having a little trouble figuring out why my ajax response is sending me the entire page.
I am not using conventional AJAX code simply because this is how the guy was doing it in a tutorial I was following. I am using firebug to track all my javascript variables and when I break the code at the responseText var it gives me the entire page. Here is the code for the javascript on the page I am working with :
function changepass() {
var u = _("username").value;
var cp = _("currentPass").value;
var np = _("newPass").value;
var cnp = _("confirmNewPass").value;
if(np != cnp) {
_("status").innerHTML = "The passwords given do not match!";
} else if (cp === "" || np === "" || cnp === "") {
_("status").innerHTML = "Please fill out all of the fields.";
} else {
_("changepassbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "change_password.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var response = ajax.responseText;
if(response == "success"){
_("status").innerHTML = "Your password change was successful! Click the button below to proceed.<br><br>Back To Home Page";
} else if (response == "no_exist"){
_("status").innerHTML = "Your current password was entered incorrectly.";
_("changepassbtn").style.display = "initial";
} else if(response == "pass_failed"){
_("status").innerHTML = "Change password function failed to execute!";
_("changepassbtn").style.display = "initial";
} else {
_("status").innerHTML = "An unknown error occurred";
_("changepassbtn").style.display = "initial";
}
}
}
ajax.send("u="+u+"&cp="+cp+"&np="+np+"&cnp"+cnp);
}
}
Here is the AJAX code that I use to handle the requests.
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Any help would be greatly appreciated.
Thanks!
Here is the server side PHP:
if(isset($_POST["u"]) && isset($_POST['oe']) && isset($_POST['ne']) && isset($_POST['p'])) {
$oe = mysqli_real_escape_string($db_conx, $_POST['oe']);
$ne = mysqli_real_escape_string($db_conx, $_POST['ne']);
$p = md5($_POST['p']);
$u = mysqli_real_escape_string($db_conx, $_POST['u']);
var_dump($oe, $ne, $p, $u);
$sql = "SELECT username, password, email FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_username = $row[0];
$db_password = $row[1];
$db_email = $row[2];
var_dump($db_username, $db_password, $db_email);
if($db_email != $oe) {
echo "bad_email";
exit();
} else if($db_password != $p) {
echo "no_exist";
exit();
} else {
$sql = "UPDATE users SET email='$ne' WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$sql = "SELECT email FROM users WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_newemail = $row[0];
if($db_newemail == $ne) {
echo "success";
exit();
} else {
echo "email_failed";
exit();
}
}
}
My mistake was a simple syntax error. Gosh PHP is picky! The error occurs in the ajax.send command. I am miss an '=' on the last parameter.
Thanks for your help guys!

Categories