Submit form with javascript/jquery after php validation - php

Could someone help me with this problem.
I have to submit a form after I checked if the database doesn't contain the inserted email.
PHP code for email control
$email = $_POST['email'];
$sql = "SELECT * FROM sc_user WHERE email='" . $email . "'";
$select = mysql_query($sql);
$row = mysql_num_rows($select);
$conn_object->connection_signout();
if($row > 0)
echo "exist";
else
echo "notexist";
PHP code for inserting new user in database
if (isset($_POST['submit_registration']))
{
$sql = "INSERT INTO sc_user (name, surname, email, password) VALUES ('" . $_POST['user_name'] . "',
'" . $_POST['user_surname'] . "', '" . $_POST['email'] . "', '" . md5($_POST['password']) . "')";
if (mysql_query($sql))
{
$conn_object->connection_signout();
}
header("Location: index.php");
}
Part of the javascript code I have is this.
$(document).ready(function(){
$("#register_form").submit(function(evReg) {
evReg.preventDefault();
//other code...
$.post('../PHP/checkMail.php', {'email' : email}, function(data) {
if(data == 'exist')
{
$('#email_id').val('');
$('#email_id').attr('placeholder', 'User already registered with this email');
$('#email_id').addClass('placeholder_red');
$('#email_id').focus();
}
else
{
$(this).submit();
}
});
//this.submit();
//other code
If I put "this.submit();" outside "$.Post(...);" block the form will submit corectly, but if is inside it's like it doesn't find the form, I think.
Sorry for the english, I hope you will understand my problem.
I've tried using this
document.getElementById("register_form").submit();
but it doesn't work. I hope I give you all the information you ned.

It doesn't work because you are inside the scope of the callback function of $.post() so $(this) doesn't reference properly to your form, you can try changing your code like this:
$("#register_form").submit(function(evReg) {
evReg.preventDefault();
var $this = $(this);
//other code
and then in your callback function submitting the form using the $this variable
if(data == 'exist')
{
$('#email_id').val('');
$('#email_id').attr('placeholder', 'User already registered with this email');
$('#email_id').addClass('placeholder_red');
$('#email_id').focus();
}
else
{
$this.submit();
}
I haven't tested your code, so i cannot be sure it works but different times this worked for me.

Related

how do i validate if my email is already exist? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
if(count($_POST)>0) { /* Form Required Field Validation / foreach($_POST as $key=>$value) {
if(empty($_POST[$key])) {
$message = ucwords($key) . " field is required"; break; } } / Password Matching Validation */
if($_POST['password'] != $_POST['confirm_password']){ $message = 'Passwords should be same '; }
/* Email Validation */ if(!isset($message)) { if (!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) { $message = "Invalid UserEmail"; }
}
/* Validation to check if gender is selected */ if(!isset($message)) { if(!isset($_POST["gender"])) { $message = " Gender field is required"; } }
if(!isset($message)) { require_once("dbcontroller.php"); $db_handle = new DBController();
$query = "INSERT INTO users (username, name, last_name, gender, BirthMonth, BirthDay, BirthYear, Country, email, password, phone) VALUES ('" . $_POST["userName"] . "', '" . $_POST["name"] . "', '" . $_POST["lastName"] . "', '" .$_POST["gender"] . "', '" . $_POST["BirthMonth"] . "', '" . $_POST["BirthDay"] . "' , '" . $_POST["BirthYear"] ."','". $_POST["Country"] ."', '" . $_POST["userEmail"]. "','" . $_POST["password"]. "','".$_POST["Phone"]. "')"; $result = $db_handle->insertQuery($query);
Edit: Format the code to visib;e errors better. Thanks in advance to anyone who answers.
you want to check that your email is exit in database then use this code. add this code after this line .
/* Email Validation */ if(!isset($message)) { if(!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL))
{ $message = "Invalid UserEmail"; }
}
your db connection need to connect for this so first connect this
require_once("dbcontroller.php"); $db_handle = new DBController();
hope your connection is ok so this code will check
<?php
$sql = "SELECT anyfiled FROM yourtable WHERE email = " .$_POST['userEmail'];
$select = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($select) > 0) {
$message = "exist";
}
?>
Email Validation:
Apart from checking for common symbols like '#' and alpha-numeric, you must also check for white spaces/tabs in start and most importantly convert the incoming input using htmlspecialchars() as:
function reduceInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Call the reduceInput() function on $_POST['userEmail'] and then use your filter_var() funciton to validate it.
I understand you mean not to pass exploiting strings to database? You don't have to validate these values for that. There is a php function which will pass the strings safely to your database. That's it:
mysqli_real_escape_string($mysqli_object, $_POST['userName']);
But if you'd like to validate your email and username, do this:
if (ctype_alnum($nick)==false) exit(0);// this makes your nick can only contain letters and numbers
$emailB = filter_var($email, FILTER_SANITIZE_EMAIL);//this sanitizes your email
if ((filter_var($emailB, FILTER_VALIDATE_EMAIL)==false) || ($emailB!=$email)) exit(0);//this validates your email

PHP function (adding records) not working correct

I am working on a website which will have a user adding form. The following function is addrecord(). When the admin user is creating a new user, this function adds the rows in the SQL table. But, every time I add a new users, I stucked at the error message "User name/password not added to contact", at the first else statement. When I check the table, the access level and password fields are having the data, but I cannot log in with the hashed password. Anybody could help, what's wrong with this code?
Thanks,
Sixxdog
public function addRecord() {
// Verify the fields
if ($this->_verifyInput()) {
// prepare for the encrypted password
$password = trim($_POST['password1']);
// Get the Database connection
$connection = Database::getConnection();
// Prepare the data
$query = "INSERT INTO contacts(first_name, last_name, position, email, phone)
VALUES ('" . Database::prep($this->first_name) . "',
'" . Database::prep($this->last_name) . "',
'" . Database::prep($this->position) . "',
'" . Database::prep($this->email) . "',
'" . Database::prep($this->phone) . "')";
// Run the MySQL statement
if ($connection->query($query)) { // this inserts the row
// update with the user name and password now that you know the id
$query = "UPDATE contacts
SET user_name = '" . Database::prep($this->user_name) . "',
password = '" . hash_hmac('sha512',
$password . '!hi#HUde9' . mysql_insert_id(),
SITE_KEY) ."',
access = '" . Database::prep($this->access) . "'";
if ($connection->query($query)) { // this updates the row
$return = array('', 'Contact Record successfully added.', '');
// add success message
return $return;
} else {
// send fail message
$return = array('', 'User name/password not added to contact.', '');
return $return;
}
} else {
// send fail message and return to contactmaint
$return = array('contactmaint', 'No Contact Record Added. Unable to create record.', '0');
return $return;
}
} else {
// send fail message and return to contactmaint
$return = array('contactmaint', 'No Contact Record Added. Missing required information
or problem with user name or password.', '0');
return $return;
}
}
There's no WHERE clause in your update statement. Perhaps the user_name column has a unique index on it?

PHP Server-Side Validation of Related Fields

I have a user table with userid and password. I would like all form submissions to be 'verified' by another user by entering userid and password before submission. I have a code that works to verify the userid, but I would like to also verify the password, but obviously linked to the userid. This is NOT a login form, all it does is verify that a users entered userid and password are correct.
The 'verify' fields in my form are called: userid_ver and password_ver.
Any help is very appreciated! Thank you.
$rs = CustomQuery("select userid from user where userid = '"
. db_addslashes($values["userid_ver"]) . "'");
if (db_fetch_array($rs)==false)
{
$message = "UserID is incorrect. Please try again.";
return false;
}
$message="";
return true;
I think you made a mistake should be userid_ver = '...
Anyway if you are asking just to add a checking in your query, then add this at the end of your sql statement, just be sure that the $values["password_ver"] is set:
." AND password_ver = '". db_addslashes($values["password_ver"]) . "'"
Complete:
$rs = CustomQuery("select userid from user where userid = '"
. db_addslashes($values["userid_ver"]) . "' AND password_ver = '". db_addslashes($values["password_ver"]) . "'");
if (db_fetch_array($rs)==false)
{
$message = "UserID is incorrect. Please try again.";
return false;
}
$message="";
return true;

Checkbox that updates dynamically

I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John
Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.

Insert php record from mysql table into a different table

I've been searching for a long time for a solution to what I feel is a very simple problem.
I have a dynamically created page with a video that has a unique id. I also have a form that a user can submit content with. I want the id of the video to be included in the submission to tableA.
This code works great only when $id = 1.
$vidq = "SELECT * FROM tutorials";
$vidresult = mysql_query($vidq);
$vidrow = mysql_fetch_array($vidresult);
//form submission
if($_POST['formname'] == "submit") {
$name = $_POST['name'];
$id = $vidrow['id'];
$errorMessage = "";
if(empty($name)) {
$errorMessage .= "<li>Please enter a valid name</li>";
}
if(empty($errorMessage)) {
$insert = "INSERT INTO tableA (videoid, name) VALUES (".$id.", ".$name.")";
mysql_query($insert);
exit();
}
}
When I change $id to = 1, it posts, but when $id to = $vidrow['id'] it doesn't post.
What am I doing wrong?
Try displaying the mysql error message by using mysql_errno/mysql_error. Eg...
if (!mysql_query($insert))
{
die('MySQL Fail (' . mysql_errno() . ') - ' . mysql_error());
}
mysql_errno() documentation - http://php.net/manual/en/function.mysql-errno.php
Have you tried to print out the contents of $id after $id = $vidrow['id'];? It might reveal why it doesn't work the way you want...
Have you thought about what might happen if a malicious (or just curious) user calls your script with ?name=%27%27%29%3b%20DROP%20TABLE%20tableA%3B?

Categories