AJAX form not inserting values into SQL DB - php

I am trying to incorporate this code to allow me to register a user after their details are given. All details are to be inserted into the database, and then load the new page, all done using AJAX.
To help keep things in context. All pages are loaded within the #main-content div within index.php. They are all loaded via the same function used that you will see in the click.js portion upon ajax success. Register.php is simply one of the pages that loads within this div.
Currently, the form loads properly, and upon submission, the new page loads as per the ajax function. Nothing however is inserted into the database.
Disclaimer: I have not set this up yet to trim for security purposes. This is a matter of function first prior to setting up to protect against SQL injections.
register.php
<script src="js/click.js"></script>
<form action="click.js" method="post">
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" /><br>
<label for="last_name" >Last Name:</label>
<input type="text" id="last_name" name="last_name" /><br>
<label for="username">Username:</label>
<input type="text" id="username" name="username" /><br>
<label for="password">Password:</label>
<input type="text" id="password" name="password" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<button type="submit" id="reg-submit" name="submit">Submit</button>
</form>
click.js
$(document).ready(function(){
$('#reg-submit').click(function() {
var firstName = $('#first_name').val();
var lastName = $('#last_name').val();
var userName = $('#username').val();
var password = $('#password').val();
var email = $('#email').val();
var dataString = 'name1=' + firstName + '&lastname1=' + lastName + '&user1=' + userName + '&password1=' + password + '&email1=' + email;
if (firstName == "" || lastName == "" || userName == "" || password == "" || email == "") {
alert('missing some information');
} else {
$.ajax({
type: "POST",
url: "usersubmit.php",
data: dataString,
cache: false,
success: function(){
$('#main-content').load('php/next-page.php').hide().fadeIn('slow');
}
});
};
return false;
});
});
the DB connection takes place within the users_db.php.
usersubmit.php
<?php
include 'users_db.php';
$first1=$_POST['name1'];
$last1=$_POST['lastname1'];
$username1=$_POST['user1'];
$pass1=$_POST['password1'];
$email01=$_POST['email1'];
$userinfo = $conn->prepare("INSERT INTO registered_users (FirstName, LastName, Username, Password, Email) VALUES ('$first1', '$last1', '$username1'', '$pass1', '$email01')");
$userinfo->execute();
$conn = null;
?>
Much appreciated!
If you see any other problems I may have here outside of the form simply not submitting, feel free to point them out.

The answer is that is not how you prepare statements :)
<?php
include 'users_db.php';
$first1=$_POST['name1'];
$last1=$_POST['lastname1'];
$username1=$_POST['user1'];
$pass1=$_POST['password1'];
$email01=$_POST['email1'];
$userinfo = $conn->prepare("INSERT INTO registered_users (FirstName, LastName, Username, Password, Email) VALUES (?, ?, ?, ?, ?)");
$userinfo->bind_param("sssss",$first1,$last1,$username1,$pass1,$email01);
$userinfo->execute();
// you shoud close the prep statement object
$userinfo->close();
//this is the way to kill the conn
$conn->close();
?>
This is assuming your connection to database works :)

Related

Inserting data into database using AJAX-php using onclick

I am trying ajax method to insert data into the database using php. But only the alert message is working and data is not getting inserted into database
My form:
<div class="contactForm">
<h3>Share your contact Details</h3>
<form id=register>
<div class="form-group">
<input type="text" id="team" class="form-control" placeholder="Enter Team Name">
</div>
<div class="form-group">
<input type="text" id="m1" class="form-control" placeholder="Member#1">
</div>
<div class="form-group">
<input type="text" id="m2" class="form-control" placeholder="Member#2">
</div>
<div class="form-group">
<input type="text" id="m3" class="form-control" placeholder="Member#3">
</div>
<div class="form-group">
<input type="text" id="m4" class="form-control" placeholder="Member#4">
</div>
<div class="form-group">
<input type="text" id="email" class="form-control" placeholder="Enter your Email ID">
</div>
<div class="form-group">
<input type="text" id="number" class="form-control" placeholder="Enter your Mobile No.">
</div>
<div class="form-groud">
<a type="submit" onclick=register() class="btn">Register</a></div>
</form>
</div>
call function:
function register() {
var team = document.getElementById("team").value;
var m1 = document.getElementById("m1").value;
var m2 = document.getElementById("m2").value;
var m3 = document.getElementById("m3").value;
var m4 = document.getElementById("m4").value;
var email = document.getElementById("email").value;
var number = document.getElementById("number").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'team=' + team + '&m1=' + m1 + '&m2=' + m2 + '&m3' + m3 + '&m4' + m4 + '&email' + email + '&number' + number;
if (team == '' || m1 == '' || m2 == '' || m3 == '' || m4 == '' || email == '' || number == '') {
alert("Please Fill All Fields");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "workreg.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
and here is the php:
<?php
// Fetching Values From URL
$team=$_POST['team'];
$m1=$_POST['m1'];
$m2=$_POST['m2'];
$m3=$_POST['m3'];
$m4=$_POST['m4'];
$email=$_POST['m4'];
$number=$_POST['m4'];
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("event", $connection); // Selecting Database
if (isset($_POST['team'])) {
$query = mysql_query("insert into workshop values ('$team', '$m1', '$m2','$m3','$m4','$email','$number')"); //Insert Query
echo "Form Submitted succesfully";
}
mysql_close($connection); // Connection Closed
?>
whenever i am clicking register its is just showing alert message but i checked the database no value is getting inserted
Actually you are only checking for post variable test is present or not . You are not checking for your successful database query execution . in your current code check after $query
if(!$query){
echo "Form Submitted succesfully"
} else {
die('Invalid query: ' . mysql_error()); // show the error
}
mysql is deprecated functions so i am using mysqli , it is also better for you to use this. Never trust user's input so i am also using prepare statement. You should always looking for updated videos & articles.
$connection = mysqli_connect("localhost", "root", "","event"); // Establishing Connection with Server..
if (isset($_POST['team'])) {
$query = "insert into workshop values (?, ?, ?,?,?,?,?)"; //Never trust user's input so use prepare
$stmt = mysqli_prepare($connection ,$query) ;
mysqli_stmt_bind_param($stmt,'ssssssi',$team,$m1,$m2,$m3,$m4,$email,$number) ;
mysqli_stmt_execute($stmt);
if( mysqli_stmt_affected_rows($stmt) === 1 ) { //it will be int 1 if one row is inserted
echo "Form Submitted succesfully" ;
}else {
echo mysqli_error($connection)
}
}
mysqli_close($connection); // Connection Closed
some sources for future
How can I prevent SQL injection in PHP?
https://phpdelusions.net/pdo (it's about PDO but you will get idea.)
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
The Content-Type is missing from your post request. I worked only with PostgreSQL but Content-Type was kinda necessary for the post requests to work properly in my case, maybe you should check that.
Also check if you set to autocommit to your database at the connection or the data wont be added to the database.
$('#register').submit(event => {
event.preventDefault();
let team = $('#team').val();
let m1 = $('#m1').val();
let m2 = $('#m2').val();
let m3 = $('#m3').val();
let m4 = $('#m4').val();
let email = $('#email').val();
let number = $('#number').val();
$.ajax({
url: "workreg.php",
method: "POST",
data: { team, m1, m2, m3, m4, email, number }
.done(data => {
console.log(data)
})
.fail(err => console.error(err))
})
})

Random Queries Failing with MySql

I hope this question is not too broad but it is not with a specific piece of code. Basically at random times and on random queries I have failures in my code. Most of the time it seems like it is on my INSERT calls. UPDATE and DELETE still work fine, but INSERT will fail across the entire page for several hours at a time before mysteriously working again. The page is only being used and tested by myself currently.
One of the sample queries.
PHP
session_start();
$poster = $_SESSION['login_user'];
$conn = new PDO("mysql:host=localhost;dbname=spectrum",'root', '1234abcd');
$u = $_POST['user'];
$p = md5($_POST['pass']);
$e = $_POST['email'];
$fn = $_POST['first_name'];
$ln = $_POST['last_name'];
$t = $_POST['type'];
$sql = "INSERT INTO users(id, user, pass, email, type, first_name, last_name, poster) VALUES ('', :user, :pass, :email, :type, :first, :last, :poster)";
$q = $conn->prepare($sql);
$q->bindParam(":user", $u);
$q->bindParam(":email", $e);
$q->bindParam(":pass", $p);
$q->bindParam(":type", $t);
$q->bindParam(":first", $fn);
$q->bindParam(":last", $ln);
$q->bindParam(":poster", $poster);
$q->execute();
echo json_encode('User has been added.');
This is done through an Ajax call.
JQuery
var request;
if (request) {
request.abort();
}
var $form = f;
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: site + "/backend/formup.inc.php",
type: "post",
dataType: 'json',
data: serializedData
});
request.done(function (data){
if(data.location){
window.location.replace(data.location);
}
else{
alert(data);
location.reload(false);
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
"The following error occured: "+
textStatus, errorThrown
);
});
request.always(function (data) {
if(!data.tvar){
$inputs.prop("disabled", false);
}
});
Here is the HTML.
<form class="hidden" method="POST">
<input type="text" name="user" placeholder="Username" required/>
<input type="email" name="email" placeholder="Email" required/>
<input type="password" name="pass" placeholder="Password" required/>
<input type="text" name="first_name" placeholder="First Name" required/>
<input type="text" name="last_name" placeholder="Last Name" required/>
<input type="radio" name="type" value="0">Owner
<input type="radio" name="type" value="1">Employee
<input type="radio" name="type" value="2">Artist
<input type="radio" name="type" value="3">Venue
<input type="radio" name="type" value="4">Fan<br />
<input type="hidden" name="fname" value="add_user" />
<input type="submit" class="button" value="Add" />
</form>
Also I apologize if some formatting may be off with my questions. First time posting and getting used to the site.

Ajax succes working but not sending data to mysql database on.click function and not working completely with on.submit

My problem is that when I click the submit button while I have a on.('click') on top of my jQuery ajax, success works but doesn't send information to my database. Otherwise when I have on.('submit') on top of my jQuery the ajax doesn't work but PHP does.
Here is the code of my form.
<div id="seccion_registro">
<div id="login_error">Campo no valido!</div>
<div id="registro_succes"></div>
<form id="form2" name="form2" action="usuario.php" method="POST">
<label for="nombre">Nombre</label>
<input id="nombre"type="text" class="text" size="20" name="nombre">
<label for="usuario">Usuario</label>
<input id="password1" type="text" class="text" size="20" name="usuario">
<label for="contrasena">Contraseña</label>
<input id="password1" type="password" class="text" size="20" name="contrasena">
<label for="confirmar">Confirmar contraseña</label>
<input id="password2" type="password" class="text" size="20" name="confirmar">
<label for="email">Email</label>
<input type="text" class= "text" size="20" name="email">
<div>
<input type="submit" class="boton1" value="Regístrate" size="56">
</div>
</form>
This is my jquery ajax function, i use a fancybox to display the form and a succes or error response.
$(document).ready(function(){
$('.boton1').on('click', function(e){
e.preventDefault();
var name = $('#nombre').val();
var password1 = $('#password1').val();
var password2 = $('#password2').val();
var errors = '';
if(name.length < 5 || name == ''){
errors += '<p>tsads</p>';
}
if(errors != ''){
$("#login_error").show();
$.fancybox.resize();
//$("#login_succes").hide();
} else {
var datos = $('#form2').serialize();
$.ajax({
url:'Usuario.php',
data:'datos',
type:'POST',
beforeSend: function(){
$('#seccion_registro').html('<div id="carga" style="margin:0 auto;width:auto;background-position:center center;"></div>');
},
success: function(){
$('#seccion_registro').html('<p class="text_enhorabuena">Enhorabuena, has sido registrado!</p>');
$("#registro_succes").show();
$.fancybox.resize();
}
});
}
});
And finally this is my PHP script.
<?php
include 'conexion.php';
$_POST['nombre'];
$_POST['usuario'];
$_POST['contrasena'];
$_POST['email'];
$consulta = "INSERT INTO usuario (Usuario, password, email, nombre ) VALUES ('".$_POST['usuario']."',
'".$_POST['contrasena']."', '".$_POST['email']."', '".$_POST['nombre']."')";
if (!mysqli_query($conexion,$consulta))
{
die('Error: ' . mysqli_error($conexion));
}
else{
//Do stuff
};
mysqli_close($conexion);
?>
Sending Requests
Take a look at this:
<form id="form2" name="form2" action="usuario.php" method="POST">
With this you are telling our browsers that when the user clicks the submit button send all the form variables to usuario.php. And you have a script that does exactly the same.
So you are sending the form data with two ways: HTML and Jquery.
I suggest you to use only one way to send data to usuarios.php, and maybe things get a little clearer. For instance, change the form tag to this:
<form id="form2" name="form2">
No method, and no action, because that stuff jQuery will take care of.
And then check if everything works.
Jquery
Change the $('.boton1').on('click', function(e){
For $('#form2').on('submit', function(e){
Also check the things you are sending
Look at your Ajax request:
$.ajax({
url:'Usuario.php',
data:'datos',
I think it should be like this:
$.ajax({
url:'Usuario.php',
data:datos,
(Check the datos variable)
Mysql Injection
If everything went OK, next step is to prevent mysql injection. I see you are using mysqli, but you are not using prepared statements! So there is a possibility you are open to mysql injection attacks.
Change to prepared statements:
/* crear una sentencia preparada */
$consulta = "INSERT INTO usuario (Usuario, password, email, nombre ) VALUES ('?','?', '?', '?')";
if ($stmt = mysqli_prepare($link, $consulta)) {
/* ligar parámetros para marcadores */
mysqli_stmt_bind_param($stmt, "ssss", $_POST['usuario'],$_POST['contrasena'],$_POST['email'],$_POST['nombre']);
/* ejecutar la consulta */
mysqli_stmt_execute($stmt);
}
To view more information about prepared statements: http://es1.php.net/manual/en/mysqli.prepare.php

jQuery/ajax/php return value

I have a registration form that on submit, validates passwords and domain names that match respectively. If true, I am trying to then check that the domain name does not exist in the DB via an ajax request.
<div class="grid-6">
<p>
<label for="First Name">First Name:</label>
<input type="text" name="first_name" placeholder="James" required value="">
<label for="Last Name" name="lastname">Last Name:</label>
<input type="text" name="last_name" placeholder="Brown" required value="">
<label for="email">Email:</label>
<input type="email" name="email" placeholder="email#email.com" required value="">
<label for="Preferred Password">Preferred Password:</label>
<input id="og_password" type="password" name="password" required value="">
<label for="Confirm Password">Confirm Password</label>
<input id="confirm_password" type="password" name="password_confirm" required value="">
</p>
</div><!-- /grid-6-->
<div class="grid-6">
<p>
<label for="Domain Name">Domain Name <span class="italic red">(lowercase letters and numbers only - no spaces):</span></label>
<input id="domain_name_a" type="text" name="domain_name_a" placeholder="mystudioname" required value="">
<label for="Domain Name">Confirm Domain Name:</label>
<input id="domain_name_b" type="text" name="domain_name_b" placeholder="mystudioname" required value="">
</p>
</div>
JS
unction passwordMatch() {
var pass1 = $('#og_password').val();
var pass2 = $('#confirm_password').val();
var domain1 = $('#domain_name_a').val();
var domain2 = $('#domain_name_b').val();
var error = true;
if(pass1 != pass2){
alert("Your passwords do not match!");
return false; // cancel form submission if passwords don't match
}
if(domain1 != domain2){
alert("Your domain names do not match!");
return false;
}
//no errors check DB for domain exits
checkDomain(domain1);
}
function checkDomain(domain) {
alert(domain);//testing only
$.ajax({
type:"POST",
url: "/actions/domain.php",
data: {
domain:domain
}
success: function(result) {
if(result = false) {
alert(result);
} else {
alert(result);
}
}
});
}
Things run well through the alert(domain), which is returning the correct value. The problem is somewhere in the domain.php file, the return, or just plain incorrect use of the .ajax. Here is the php
PHP
<?php
require_once("../includes/connection.php");
$domainName = $_POST['domain'];
$sql = "SELECT domain_name
FROM user
WHERE domain_name = '{$domainName}'
";
$run = mysqli_query($mysqli, $sql);
$result = mysqli_fetch_assoc($run);
echo $result['domain_name'];
?>
Any help on where I have gone wrong on this would bea appreciated.
Thanks!
Looks like you are missing a comma between the data and success function in your ajax Request.
data: {
domain:domain
} , < -- Missing comma here
success: function(result) {
If that was a direct copy of your code - you're missing a comma in the ajax call after data: {}, <- right there.
Also, remove the if...else from the success statement, because it's not done right as well (you're testing a value by using ONE equal sign, and all that does is just declare the value you're trying to test against). Just try: success: function(result) { console.log(result); alert(result); } and see what you get.
For some odd reason jQuery does not recognise the file by a shortened url.
The solution is to type the whole url -> not only smtg/smtg.php but http://www.domain.com/smtg/smtg.php.
Also, you could try to send the data in json format by adding the following line of code into your ajax call: "dataType: 'json'," and then outputting from a php file like this: "echo json_encode("return value");"

Inserting values into database with php, ajax and jQuery

I'm struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...
sign_up.php
<?php
include 'connect.php';
include 'header.php';
echo '<h2>Register</h2>';
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<br/>';
echo '
<div class="container">
<form id="submit" method="post" action="">
<fieldset>
<legend> Enter Information </legend>
<br/>
<label for="user_name">Your username: </label>
<br/>
<input id="user_name" class="text" name="user_name" size="20" type="text">
<br/>
<br/>
<label for="user_pass">Your password: </label>
<br/>
<input id="user_pass" class="text" name="user_pass" size="20" type="password">
<br/>
<br/>
<label for="user_pass_check">Confirm password: </label>
<br/>
<input id="user_pass_check" class="text" name="user_pass_check" size="20" type="password">
<br/>
<br/>
<label for="user_email">Email: </label>
<br/>
<input id="user_email" class="text" name="user_email" size="20" type="email">
<br/>
<br/>
<button class="button positive" type="submit"> <img src="like.png" alt=""> Register </button>
</fieldset>
</form>
<div class="success" style="display: none;"> You are now a registered user!</div>
</div>';
}
else {
$errors = array();
//Checks the errors
if(isset($_POST['user_name']) == NULL)
{
//if the user name is larger than 30 characters
$errors[] = 'Please enter your username.';
}
//Checks the password
if(isset($_POST['user_pass']) == NULL)
{
$errors[] = 'Please enter your password.';
}
else
{
if($_POST['user_pass'] != $_POST['user_pass_check'])
{
$errors[] = 'The two passwords did not match.';
}
}
if(!empty($errors)) //Checks for empty fields
{
echo 'Please check that all the fields are filled in.<br /><br />';
echo '<ul>';
foreach($errors as $key => $value) //walk through the array so all the errors get displayed
{
echo '<li>' . $value . '</li>'; //this generates a list with errors
}
echo '</ul>';
}
}
?>
in my header.php (which I include in every page) I included addMembers.js
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var user_name = $('#user_name').val();
var user_email = $('#user_email').val();
var user_pass= $('#user_pass').val();
//$user_name = $('#user_name').val();
//$user_email = $('#user_email').val();
//$password = $('#password').val();
alert(user_name);
$.ajax({
type: "POST",
url: "ajax.php",
data: "user_name="+ user_name +"&user_email="+ user_email +"$user_pass=" + user_pass,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
//alert("ji");
return false;
});
});
and then my ajax.php that gets the data and must insert it into the database but it doesn't! :(
<?php
include 'connect.php';
include 'header.php';
// CLIENT INFORMATION
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
mysql_query("INSERT INTO
users(`user_name`, `user_pass`, `user_email` , `user_date` , `user_level`)
VALUES('$user_name', '$user_pass', '$user_email', NOW() , 0)" OR trigger_error(mysql_error()));
?>
PLEASE help...
Thanks a lot!
Joe
There are a bit of things not right here:
html:
Give a type="submit" to your button:
<button type="submit" class="...>...</button>
jQuery:
Don't use attr() to get a form value, but use val(). Also, note how you built your query string. You might also want to use serialize(), which shortens your code a bit:
$("form#submit").submit(function() {
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
success: function(){
$(this).hide();
$('div.success').fadeIn();
}
});
return false;
});
PHP:
You didn't show your ajax.php, what is it doing?
Why do you make a check in sign_up.php, if you're calling ajax?
Also, this piece of code:
if(!ctype_alnum($_POST['user_name']))
{
$errors[] = 'That user name is allready taken.';
}
is misleading, ctype_alnum() does check if username has only alphabetical characters or numbers, what's this thing about a username being already taken?
Mysql:
you dint' provide your INSERT query, so noone can tell if that's failing too or not
UPDATE:
Your query has more columns than values.
Also, what is htmlspecialchars() good to here? to avoid SQL injections you need to use mysql_real_escape_string(). Escaping html before entering the database is useless
Make sure you have an open connection when calling mysql_real_escape_string().
Should be:
mysql_query("INSERT INTO users
(`user_name`,`user_pass`,`user_email`,`user_date`,`user_level`)
VALUES ('$user_name','$password','$user_email','missingvalue','missingvalue')"
) OR trigger_error(mysql_error());
$.ajax({
type: "POST",
url: "ajax.php",
data: "user_name="+ user_name + "&user_email=" + user_email + "&password=" + password,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
show the ajax.php, besides earlyer comments like : ' $('#user_name').val();','ampersant before user_email'... seems ok...

Categories