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))
})
})
Related
I am really new to AJAX/jQuery and PHP, and im trying to work on a little project that writes your daily weight to a Db which then is displayed later on with graphs etc.
I would like when the user submits the form for his or her weight that it displays a pop up message but for whatever reason, the AJAX/Jquery script doesn't seem to be doing anything with the php file therefore no info gets added into the database.
Here is the HTML Form: (index.html)
<form id="ajax-form" method="post" action="connection.php">
<div class="columns field">
<div class="column control is-half is-offset-one-quarter">
<input
class="input"
id="weight"
name="weight"
type="text"
placeholder="Enter your weight for the day"
/>
</div>
</div>
<div class="center-test">
<div class="field">
<div class="control">
<span class="select">
<select name="person">
<option value="Ayush">Ayush</option>
<option value="Sheri">Sheri</option>
</select>
</span>
</div>
</div>
</div>
<input type="date" name="weightdate" id="weightdate" />
<div class="field column is-half is-offset-one-quarter">
<button
type="submit"
id="submit"
name="submit"
class="button is-primary"
>
Submit
</button>
</div>
</form>
<div id="error_message" class="text-danger"></div>
<div id="success_message" class="text-success"></div>
AJAX/jQuery: (inside index.html )
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
var weight = $("#weight").val();
var person = $("#person").val(); // You miss this
var weightdate = $("#weightdate").val(); // You miss this
if (weight == "" || person == "" || weightdate == "") {
$("#error_message").html("All Fields are required");
} else {
$("#error_message").html("");
$.ajax({
url: "connection.php",
method: "POST",
data: {
weight: weight,
person: person, // Add this
weightdate: weightdate, // Add this
},
success: function (data) {
$("form").trigger("reset");
$("#success_message").fadeIn().html("data");
setTimeout(function () {
$("#success_message").fadeOut("Slow");
}, 2000);
},
});
}
});
});
PHP: (connection.php)
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
include_once 'dbconnect/db_info.php';
$weight = $_POST['weight'];
$person = $_POST['person'];
$date = $_POST['weightdate'];
$formatDate = date("d/m/y", strtotime($date));
//echo $formatDate;
if(date("m", strtotime($date)) == date("01")) {
$sql = "INSERT INTO WeightTracker (person, kg, weight_date, date_month) VALUES ('$person', '$weight', '$formatDate', 'January');";
#$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
}
elseif(date("m", strtotime($date)) == date("04")) {
//echo working;
$sql = "INSERT INTO WeightTracker (person, kg, weight_date, date_month) VALUES ('$person', '$weight', '$formatDate', 'April');";
#$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
}
else {
$sql = "INSERT INTO WeightTracker (person, kg, weight_date) VALUES ('$person', '$weight', '$date');";
#$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
}
Does anyone have any ideas? When I remove the AJAX/jQuery code, the form successfully submits and the connection.php writes to the database with no issues.
Most of the problem was resolved in comments. The problem (as described in the comments) was a PHP error Undefined index on this line:
$person = $_POST['person'];
As I mentioned in an earlier comment: your person input is missing the expected person ID. That means this Javascript:
var person = $("#person").val();
Is actually undefined, so there is no person field POSTed to your PHP, so when you try to use it as $_POST['person'], you'll get an error.
To fix that, just add the id your Javascript is using to find the person:
<select name="person" id="person">
The data you give for the POST request is just weight, there is no person and weightdate data.
var weight = $("#weight").val();
var person = $("#person").val(); // You miss this
var weightdate = $("#weightdate").val(); // You miss this
if (weight == "" || person == "" || weightdate == "") {
$("#error_message").html("All Fields are required");
} else {
// Your code :)
}
And the data,
$.ajax({
url: "connection.php",
method: "POST",
data: {
weight: weight,
person: person, // Add this
weightdate: weightdate // Add this
},
success: function(data) {
$("form").trigger("reset");
$("#success_message")
.fadeIn()
.html("data");
setTimeout(function() {
$("#success_message").fadeOut("Slow");
}, 2000);
}
});
Your Problem lies here.
include_once 'dbconnect/db_info.php';
Change it to something like
realpath('__DIR__'.'/dbconnect/db_info.php');
Hopefully it will solve your problem.
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 :)
I've put together an ajax style form that has a simple animated validation through jQuery. When everything checks out, it posts the content to my database. Or at least, that's the idea. Right now it logs an error at the very end of the function rather than inserting the information.
It consists of:
db.php, connects to database
scripts.js (+jQuery), form validation
index.php, the form and such
insert.php, inserts post data into the database
db.php
<?$con = mysql_connect("localhost","db_name","db_pass");
if (!$con){die('Could not connect: ' . mysql_error());}
?>
scripts.js
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
// Tell console that it's started the validation
console.log("Begin Validation");
// Dump post data into variables
var alert = false;
var first = $("#firstname").val();
var last = $("#lastname").val();
var email = $("#email").val();
var phone = $("#phone").val();
var dropdown = $("#dropdown").val();
// Check first name field
if (first.length === 0) {
var alert = true;
$("#firstname").addClass("error");
} else {
$("#firstname").removeClass("error");
}
// Check last name field
if (last.length === 0) {
var alert = true;
$("#lastname").addClass("error");
} else {
$("#lastname").removeClass("error");
}
// Check email field
if (email.length < 7 || email.indexOf("#") == "-1" || email.indexOf("#.") != -1 || email.indexOf("-.") != -1 || email.indexOf("_.") != -1 || email.indexOf("..") != -1 || email.indexOf("._") != -1 || email.indexOf(".-") != -1 || email.indexOf(".#") != -1 || email.indexOf("#-") != -1 || email.indexOf("#_") != -1 || email.indexOf("#") == -1 || email.indexOf(".") == -1) {
var alert = true;
$("#email").addClass("error");
} else {
$("#email").removeClass("error");
}
// Check phone field
if (phone.length === 0) {
var alert = true;
$("#phone").addClass("error");
} else {
$("#phone").removeClass("error");
}
// Check dropdown field
if ($("#dropdown").val() === 0) {
var alert = true;
$("#dropdown").addClass("error");
} else {
$("#dropdown").removeClass("error");
}
// If anything returned an error, display the alert dialog
if (alert === true) {
$(".formcheck").slideDown(500);
}
// If no issues were found, disable submit button and proceed to data insertion
if (alert === false) {
$(".formcheck").slideUp(500);
$("#submit").attr({
disabled: "true",
value: "Sending Info..."
});
console.log("Finish validation, move on to insert.php");
// Insert the data into the database via php file, echo success message to form
$.post("insert.php", $("#form").serialize(), function (e) {
console.log("Post data to insert.php");
if (e == "sent") {
console.log("Hide submit button and display success message");
$("#submit").slideUp(500);
$(".formfail").slideUp(500);
console.log("remove submit and errors");
$(".formsuccess").slideDown(500);
console.log("message sent successfully");
} else {
console.log("something went wrong");
$("#submit").removeAttr("disabled").attr("value", "Submit");
}
});
}
});
});
index.php
<? include 'db.php'; ?>
<!doctype html>
<head>
<!-- meta info and such goes here -->
<link rel='stylesheet' href='theme.css' type='text/css' media='all' />
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript' src='scripts.js'></script>
</head>
<body>
<form action='#submit' method='post' id='form'>
<div class='formsuccess'>Your entry has been submitted; Thank you.</div>
<div class='formerror'>There was a problem submitting the entry.</div>
<div class='formcheck'>Please check the form, something's missing.</div>
<div class='formfail'>There was a problem contacting the server.</div>
<input type="text" name="firstname" id="firstname" tabindex="1" placeholder="First Name">
<input type="text" name="lastname" id="lastname" tabindex="2" placeholder="Last Name">
<input type="text" name="email" id="email" tabindex="3" placeholder="Email">
<input style="display:none" id="email2" name="email2" type="text">
<input type="text" name="phone" id="phone" tabindex="4" placeholder="Phone">
<select name="dropdown" id="dropdown" tabindex="5">
<option value="0">Please select an option...</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input id="submit" name="submit" type="button" value="Submit" tabindex="6"/>
</body>
</html>
insert.php
<?$con = mysql_connect("localhost","db_name","db_pass");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_select_db("db_name", $con);
//This bit makes the data input secure (preventing things like drop_tables, etc...)
function sanitize($input){
switch(gettype($input)){
case 'object':
foreach($input as $key => $variable){
$input->$key = sanitize($variable);
}
break;
case 'array':
foreach($input as $key => $variable){
$input[$key] = sanitize($variable);
}
break;
case 'string':
//clean out extra sql queries
//remove poison null byte
//remove blank space at beginning and end of string
$input = mysql_real_escape_string(trim(htmlentities(str_replace(chr(0),'',$input),ENT_QUOTES)));
break;
}
return $input;
}
//create an alias for "clean" version of our variable.
$post = sanitize($_POST);
//now use $post['firstname'] instead of $_POST['firstname'], $post has been cleaned.
//INSERT POST DATA INTO TABLES
$sql="INSERT INTO 'db_name'.'table_name' ('firstname', 'lastname', 'phone', 'email', 'dropdown')
VALUES ('".$post['firstname']."','".$post['lastname']."','".$post['phone']."','".$post['email']."','".$post['dropdown']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo 'sent';
mysql_close($con);
?>
That's all of it (of course, I stripped out branded bits). As it is now, it logs "something went wrong"
Which means it passes the JavaScript validation and successfully reaches the last function. unfortunately it isn't able to insert the information into the database and defaults to the else statement, which doesn't return the "sent" message to the script file -- thus no success.
I've been tinkering with this thing for hours and can't figure out why it's failing.
You need to use backticks, not quotes for table/column names.
$sql="INSERT INTO `db_name`.`table_name` (`firstname`, `lastname`, `phone`, `email`, `dropdown`)
VALUES ('".$post['firstname']."','".$post['lastname']."','".$post['phone']."','".$post['email']."','".$post['dropdown']."')"
Or none, just:
$sql="INSERT INTO table_name (firstname, lastname, phone, email, dropdown)
VALUES ('".$post['firstname']."','".$post['lastname']."','".$post['phone']."','".$post['email']."','".$post['dropdown']."')"
I also would trash your sanitize() function and all the mysql_* functions and revert to parametrized queries instead. Look into PDO, something like:
$db = new PDO('mysql:dbname=db_name;host=127.0.0.1;charset=utf8', 'db_name', 'db_pass');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $db->prepare('INSERT INTO table (firstname, lastname, phone, email, dropdown) VALUES (:firstname, :lastname, :phone, :email, :dropdown)';
$stmt->execute(array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname'],
'phone' => $_POST['phone'], 'email' => $_POST['email'], 'dropdown' => $_POST['dropdown']));
mysql_real_escape_string is not a good way to escape data instead you should use PDO, prepared statements. In PDO you do not have to escape data. PDO will take care of it. Use bindParam to insert parameterized data in db.
I'm having an issue with AJAX/PHP form submission.
My ajax is as follows:
<script type="text/javascript">
$('#loginForm').submit(function() {
checkLogin();
});
function checkLogin()
{
$.ajax({
url: "login.php",
type: "POST",
data: {
username: $("#username").val(),
password: $("#password").val()
},
success: function(response)
{
if(response == 'true')
{
window.location.replace("main.html");
}
else
{
$("#errorMessage").html(response);
}
}
});
}
</script>
My form:
<form id="loginForm" data-ajax="false">
<label id="errorMessage"></label>
<div data-role="fieldcontain">
<label for="username">Username:</label>
<input id="username" type="text" placeholder="Username" />
</div><!-- End Contained Fields -->
<div data-role="fieldcontain">
<label for="password">Password:</label>
<input id="password" type="password" placeholder="Password" />
</div><!-- End Contained Fields -->
<div data-role="fieldcontain">
<input type="submit" id="login" value="Login" />
</div><!-- End Contained Fields -->
</form><!-- End Form -->
And then my login.php script:
<?php
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
if(!empty($username) && !empty($password))
{
$db = new PDO('mysql:host=localhost;dbname=mobile;charset=utf8', 'root', 'password');
try {
$stmt = $db->query("SELECT COUNT(*) FROM users WHERE username='$username' and password='$password'");
if(intval($stmt->fetchColumn()) === 1)
{
echo 'true';
}
else
{
echo 'false';
}
} catch(PDOException $ex) {
echo "An error has occured!";
}
}
?>
I originally had programmed my whole JQuery Mobile application using just raw php, but recently found out that I must use AJAX and Html to be able to port it to IOS and Android using PhoneGap.
I'm rather new to using ajax and have read as many articles that I could/topics here to try to get it to work. Unsure if I'm having a syntax issue or just not handling it correctly.
My local machine is loading a mysql server (database name is mobile, table I'm trying to load is users). I know that part is all correct because it works fine with php.
Could someone explain my issue? Thank you.
this:
$("$errorMessage").html("Attempting to login...");
should be:
$("#errorMessage").html("Attempting to login...");
or, if you have previously defined a $errorMessage variable like this:
var $errorMessage = $("#errorMessage");
it should be :
$errorMessage.html("Attempting to login...");
EDIT:
PHP manual : "For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement....."
you can try:
....
$stmt = $db->query("SELECT COUNT(*) FROM users WHERE username='$username' and password='$password'");
if (intval($stmt->fetchColumn()) === 1) { //make sure it's not a string
echo 'true';
$_SESSION['username'] = $username;
// OR perform another SELECT query to retrieve the data
}
else
{
echo 'false';
}
.....
The problem is this line:
window.location.replace('main.html');
Change it to:
window.location.href='main.html';
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...