it is my code.
html
<html>
<head></head>
</body>
<form id="myform" action="formdata.php" method="post">
username:<input type="text" name="username" id="name"><br>
password:<input type="password" name="password" id="pass"><br>
firstname:<input type="text" name="firstname" id="fname"><br>
lastname:<input type="text" name="lastname" id="lname"><br>
<input type="submit" id="submit" value="register">
</form>
<div id="status_text"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$("#submit").click(function(){
var username = $('#name').val();
var password = $('#pass').val();
var firstname = $('#fname').val();
var lastnamee = $('#lname').val();
var postData = '&username='+username+'&password='+password+'&firstname='+firstname+'&lastname='+lastname;
var status_text = $('#status_text');
//alert(postData);
//var mydata = {'username':name,'password':pass,'firstname':fname,'lastname':lname};
/*$.post($('#myform').attr('action'),
$('#myform:input').serializeArray(),
function(info){
$('status_text').html(info)
});*/
$.ajax({
url:"action",
type:"post",
success:function(info)
{
status_text.html(info);
}
});
});
</script>
</body>
</html>
and it is my php code for database
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$conn = new mysqli($servername, $username, $password);
$name = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO karthik.person(name,password,firstname,lastname)VALUES('$name','$password','$firstname','$lastname')";
if($conn->query($sql) === TRUE){
echo("record added success");
}else{
echo("failed".$conn->error);
}
$conn->close();
?>
when ever i run this code it goes to next page and display the result like "record added successfully" instead of that i want the code to display the result in the same page. i almost tried all ways but i can't get my expected result.
You have some problems here:
You are not preventing the default submit event and that causes the form to submit "normally" as well.
You are not sending any data with your ajax request so you will never have any $_POST variables on the server-side.
You have an sql injection problem. You should use a prepared statement and bind the values.
You are not sending your ajax request to the correct url.
You are using a plain-text password. You should always salt and hash passwords.
You need to tell the browser not to submit the form:
$("#submit").click(function(e) {
e.preventDefault(); // Prevents the default behaviour for the submit-action
//... the rest of your code
When you get this working, you should start fixing stuff from #jeroen's list.
Related
I posted two javascript variables to a php file aswell as a html form using Ajax separately. I want to use the two javascript variables with the posted form values but I'm not sure how to go about this.
<script>
$(document).ready(function() {
var aucid = "<?php echo $auctionID; ?>";
var userid = "<?php echo $userID; ?>";
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': aucid, 'userid' : userid },
success: function (result) {
$('#price').html(result);
}
});
$('form').bind('submit', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
type: 'POST',
url: 'JqueryPHP/HighestBid.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
I posted the two javascript variables separately to the form.
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
</form>
<h4 class="price">Highest bid : <span id="price"></span></h4>
When I echo the value of userID into the span class, you can see it has a value of 2.
//JqueryPHP/HighestBid.php'
$auctionid;
$userID;
$auctionid = $_POST['auctionid'];
$userID = $_POST['userid'];
echo $userID;
if (isset($_POST['newbid']))
{
$newbid=$_POST['newbid'];
$conn = new mysqli('localhost', 'root', '', 'auctionsite');
$sql = 'INSERT INTO auction (useridhighestbid)VALUES("'.$userID.'")';
if(#$conn->query($sql)){ //execute the query and check it worked
return TRUE;
}
}
however when I try use the userID when the form is submitted and try insert it into the database for testing purposes, the value is 0.
How would I go about posting the form value with the javascript variables so I can use an update statement to update my database?
Set two hidden inputs to save aucid and userid like this:
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
<input name='aucid' style="display:none"/>
<input name='userid' style="display:none"/>
</form>
<script>
$(document).ready(function() {
$("input[name='aucid']").val("<?php echo $auctionID; ?>");
$("input[name='userid']").val("<?php echo $userID; ?>");
.......................
});
</script>
Send your form to a php script. When the user logs in, retrive his ID from DB and put it in session like this
switch(isset($_POST['login'])):
case 'Register':
$email = htmlspecialchars(trim($_POST['em']), ENT_QUOTES, 'UTF-8');
$password = htmlspecialchars(trim($_POST['pw']), ENT_QUOTES, 'UTF-8');
// check if the combination fname/lname/email is already used
include('./Models/log_check.php');
unset($_SESSION['ID'],$_SESSION['role']);
$_SESSION['ID'] = $row['ID'];
$_SESSION['role'] = $row['role'];
So you can use ID in your Model/query:
<?php
/* Jointure sama RDV des vets */
$query =
"SELECT
appointment.start,
appointment.app_day,
patients.pet_name,
patients.breed,
patients.ID,
clients.last_name,
clients.first_name,
appointment.type,
appointment.canceled
FROM appointment
JOIN patients
JOIN clients
WHERE clients.users_ID = patients.owner_ID
AND patients.ID = appointment.patients_ID
AND appointment.vets_ID = (SELECT ID FROM vets WHERE users_ID = :ID)
AND appointment.canceled = 'n'
AND WEEK(appointment.app_day) = WEEK(:date)
ORDER BY appointment.app_day,appointment.start";
$query_params = array(':ID' => $_SESSION['ID'],
':date' => $date);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
?>
Insert instead of SELECT
Assuming you parsed the variables correctly, you can use:
$_POST['JavaScript_variable_name_goes_here'];
or
$_GET['JavaScript_variable_name_goes_here'];
to retrieve the variables in a PHP format, depending on your AJAX method.
A direct example from your AJAX function would be:
<?php $auctionId=$_POST['auctionid']; ?>
However, what I would encourage you to do, is that once a user is logged in, you set their userId as a session variable that you can use wherever the user "goes". That way, you are not parsing a crucial data element through JavaScript, which is handled client side, meaning that it's fully editable by the user through the use of a browsers dev tools. The same goes for the auctionId. I would recommend a php session variable logic for the exact same reasons. You can always overwrite the auctionId session variable with another auctionId depending on which auction is "in use".
Another good reason to why setting userId as a session variable, is that you will never have any trouble accessing the variable anywhere, as long as you remember to set the following at the very beginning of your PHP files:
<?php session_start(); ?>
The PHP/SQL syntax for the mysqli_* extension would then be the following:
$conn=mysqli_connect("localhost", "root", "", "auctionsite");
$sql="INSERT INTO auction SET useridhighestbid='$userID'";
mysqli_query($conn, $sql);
Let me know if you need anything elaborated, or if you run into any other problems.
You can append the data with the serialize like this in ajax call
data: $("#form_id").serialize() + '&xyz=' + xyz
I'm doing a log in page, i have javascript doing validations ( checking if field is blank) sql storing the data and php doing what php does (idk).... anyway when I press submit it tells me Cannot POST /login.php
is there away to test it on a website and see if it actually works or is the code completely wrong.
<?php
$server = 'localhost';
$username = 'root';
$passowrd = 'cosc_453';
$dbname = 'login'
if(!empty($_POST['user']))
{ $query = mysql_query("SELECT * FROM UserName where userName ='$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
{ $_SESSION['userName'] = $row['pass']; echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }
else { echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{ SignIn();
} ?>
php external
function validate(){
if ( document.getElementById (user).value=="")
{
alert ("Please enter your user name");
}
else if ( document.getElementById(pass).value=="")
alert("Please enter you password");
else {
alert("Processing Login........");
}
}
javscript external
CREATE TABLE UserName (
UserNameID int(9) NOT NULL auto_increment,
userName VARCHAR(40) NOT NULL,
pass VARCHAR(40) NOT NULL,
PRIMARY KEY(UserNameID) );
INSERT INTO
UserName (userName, pass)
VALUES
("cosc" , "453");
sql external
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-In</title>
<link rel="stylesheet" type="text/css" href="home.css">
<script src ="login.js"></script>
</head>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>
<form method="Post" action="login.php" submit =" validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
< /fieldset>
</div>
</body>
</html>
Your mysql do not have a connection to database. And please stop using mysql, use mysqli instead
<?php
$con = mysqli_connect("localhost","root","cosc_453","login");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM UserName WHERE userName ='".$_POST[user]."' AND pass = '".$_POST[pass]."'";
$result = mysqli_query($conn,$sql);
$count_result = mysqli_num_rows($result);
// Login Success URL
if($count_result == 1)
{
// If you validate the user you may set the user cookies/sessions here
#setcookie("logged_in", "user_id");
#$_SESSION["logged_user"] = "user_id";
$_SESSION["secret_id"] = $row['secret_id'];
if($row['level'] == 1)
{
// Set the redirect url after successful login for admin
$resp['redirect_url'] = 'admin/';
}
else if($row['level'] == 2)
{
// Set the redirect url after successful login for user
$resp['redirect_url'] = 'user/';
}
}
else
{
echo "Invalid username or pass";
}
?>
To add onto what Eh Ezani stated, you have an issue in your HTML. Your form attribute reads submit when I believe what you meant is onsubmit. Might want to try something like.
<form method="Post" action="login.php" onsubmit ="return validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
Also, "Use MySQLi over the older MySQL functions. The "i" stands for "improved". The list of improvements can be found in the docs.
-credited to
Difference between mysqli and mysql?
I have a form in which people have to type their ID, based on the ID the corresponding data from the database is loaded into text fields on the same page. People can alter the data and update the database.
To load the data I use the following Javascript code:
function btn_load_Click(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4&& xmlhttp.status==200){
document.getElementById("perDATA").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","Load.php",true);
xmlhttp.send();
document.getElementById('txtItem1').value = document.getElementById('hid-item1').value;
document.getElementById('txtItem2').value = document.getElementById('hid-item2').value;
}
The PHP:
$host = "localhost";
$user = "username";
$password = "password";
$database = "database";
$connection = mysqli_connect($host,$user,$password,$database) or die ("connection to server failed");
mysqli_select_db($connection,$database) or die ("couldn’t select database");
$player = mysqli_real_escape_string($connection,$_POST['txtUser']);
$item1 = mysqli_real_escape_string($connection,$_POST['txtItem1']);
$item2 = mysqli_real_escape_string($connection,$_POST['txtItem2']);
$query = "SELECT * FROM table WHERE userId=$player";
$result = mysqli_query($connection,$query)
or die ("couldn’t execute update query: ".mysqli_error($connection));
$row = mysqli_fetch_assoc($result);
echo "<input type='hidden' id='hid-item1' value='".$row['item1']."'>";
echo "<input type='hidden' id='hid-item2' value='".$row['item2']."'>";
mysqli_close($connection);
?>
The HTML form:
<body>
<form id="form1" action="http://www.something.com/TestScript1.php" method="post" enctype="application/x-www-form-urlencoded">
<div>
<button type="submit" id="submit" value="Submit" title="SAVE">SAVE</button>
</div>
<div>
<input id="txtUser" name="txtUser" type="text" />
<input id="txtItem1" name="txtItem1" type="text" />
<input id="txtItem2" name="txtItem2" type="text" />
</div>
</form>
<div id="perDATA" name="perDATA"></div>
</body>
The issue: I use the Javascript to load the data in hidden fields and then copy them to the right text field. When I use a fixed ID instead of $player in the PHP script, it works just fine. However passing the ID to $player seems to be a problem. So, what I want is when people enter their ID en click LOAD, their ID value is send to the $player variable in the PHP script. The PHP script fetches the required data of that user from the database, echoes the hidden fields containing the data. And subsequently the data from the hidden fields is copied to the right text fields. All of this should happen without leaving the current page.
Okay I am at a loss for what is going wrong. I am trying to pass the form data to my php script from a simple jQuery script but for some reason when I try to access $_POST data php says that $_POST is empty?
Here we go, so I have the following jQuery and php scripts
jQuery
var post = $('#cform').serialize();
console.log("POST DATA: " + post);
$.post(action, post, function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.contact-loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#cform').slideUp('slow');
});
PHP
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
The console log of var post looks like this
POST DATA: fname=Daniel&lname=Jarvis&email=test%40gmail.com&phone=4444444444&comments=hello
And the var_dump of $_POST says this
array(0) { }
I have no clue why this is giving me so many problems so any help would be greatly appreciated.
P.S
I have also tried simply doing this for the post data but it still was not working.
var post = {fname: $('#fname').val(), lname: $('lname').val(), ...} //you get the idea
The console.log looked like this
{fname: "Dan", lname: "Jarvis", ...}
But when I var_dumped the $_POST variable it still said
array(0) { }
*There are several issues in your code,
1.Add event which will trigger ajax.
2.Your php script does not echo any data.
3.No return false or prevent defaul to stop form submission manually.(I think this is the main issue)
check the solution:*
HTML:
<form id="form">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="text" name="phone">
<input type="text" name="comments">
<input type="submit" name="submit" value="submit">
</form>
<span id="message"></span>
Javascript:
$("#form").submit(function(){
var post = $('#form').serialize();
console.log("POST DATA: " + post);
$.post('target.php', post, function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.contact-loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#cform').slideUp('slow');
});
return false;
})
PHP(I assume that your php script is target.php):
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
echo $fname.$lname.$email.$phone.$comments;
I've got a problem with a html form. Php seems to remember my POST value after refreshing my page. It has to do with a login form that I uses.
I'm using cookies to let php communicate with javascript, telling javascript if the user is logged in or not.
Php code:
<?php
if (isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = MD5($_POST['password']);
echo '<script>console.log("' . $username . '", "username"); </script>';
echo '<script>console.log("' . $password . '" , "password"); </script>';
/* against sql injections */
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$query = "SELECT user_id FROM User WHERE username='$username' AND password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
if ($row[user_id]){
$cookie_name = "login";
$cookie_value = "1";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
} else{
echo '<script> alert("Incorrect username and password combination");</script>';
}
}
?>
The form:
<form method="POST" id="loginForm">
<b>Login</b>
<table style="margin-top: 10px">
<tr><td>Username: </td><td><input type="text" name="username" placeholder="username" required="required"></td></tr>
<tr><td>Password: </td><td><input type="text" name="password" placeholder="password" required="required"></td></tr>
<tr><td><input type="submit" name="login" value="Login" style="margin-top: 5px"></td></tr>
</table>
</form>
Because I love javascript, I'm using a ajax call to communicate with php and the server database.
Javascript code:
function openPage(page) {
var content;
$.ajax({
type: 'post',
url: '/php/' + page + '.php',
success: function (data) {
document.getElementById('contentMiddle').innerHTML = data;
}
});
}
}
The problem is whenever I try to refresh the page, my php code will always run and $_POST['username'] and $_POST['password'] will always have the POST value from before refreshing the page.
I always make sure I remove the cookie before refreshing the page.
Any idea?
You've most likely already submitted the page and by hitting refresh the browser is attempting to send the POST data along with the refresh.
Since you're using Ajax to process your form you can/should remove type="submit" from the login button since there's no need for it. Instead you can have Login.
Then update your Ajax to run when the button is clicked. You can also use jQuery to get your elements by ID, for example:
$("#btn_login").on("click", function() {
$.ajax({
type: 'post',
url: '/php/' + page + '.php',
success: function (data) {
//document.getElementById('contentMiddle').innerHTML = data;
$("#contentMiddle").html(data);
}
});
});
To address the comment by #charlietfl, handling an Enter press to submit the form you'd use something like this.
document.onkeydown = function(){
if(window.event.keyCode=='13'){
$("#loginForm").submit();
}
}