i have 2 files :
- form.php :
<html>
<head>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function()
{
$('#r').click(function()
{
pseudo= $("#pseudo").val();
password= $("#password").val();
$.ajax({
type:"POST",
url:"insert.php",
data:'pseudo='+pseudo+'&password='password,
success:function(data)
{
if(data == 1)
{
alert("ddd");
}
else
{
alert("lll");
}
}
});
});
});
</script>
</head>
<body>
<center>
<form class="well form-inline" method="post" action="buscarUsuario.php">
<a class="btn btn-danger" href="" id="r">Save</a>
<input type="text" style="height: 30px" class="span4" placeholder="Pseudo" id="pseudo" />
<span id="error"></span>
<span id="ok"></span>
<input type="password" style="height: 30px" class="span4" placeholder="Password" id="password"/>
<button type="submit" style="width: 95px" class="btn btn-primary" value="Entrar" name="Entrar">Entrar</ button>
</form>
<center>
</body>
</html>
and i want to save pseudo and password in my data base through this file insert.php :
<?php
require "connecttoBD.php";
$pseudo= $_POST["pseudo"];
$password= $_POST["password"];
$sql="INSERT INTO usuarios (pseudo,password) VALUES ('$pseudo,$password') ";
$req=mysql_query($sql) or die (mysql_error());
echo "1";
?>
but when i fill out the 2 fields and press the button Save I have not saved the 2 fields in my data base.
can anyone help me please ?
thank you.
data:'pseudo='+pseudo,
change in
data:{ pseudo:pseudo,
password:password
},
in your ajax request
try
$sql="INSERT INTO usuarios (pseudo,password) VALUES ('$pseudo','$password') ";
$req=mysql_query($sql) or die (mysql_error());
and insted of
if(data == 1)
use
if($.trim(data) == 1)
Related
I made a simple script to insert data to database using ajax and jquery . It seems that I am not receiving back any response , and I don't think I am doing something wrong . So , can anybody take a look and help me ?
process.php
<?php
$id = $_POST['id'];
$user= $_POST['username'];
$password = $_POST['password'];
$con = mysqli_connect('localhost','root','','car_rental');
$query = 'insert into car_admin (admin_id,admin_username,admin_password) values(?,?,?)';
$query = $con->prepare($query);
$query-> bind_param('iss',$id,$user,$password);
if($query->execute()) { echo "done";}
else { echo "failed"; }
$query->close();
$con->close();
?>
register.php
<script src="jquery-1.12.4.js"></script>
<script src="script.js"></script>
<form id="register" method="POST" >
<fieldset>
<legend>
Register
</legend>
ID: <input id="id" type="text" name="id" value="" />
Username : <input id="username" type="text" name="username" value="" />
Passsword : <input id="password" type="password" name="password" value="" />
<input id="submit" type="submit" name="submit" value="Register" />
</fieldset>
</form>
<div id="result"></div>
jquery
$(document).ready( function() {
$('#submit').click(function() {
var id = $('#id').val();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type:'post',
url:'process.php',
data:'id='+id+'username='+username+'password='+password,
success:function(data){
$('#result').html(data);
}
});
});
Prevent the form from submitting via the browser
You need to change your code to include the correct formatting
data:'id='+id+'&username='+username+'&password='+password,
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<form id="register" >
<fieldset>
<legend>
Register
</legend>
ID: <input id="id" type="text" name="id" value="" />
Username : <input id="username" type="text" name="username" value="" />
Passsword : <input id="password" type="password" name="password" value="" />
<button id="submit" name="submit" />Register</button>
</fieldset>
</form>
<div id="result"></div>
<script>
$(document).ready( function() {
$('#submit').click(function(e) {
e.preventDefault(); // Prevent the form from submitting via the browser
var id = $('#id').val();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type:'post',
url:'login.php',
data:'id='+id+'&username='+username+'&password='+password,
success:function(data){
$('#result').html(data);
}
});
});
});
</script>
The reason your ajax is failing is because you are not posting the parameters correctly. If ID is 1, username is "Username", and password is "password", the following code will return the value shown.
'id='+id+'username='+username+'password='+password,
id=1username=Usernamepassword=Password
You need to change your code to include the correct formatting, as per below.
'id='+id+'&username='+username+'&password='+password,
Then your Ajax request should work. I can see no problems with your PHP. I would also suggest doing an encodeURIComponent as if your strings contain any URI characters, it will cause further problems. Take a look at this tutorial as it is an excellent example of making an Ajax request.
I am facing error in my code. My problem is not allowing signin at the home page. The database is working fine. The validation is fine. The problem is in script of login page. It is showing an error only in the success portion.
Here are my files:
login1.php
<!DOCTYPE html>
<?php
include('header.php');
?>
<html>
<head>
<title>Login screen</title>
<script type="text/javascript" src="script/validation.min.js"></script>
<script type="text/javascript" src="script/login.js"></script>
<link href="css1/style_log.css" rel="stylesheet" type="text/css" media="screen">
</head>
<body>
<div class="container">
<h1 align=center></h1>
<h2 align=center style="color:purple";> </h2>
<form class="form-login" method="post"name="Loginform" action="" id="login-form">
<h2 class="form-login-heading">User Log In Form</h2>
<hr />
<div id="error"></div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name="userEmail" id="user_email" />
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-success" name="submit" id="login_button">
<span class="glyphicon glyphicon-log-in"></span> Sign In
</button>
</div>
<div class="form-group">
<button class="btn btn_success"> Sign up</button>
<button class="btn btn_success"> <a href="forget_password.php"style="text-decoration: none;" >Forget password?</a></button>
<button class="btn btn_success">Reset password </button>
</form>
</div>
</div>
</div>
</body>
</html>
login1_action.php
<?php
session_start();
include'connect.php';
if(isset($_POST['submit'])& !empty($_POST)){ //check the input is post or not
$email=(strip_tags($_POST['userEmail'])); //post the input.
$password=md5(strip_tags($_POST['password']));
require"connect.php";
echo $q="select password,useremail from users where password='$password' and useremail='$email'"; //select the data from table for validation
$result=mysqli_query($con,$q);
$row=mysqli_fetch_assoc($result);
if($row['password']==$password){
echo "ok";
exit;
$_SESSION['user_session'] = $row['serialno'];
} else {
echo "email or password does not exist."; // wrong details
}
}
?>
login.js
$('document').ready(function() {
/* handling form validation */
$("#login-form").validate({
rules: {
password: {
required: true,
},
userEmail: {
required: true,
email: true
},
},
messages: {
password:{
required: "please enter your password"
},
userEmail: {required: "please enter your password"},
},
submitHandler: submitForm
});
/* Handling login functionality */
function submitForm() {
var data = $("#login-form").serialize();
$.ajax({
type : 'POST',
url : 'login1_action.php',
data : data,
beforeSend: function(){
$("#error").fadeOut();
$("#login_button").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(response){
if(response=="ok") {
$("#login_button").html('<img src="ajax-loader.gif" /> Signing In ...');
setTimeout(' window.location.href = "index1.php"; ',4000);
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
$("#login_button").html('<span class="glyphicon glyphicon-log-in"></span> Sign In');
});
}
}
});
return false;
}
});
In login1.php:
You have a semicolon outside your style value on <h2>. Pull it inside the double quote.
You have one too many </div>'s at the end and your </form> is out of nesting order.
In login1_action.php:
Your first condition statement only has one & in the between the two conditions. Change this to &&.
You are using exit before you declare the $_SESSION data. Move exit after the declaration.
Your query is not injection-safe. I advise you to use a prepared statement.
You are not calling the serialno column in your query, but you are asking for the value from the resultset when you are declaring the $_SESSION['user_session'] value.
Here is a new block of code using a prepared statement:
if($stmt=$con->prepare("SELECT `serialno` FROM `users` WHERE `useremail`=? AND `password`=?;")){
// stripping tags will do nothing to protect you
$email=$_POST['userEmail'];
$password=md5($_POST['password']);
$stmt->bind_param("ss",$email,$password);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($serialno);
if($stmt->fetch()){
$_SESSION['user_session']=$serialno;
echo "ok";
$stmt->free_result();
}else{
echo "Incorrect Username/Password Combination"; // Query Logic Error
}
$stmt->close();
}else{
echo "Query Syntax Error"; // echo mysqli_error($con);
}
And I recommend that you replace your md5() function.
Reading: Why not use MD5 for password hashing?
Creating a register.html form where the user is prompt to enter a name, email and password, then clicks submit which triggers a php script to check is the email enter is already in use, and if it is not already in use, it places the users data in the appropriate fields in the table 'users-form' on mysql.
My issue is that AJAX isn't submitting the form. The javascript that states "Fill in empty fields" works fines. I don't know what I am doing wrong.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Reg Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div class="header">
<div>Register form</div>
</div>
<form action="">
<p> Enter name, email and password</p>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="email" type="text">
<label>Password :</label>
<input id="password" type="password">
<input id="submit" type="button" value="Submit">
</form>
//Internal Javascript
<script>
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
//success message when information is stored in database.
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password;
if (name == '' || email == '' || password == '') {
alert("Fill in empty fields");
} else {
//submits form
$.ajax({
type: "POST",
url: "connect.php",
data: dataString,
cache: false,
success: function(result) {
alert(result);
}
});
}
return false;
});
});
</script>
</body>
</html>
AJAX connect.php:
<?php
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("mydatabase", $connection); // Selecting Database
//Fetching Values from URL
$name2=$_POST['name1'];
$email2=$_POST['email1'];
$password2=$_POST['password1'];
//Insert query
$query = mysql_query("insert into users-form(name, email, password) values ('$name2', '$email2', '$password2')");
echo "Submitted!";
mysql_close($connection); // Connection Closed
?>
Any ideas? Thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Reg Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<script src="js/theme.init.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<div class="header">
<div>Register form</div>
</div>
<form action="" id="form">
<p> Enter name, email and password</p>
<label>Name :</label>
<input id="name" name="name1" type="text">
<label>Email :</label>
<input id="email" name="email1" type="text" required>
<label>Password :</label>
<input id="password" name="password1" type="password" required>
<input id="submit" type="button" value="Submit">
</form>
//Internal Javascript
<script type="text/javascript">
$(document).ready(function (e){
$("#form").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "connect.php ",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(result) {
alert(result);
}
});
return false
}));
});
</script>
</body>
</html>
Your javascript code is fine the problem is mysql has deprecated instead you can use mysqli so your connection could be something like this:
$con = mysqli_connect("localhost","username","password","dbname");
$name2=$_POST['name1'];
$email2=$_POST['email1'];
$password2=$_POST['password1'];
$query = mysqli_query($con, "insert into `users-form` (name, email, password) values ('$name2', '$email2', '$password2')");
if ($query) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../rncdemo/w3.css">
<script src="../rncdemo/jquery/jquery.min.js"></script>
</head>
<body>
<?php
include('menubar.php');
?>
<center>
<div class="w3-dark-grey" style="max-width:650px">
<header class="w3-padding-32 w3-teal"><h4>Member Login</h4></header>
<br><br>
<form name="loginform" method="post">
<div id="req"></div>
<table>
<tr>
<td><label><b>User Name</b></label></td>
<td><input class ="w3-input w3-border" type="text" id="username" name="username" required /></td>
</tr>
<td><label><b>Password</b></label></td>
<td><input class="w3-input w3-border" type="password" id="pwd" name="pwd" required/></td>
</tr>
<tr>
<td></td><td class="w3-center">
<br>
<tr>
<td></td>
<td>
<input class ="w3-btn w3-teal w3-hover-red" name="login" type="submit" id="login" value="Login">
<input class ="w3-btn w3-light-grey w3-hover-red" name="reset" type="reset" id="reset" value="Reset">
</td>
</tr>
</table>
<br><br>
<div id="errmsg"></div>
</form>
</div>
</center>
<script src="memlogin.js"></script>
</body>
</html>
///////////
$(document).ready(function(){
$("#pwd").focus(function(){
$("#errmsg").html('');
});
$("#login").click(function(){
username = $("#username").val();
pwd = $("#pwd").val();
if(username=='' || pwd =='')
{
$("#req").html("All fields are required");
}
else{
$.ajax({
type: "POST",
url: "memlogprocess.php",
data: "username="+username+"&pwd="+pwd,
success: function(data){
if(data=="ok") {
window.location="memberwelcome.php";
}
else{
$("#errmsg").html("username or password is incorrect !!!!");
$("#pwd").val('');
}
}
/*beforeSend:function()
{
$("#msg").css('display', 'inline', 'important');
$("#msg").html("<img src='images/ajax-loader.gif' /> Loading...")
}*/
});
return false;
}
});
});
///////////////
<?php
session_start();
include('database.php');
$name=$_POST['username'];
$pwd=$_POST['pwd'];
$rs=mysqli_query($conn,"select * from memberuser where username='$name' and password='$pwd'")or die("Could Not Perform the Query");
if(mysqli_num_rows($rs) > 0)
{
$_SESSION['memusername']=$name;
echo 'ok';
}
else
{
echo 'notok';
}
?>
////////
<?php
echo $_SESSION['memusername'];
?>
I am not getting the value of session value on welcome page on server But getting the value on localhost server. 1st time is not showing but after that it is showing the session value. PLZ help me......
you need to start session in all pages
<?php session_start();?>
Note :- Start session on top of the page right after php tag
The above code is correct. If we face this kind of problem we need to change the file name.On the server if we edit a single file many time, there may be a chance to get this kind of error. So we need to change the file name and write the same code.
Hello so I have 2 submit buttons with different names (btn1, btn2) in my html form and what I am trying to do is to submit to another page without refreshing page. So what I wanted to do is if I click btn1 submit it will do something and if I click btn2 it will do another thing. My code in the html page is this
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'update.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1"> <input type="submit" name="btn2">
</form>
</body>
</html>
And the code in my update.php page
<?php
if(isset($_POST['btn1'])) {
//insert query
} else if(isset($_POST['btn2'])) {
//another insert query
}
?>
I actually got it working if I only have 1 submit button and no if(isset()) thing in the update.php page. What can I do to use 2 submits and with issets in another page without refreshing the main page?
$(this).serialize();
The above code statement doesn't include name of the submit button as a key value pair.
So, as people have suggested before me, you should use button instead of submit button. Something like this.
HTML and JS
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#btn1, #btn2').on('click',function(e) {
var datastr = $(this).serialize() + "&button_id="+$(this).attr('id');
$.ajax({
url:'update.php',
data:datastr,
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm" action="update.php">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<button id="btn1">Button1</button><button id="btn2">Button2</button>
</form>
</body>
</html>
AND PHP would be:
<?php
if($_POST['button_id'] == 'btn1') {
//do something
} else if($_POST['button_id'] == 'btn2') {
//do something else;
}
?>
Use this, may useful for you
try
$('#myForm').on('submit',function(e) {
e.preventDefault();
});
OR
<button type="button">
Use on click event on the button and add the value attribute to the submit button, the value of the click button will be pased to the php file
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('input[type="submit"]').on('click',function(e) {
e.preventDefault();
$.ajax({
url:'update.php',
data:{'txt_amount':$('input[name="txt_amount"]').val(),'btn': $('input[type="submit"]').val()}
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1" value="btn1"> <input type="submit" name="btn2" value="btn2">
</form>
</body>
</html>
php:
<?php
if($_POST['btn'] == 'btn1') {
//do something
} else if($_POST['btn'] == 'btn2') {
//do something else;
}
?>