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...
Related
as a practice i made a log in form and linked it with a MySQL database and am trying to show a toastr according to to the result that is if the username and password are correct or not so when the input fields are empty it's showing the error toaster but when i add any thing in the fields it always shows the success toastr i don't know how to fix that
here is my html code
<form class="sing_in_form " method="POST" action="#">
<input id="email" type="text" name="username" placeholder="Email">
<input id="password" type="text" name="password" placeholder="password">
<!--log in button-->
<button type="submit" id="btn" name="submit " value="LOGIN" class="btn-login">Sign In</button>
<p class="sign_up">Don't have account? Sign up</p>
</form>
php
if(isset($_POST['username'])){ //username from the form
$uname=$_POST['username'];//username from the form
$pass_word=$_POST['password'];
$sql="SELECT * FROM `loginform2` WHERE user='".$uname."' And Pass='".$pass_word."' limit 1";
$result= $con->query($sql);
}
and my js code
$(document).ready(function(){
$("#btn").click(function(){
var name = $("#email").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username='+ name + '&password='+ password;
if(name==''||password=='')
{
toastr.error("fill the feilds");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "login(2).php",
data: dataString,
cache: false,
success: function(){
toastr.success("logged in");
}
});
}
return false;
});
});
Do something like this.
Put if(mysqli_num_rows($result) ===1 {echo 1}; after $result= $con->query($sql);
And then edit your ajax request as
success: function(data){
if(data ==1){
toastr.success("logged in");
}else{
//error message goes here
}
}
I'm not able to connect with database using jquery ajax.
The below is the login1.html page
<form method='POST'>
<div class="username">
<input type="text" id='name' name="name" class="form-control" placeholder="Enter your username">
<i class="glyphicon glyphicon-user"></i>
</div>
<div class="password">
<input type="password" id='password' name='password' class="form-control" placeholder="Enter your password">
<i class="glyphicon glyphicon-lock"></i>
</div>
<div id="error"></div>
<div class="custom-radio-checkbox">
<input tabindex="1" type="checkbox" class="bluecheckradios">
<label>Remember me</label>
</div>
<script>
$(document).ready(function(){
$('.bluecheckradios').iCheck({
checkboxClass: 'icheckbox_flat-blue',
radioClass: 'iradio_flat-blue',
increaseArea: '20%' // optional
});
});
</script>
<input type="submit" class="btn btn-primary style2" name='submit' id="submit" value="Sign In">
</form>
The form value is transferred through jquery ajax
<script>
$(document).ready(function(){
// jQuery methods go here...
$('#submit').click(function(){
var username = $('#name').val();
var pass = $('#password').val();
var datastring = {username:username,pass:pass};
if($.trim(username).length>0 && $.trim(pass).length>0){
$.ajax({
type: "POST",
url : "process/login.php",
data : datastring,
cache: false,
beforeSend : function(){
$("#submit").val('Connectiing...');
},
success:function(data){
if(data){
window.location.href('http://www.google.com');
}
else{
$('#loginone').shake();
$('#submit').val('Login')
$("#error").html("<span style='color:red'>Error:</span>Invalid Username or Password");
}
}
});
}
return false;
});
});
</script>
** This is the data connection page process/login.php**
<?php
include_once('config.php');
if(isset($_POST['submit'])){
$username = $_POST['username'];
$pass = $_POST['pass'];
$sql = "select id from login where login_name = '".$username."' and login_password = '".$pass."' ";
$result = $conn->query($sql);
if($result->num_row > 0){
echo "connected";
}
}//EOF SUBMIT
?>
When ever i pass the correct credentials i get an error for wrong username and password.
You are not sending the value of the submit over the ajax change your if to
if(isset($_POST['username']) && isset($_POST['pass']) ){
or add the value to the ajax:
datastring = {username:username,pass:pass,submit:"true"};
You are getting wrong username and password because your PHP not returning anything in ajax success.
Whats wrong here:
You are sending username and password in ajax request but checking by using submit input which is wrong because submit is not the part of ajax data.
You can also check what are you getting in ajax request in php as:
print_r($_POST);
Here, you can solve the problem as:
if(count($_POST) > 0) // check $_POST array > 0 or not..
instead of:
if(isset($_POST['submit'])){ // submit not available in $_POST
The object data you are sending through Ajax to the PHP script does not have a key called "submit" and hence this part of the code will fail
if(isset($_POST['submit'])){
Just remove that if statement and you will be fine... You can equally check whether you have data within the $_POST super global like devpro suggested in the comment below your question or just check for only the fields you sent within the $_POST variable.
I am trying to create on-page login.
without ajax it works very well. Here is my login.php;
if($_POST)
{
$username =$_POST["username"];
$password =$_POST["password"];
$query = $handler->query("SELECT * FROM members WHERE username='$username' && password='$password'",PDO::FETCH_ASSOC);
if ( $say = $query -> rowCount() ){
if( $say > 0 ){
session_start();
$_SESSION['session']=true;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
echo "ok";
}else{
echo "Couldn't login.";
}
}else{
echo "Wrong username or password.";
}
}
Anyway, here is my java script code;
$(function(){
$("#loginbutton").click(function(){
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != ""){
$.ajax("login.php",{
type : "POST",
data : "username="+username+"&password="+password,
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
}
});
});
Even though I put correct login information (when I get "ok" response from login.php, it always outputs $("#fail").fadeIn(); . instead of $("#message").html(data); I couldn't figure out where I am mistaken.
and here is login form:
<div id="login">
<form action="" onsubmit="return false;" method="post">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"><br>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off"><br>
<input class="btn btn-success" type="submit" id="loginbutton" value="Login">
</form>
<div id="message"> </div>
<div id="fail" style="display: none;">failed.</div>
</div>
You are using type as post, but sending parameters as get.Change your ajax like this,
$.ajax("login.php",{
type : "POST",
data : {username:username,password:password},// only this line is changed.
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
Here is a quick example of using post with JQuery AJAX.
$(document).ready(function(){
$.post("login.php", {username:username, password:password}, function(data){
if(data == 'ok'){
$("#message").html(data);
}else{
alert(data);//alert the data you receive. It alerts you if there is any error in php file.
$("#fail").fadeIn();
}
});
});
Hope that was helpful!
Firstly, debug your code like this:
1) On button click you will put alert function inside javascript code. if it is working then move second step.
2) use alert function to print username and password if it comes inside your javascript code and correct as you put into input fields then move third step.
3) use serialize method in javascript.
I hope its help you to get your solution.
Here is my html
<div id="stylized" class="myform">
<form action="index.php" method="post" class="formPadd">
<div align="right">
<fieldset class="FloatLeft">
</fieldset>
<fieldset class="FloatRight" style="padding-right:14px;">
<div style="height:40px; line-height:30px; text-align:center;">
<label>Username:</label><br>
<input class="inputbox" type="text" style="text-align:center; padding-right:14px;" name="uname" value maxlength="50">
</div><br><br>
<div style="height:30px; line-height:30px; text-align:center;">
<label align="center">Password:</label>
<input class="inputbox" type="password" name="pass" style="text-align:center; padding-right:14px;" value maxlength="50"><br><br>
</div><br>
<div>
<button id="login" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">Login</span>
</button>
</div>
</fieldset>
</div>
</form>
</div>
</div>
and heres my php
<?PHP
include("db.classes.php");
$g = new DB();
$g->connection();
if($_POST)
{
$un = $g->clean($_POST["username"]);
$pw = $g->clean($_POST["password"]);
$g->login($un, $pw);
}
$g->close();
?>
and here's my db.classes
ublic function login($un, $pw)
{
$result = mysql_query("select username, password from admin where username='$un' and password='$pw'");
$data = $this->getResults($result);
$uName = $data["username"];
$password = $data["password"];
if($uName === $un && $password === $pw)
{
echo ('Correct');
}
else
{
echo 'Incorrect username/password';
}
}
And here's my ajax request
$( "#login" ).button().click(function( event ) {
event.preventDefault();
var un = $("input[name=uname]").val();
var pw = $("input[name=pass]").val();
var dataString = 'username='+ un + '&password='+ pw;
$.ajax({
type: "POST",
url: "processLogin.php",
data: dataString,
success: function(){
if (data === 'Login') {
window.location.replace('list.php');
}
else {
alert('Invalid Credentials');
}
}
});
});
I have already checked if my sql staments if they are to blame but they are fine. I think my problem is somewhere in the ajax request but i can't seem to point it out.
You need to narrow down where the problem is exactly, but the first thing I would change, is the way you build your query string in javascript. I am not sure if a data string gets encoded correctly if you send it directly, so I would use jQuery to make sure it does (in case your password contains funny characters for example).
Apart from that you are not using the data sent back from your ajax request in your javascript:
$.ajax({
type: "POST",
url: "processLogin.php",
data: $('form.formPadd').serialize(),
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ serialize your form
success: function(data){
// ^^^^ get the data
if (data === 'Correct') {
// ^^^^^^^ this is what you echo in php
window.location.replace('list.php');
} else {
alert('Invalid Credentials');
}
}
});
You would also have to change the names of the form fields or the POST variables in php so that they match again.
As a side-note, if you are going to redirect to another page in javascript, there is not much point in using ajax in the first place.
Have been trying to make a guestbook with jquery, ajax and php, I have been able to reed and print out everything inside the database but for some reason I cant save what I write in the database and then print it out as a post in the guestbook, if someone could see what I am doing wrong I would appreciate it! (for now I only try to get the username inside the database)
this is the jquery:
$("#newPost").bind('click', function(){
var userName = $('#userName').val();
var message = $('#message').val();
$.ajax({
url: "server.php?action=newPost",
type: "POST",
data: {userName: userName},
success: function(data){
if(data == "true"){
alert(data);
$('#posts').prepend('<td>'+userName+'</td>');
$('#userName').val('');
}
else{
alert('Something went wrong while trying to save!');
}
},
error: function(xhr, error){
alert('Could not connect to server!');
}
});
});
this is the server.php file:
$db = mysqli_connect('localhost', 'username', 'password', 'my_database');
if(isset($GET_['action']) && $GET_['action'] == 'newPost'){
$userName = mysqli_real_escape_string($db, POST_['userName']);
if(mysqli_query($db, "INSERT INTO message (name) VALUES ('$userName')")){
echo "true";
}
else{
echo "false";
}
}
and tis is the html form:
<form action="#">
<p>Name:</p>
<textarea type="text" class="field" id="userName" rows="1" cols="20"></textarea><br/><br/>
<p>Meddelande:</p>
<textarea type="text" class="field" id="message" rows="3" cols="20"></textarea><br/><br/>
<input value="Send" class="button" type="button" id="newPost"></input><br/>
</form>
Try replacing $GET_ and POST_ with $_GET and $_POST
Also your field names are empty, add name="userName" and name="message" to your textarea HTML tags
You forgot the name in your textarea. So $userName is empty.