I'm trying to create a php form that sends textarea data to database. The database table uploads has 3 data items that are needed:
user_id
category
content
HTML:
<form id="myform" action="php/savetext.php" method="POST" enctype="multipart/form-data">
<p><strong>Add your story here.</strong></p>
<input type="hidden" name="fbid" id="fbid">
<input type="hidden" name="category" id="category">
<textarea cols="50" rows="10" name="usertext" id="storyArea"></textarea>
<input type="submit" name="submit" value="Saada" />
<script type="text/javascript">
$( "#fbid" ).val( "sdf88d99sd" );
$( "#category" ).val( "texts" );
</script>
</form>
savetext.php:
include_once('config.php');
if (isset($_POST['user_id']) && isset($_POST['category']) && isset($_POST['usertext'])) {
$user_id = mysql_real_escape_string($_POST['fbid']);
$category = mysql_real_escape_string($_POST['category']);
$content = mysql_real_escape_string($_POST['usertext']);
addUser($user_id, $category, $content);
}
else {
echo 'Upload failed! Try again.';
}
function addUser($user_id, $category, $content) {
$query = "SELECT id FROM uploads WHERE user_id = '$fbid' LIMIT 1";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
if ($rows > 0) {
$query = "UPDATE uploads SET user_id = '$user_id', category = '$category' WHERE content = '$content'";
}
else {
$query = "INSERT INTO uploads (user_id, category, content) VALUES ('$user_id', '$category', '$content')";
}
mysql_query($query);
echo 'Upload was succesful. Thank you!';
}
But this doesn't work. Any ideas on how to correct this?
please review this code ,there is no field with name user_in in <form></form>
if (isset($_POST['fbid']) && isset($_POST['category']) && isset($_POST['usertext'])) {
$user_id = mysql_real_escape_string($_POST['fbid']);
$category = mysql_real_escape_string($_POST['category']);
$content = mysql_real_escape_string($_POST['usertext']);
addUser($user_id, $category, $content);
}
Related
i'll be glad if anyone can help out am working on a login system using jquery but i encounter a problem
what i want to achieve is user filling out their details on the login page and i'll process it using jQuery at the back end without reloading the page, i have achive that but the problem now is when the details they provide and the details in the database is correct i want to redirect them to another page
here is my login form
<form class="form-login" id="loginmyForm" method="post">
<input class="input input_auth" type="text" name="loginemail" id="loginemail" placeholder="E-mail" required />
<span id="loginError_username" class="error error-opacit"></span>
<input class="input input_auth" type="password" name="loginpassword" id="loginpassword" placeholder="Password" required />
<span id="loginError_password" class="error error-opacit"></span>
<input type="hidden" name="source" value="login" id="source">
<button class="btn pulse input_auth" type="button" id="submitFormData" onclick="loginSubmitFormData();" value="Submit">Login</button>
<div class="forgot-password">
<a id="forgotPass" href="#" class="link-btn open-modal" data-openModal="modal-recovery">Forgot your password?</a>
</div>
Here is jquery code
<script type="text/javascript">
function loginSubmitFormData() {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
var source = $("#source").val();
$.post("authlogin.php", { loginemail: loginemail, loginpassword: loginpassword },
function(data) {
$('#loginresults').html(data);
$('#loginmyForm')[0].reset();
});
}
</script>
And here is the login authentication authlogin.php
<?php
session_start();
include 'config/info.php';
// get the details from form
$email=$_POST['loginemail'];
$password = stripslashes($_REQUEST['loginpassword']);
$password = mysqli_real_escape_string($conn,$password);
$sql="SELECT * FROM user_info WHERE email='".$email."'";
$result = mysqli_query($conn,$sql);
$Countrow = mysqli_num_rows($result);
if ($Countrow == 1) {
$fetchrow = mysqli_fetch_assoc($result);
$loginpassword = $fetchrow['password'];
// Verify the password here
if (password_verify($password, $loginpassword)) {
$_SESSION['email'] = $email;
//setcookie('username', $adminID, time() + (86400 * 30), "/");
$date = date('Y-m-d H:i:s');
$ActivityStmt = "INSERT INTO login_activity (`email`, `last_login`, `browser`, `os`, `ip_address`) VALUES('".$email."', '".$date."', '".$gen_userBrowser."', '".$gen_userOS."', '".$gen_userIP."')";
$ActivityResult = mysqli_query($conn, $ActivityStmt);
echo 'Login Successfully! Click to proceed';
exit();
}
else{
echo 'Incorrect Password';
exit();
}
}
else{
echo 'User does not exit';
exit();
}
?>
I have tried using
header('Location: account');
and
window.location.href = "account";
after the session is saved but none is working, please who can help me on how to get this done
You should try this jQuery Code and PHP Code by replacing them in your code section, It will definitely work for you:
<script type="text/javascript">
function loginSubmitFormData() {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
var source = $("#source").val();
$.post("authlogin.php", { loginemail: loginemail, loginpassword: loginpassword },
function(data) {
var data = jQuery.parseJSON( data );
console.log(data);
$('#loginresults').html(data.message);
if(data.redirect_url){
window.location.href = data.redirect_url;
}
$('#loginmyForm')[0].reset();
});
}
</script>
<?php
session_start();
include 'config/info.php';
// get the details from form
$email=$_POST['loginemail'];
$password = stripslashes($_REQUEST['loginpassword']);
$password = mysqli_real_escape_string($conn,$password);
$sql="SELECT * FROM user_info WHERE email='".$email."'";
$result = mysqli_query($conn,$sql);
$Countrow = mysqli_num_rows($result);
if ($Countrow == 1) {
$fetchrow = mysqli_fetch_assoc($result);
$loginpassword = $fetchrow['password'];
// Verify the password here
if (password_verify($password, $loginpassword)) {
$_SESSION['email'] = $email;
//setcookie('username', $adminID, time() + (86400 * 30), "/");
$date = date('Y-m-d H:i:s');
$ActivityStmt = "INSERT INTO login_activity (`email`, `last_login`, `browser`, `os`, `ip_address`) VALUES('".$email."', '".$date."', '".$gen_userBrowser."', '".$gen_userOS."', '".$gen_userIP."')";
$ActivityResult = mysqli_query($conn, $ActivityStmt);
$message = 'Login Successfully!';
$response = array(
'message' => $message,
'redirect_url' => 'https://www.example.com',
);
exit();
}
else{
$message = 'Incorrect Password';
$response = array(
'message' => $message
);
exit();
}
}
else{
$message = 'User does not exit';
$response = array(
'message' => $message,
);
exit();
}
echo json_encode( $response);
?>
here in my code i am trying to fetch and display the data after selecting a option from the dropdown using onChange, fetching data from a PHP file and via ajax displaying it in textarea in same select.php file but unfortunately it is not working out for me am quit confused were i made a mistake, please help me out on this.
select.php
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#channel").change(function(){
$.post("ajax.php", { channel: $(this).val() })
.success(function(data) {
$(".result").html(data);
});
});
});
</script>
</head>
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" id = 'channel' name="ProductCategoryID" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="1234">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group result"></div>
ajax.php
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode = '$channel' ";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
while($row = mysql_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
Try using:
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
May be it would help
replace,
$.post("ajax.php", { channel: $(this).val() })
with
$.post("ajax.php", { 'channel': $(this).val() })
$.post("ajax.php", { channel: $(this).val() },function(data) {
$(".result").html(data);
});
Please remove .success(function(data){ }) from the code and it will work :)
Try to initiate $msg first and use mysqli module.
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode =$channel";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
UPDATE
Update your post request with:
$.post("ajax.php",
{ channel: $(this).val() },
function(data) {
$(".result").html(data);
}
);
OR
$.post("ajax.php",
{ channel: $(this).val() },
successCallback
);
function successCallback(data){
//process data..
}
see https://api.jquery.com/jquery.post
I want Ajax to apply only in the div (#usersDiv)
When selector is changed into 'body' it loads the whole page repeatedly. (Cannot type in the box)
but when selector changed as #userDiv, it shows the search box twice in the page. In the first box can be typed, but again second box loads over and over.
PHP file is as follows (test.php)
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function users($connection){
if(!empty($_POST)){
$country = $_POST['userCountry'];
$sql = "SELECT * FROM users WHERE country = '$country' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userName = $row['username'];
$city = $row['city'];
echo '<div><h4>'. $userName. " ". $city. '</h4></div>';
}
} else {
echo "Use search box!";
}
} else {
echo "Use Search Box!";
}
}
?>
<html>
<head><script src = "jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("http://freegeoip.net/json/", function(data) {
var country = data.country_name;
$.ajax({
method:"POST",
url:"test.php",
data:{userCountry:country},
success:function(result){
$('#usersDiv').html(result);
}
});
});
});
</script>
</head>
<body>
<form name = "searchForm" action = "search.php" method = "POST">
<input type = "text" name = "searchPlace" required />
<input type = "submit" value = "Search"/>
</form>
<div id = "usersDiv"> <?php users($connection); ?> </div>
</body>
<html/>
I have altered your code to wrap your PHP function within an if($_POST) to prevent the entire page loading
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
if($_POST){ // Check if form has been submitted
$country = $_POST['userCountry'];
$sql = "SELECT * FROM users WHERE country = '$country' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userName = $row['username'];
$city = $row['city'];
echo '<div><h4>'. $userName. " ". $city. '</h4></div>';
}
} else {
echo "Use search box!";
}
}else{ // If it hasn't then show the search form
?>
<html>
<head><script src = "jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#searchForm").on("submit",function(e){ // Check for form submission
$.getJSON("http://freegeoip.net/json/", function(data) {
var country = data.country_name;
$.ajax({
method:"POST",
url:"test.php",
data:{userCountry:country},
success:function(result){
$('#usersDiv').html(result);
}
});
});
});
});
</script>
</head>
<body>
<form name = "searchForm" action = "search.php" method = "POST" id="searchForm">
<input type = "text" name = "searchPlace" required />
<input type = "submit" value = "Search"/>
</form>
<div id = "usersDiv"></div>
</body>
<html/>
<?php } ?>
As Alexander suggests, read up on SQL Injection
How can I prevent SQL injection
I'm trying to send two values from a form to another PHP using ajax post method. One value is the value that's already entered in an input box, and the other is a value that is being typed into another input box. It acts like a search box. I tried executing the SQL query in my SQL workbench and it returns the value properly. What am I doing wrong in my code?
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
$("#sbb").html(sbb);
//searchq7();
});
}
This is the input box where I search and get the value from:
<input type="text" name="region" list="state" value="<?php echo $region; ?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" list="sbb" value="<?php echo $suburb; ?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6" >
<option> </option>
</datalist>
This is the search-suburb.php file:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state="'.$st.'" AND `title` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$suburb = $row['title'];
?>
<option value="<?php echo $suburb; ?>"><?php echo $suburb; ?> </option>
<?php
} // while
} // else
} // main if
<input type="text" name="region" list="state" value="<?=(isset($_POST['region'])?$_POST['region']:'');?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" onkeyup="searchq6()" list="sbb" value="<?=(isset($_POST['suburb'])?$_POST['suburb']:'');?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6"></datalist>
Javascript:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
var decode = jQuery.parseJSON(sbb); // parse the json returned array
var str = ""; // initialize a stringbuilder
$.each(decode, function (x, y) {
str+="<option value='" + y.title +"'>";
});
$("#sbb").html(str);
}); // end of post
}// end of searchq6 function
Php:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='{$st}' AND `title` LIKE '%{$searchq}%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
} else{
$data = array();
while($row = mysqli_fetch_array($query))
$data[] = $row;
echo json_encode($data);
}
} // main if
Got the answer from small snippets gathered through the comments
Changed the query to:
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."' AND `title` LIKE '%".$searchq."%' LIMIT 10")or die("Could not search!");
And the ajax to:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate})
.done(function(sbb) {
$("#sbb").html(sbb);
});
//searchq7();
}
Thanks for all the comments guys
I may be being stupid, but I am trying to process a registration form using an AJAX call to a PHP page. My PHP page is working perfectly on it's own, but when I try to post the form data to the PHP page through AJAX nothing happens.
This is my AJAX call:
$(document).ready(function ($) {
$("#register").submit(function(event) {
event.preventDefault();
$("#message").html('');
var values = $(this).serialize();
$.ajax({
url: "http://cs11ke.icsnewmedia.net/DVPrototype/external-data/register.php",
type: "post",
data: values,
success: function (data) {
$("#message").html(data);
}
});
});
});
This is the form:
<div id="registerform">
<form method='post' id='register'>
<h3>Register</h3>
<p>Fill in your chosen details below to register for an account</p>
<p>Username: <input type='text' name='username' value='' /><br />
Password: <input type='password' name='password' ><br />
Repeat Password: <input type='password' name='repeatpassword'></p>
<input name='submit' type='submit' value='Register' >
<input name='reset' type='reset' value='Reset'><br /><br />
</form>
<div id="message"></div>
</div>
And this is my PHP page:
<?php function clean_string($db_server = null, $string){
$string = trim($string);
$string = utf8_decode($string);
$string = str_replace("#", "#", $string);
$string = str_replace("%", "%", $string);
if (mysqli_real_escape_string($db_server, $string)) {
$string = mysqli_real_escape_string($db_server, $string);
}
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return htmlentities($string);
}
function salt($string){
$salt1 = 'by*';
$salt2 = 'k/z';
$salted = md5("$salt1$string$salt2");
return $salted;
}
?>
<?php
//form data
$submit = trim($_POST['submit']);
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$repeatpassword = trim($_POST['repeatpassword']);
// create variables
$message = '';
$s_username = '';
//connect to database
{databaseconnection}
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
if(!$db_server){
//error message
$message = "Error: could not connect to the database.";
}else{
$submit = clean_string($db_server, $_POST['submit']);
$username = clean_string($db_server, $_POST['username']);
$password = clean_string($db_server, $_POST['password']);
$repeatpassword = clean_string($db_server, $_POST['repeatpassword']);
//check all details are entered
if ($username&&$password&&$repeatpassword){
//check password and repeat match
if ($password==$repeatpassword){
//check username is correct length
if (strlen($username)>25) {
$message = "Username is too long, please try again.";
}else{
if (strlen($password)>25||strlen($password)<6) {
//check password is correct length
$message = "Password must be 6-25 characters long, please try again.";
}else{
mysqli_select_db($db_server, $db_database);
// check whether username exists
$query="SELECT username FROM users WHERE username='$username'";
$result= mysqli_query($db_server, $query);
if ($row = mysqli_fetch_array($result)){
$message = "Username already exists. Please try again.";
}else{
//insert password
$password = salt($password);
$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($db_server, $query) or die("Registration failed. ".
mysqli_error($db_server));
$message = "Registration successful!";
}
}
}
}else{
$message = "Both password fields must match, please try again.";
}
}else{
$message = "You must fill in all fields, please try again.";
}
}
echo $message;
mysqli_close($db_server);
?>
Apologies for all the code. I feel I may be making a stupid mistake but I don't know why the data isn't being posted or returned.
Thanks in advance!
Notice: This is more a comment than an answer but this is more readable since it includes code.
== EDIT ==
I Checked your code on http://cs11ke.icsnewmedia.net/DVPrototype/#registerlogin, your form doesn't have a id assigned to it
First: use your console...do you see an XMLHTTPREQUEST in your console?
What are the responses/headers etc? I can't stress this enough: use your console and report back here!!!
Next up the overly complicated ajax call...dumb it down to:
$('#register').submit(function(){
$('#message').html('');
$.post("http://cs11ke.icsnewmedia.net/DVPrototype/external-data/register.php",
$(this).serialize(),
function(response){
console.log(response);
$('#message').html(response);
}
);
return false;
});
In your PHP put this on top to check whether anything at all came through:
die(json_encode($_POST));
Please use Firebug or any other tool, to checḱ if the AJAX-script is called, what is its answer and if there are any errors in the script
My form is not submitting data to my database.
This is the PHP code:
<?php require 'core.inc.php'; ?>
<?php require 'connection.inc.php'; ?>
<?php
if(isset($_POST['username']) && isset($_POST['password']) &&
isset($_POST['password_again']) && isset($_POST['firstname']) &&
isset($_POST['surname'])){
$username = $_POST['username'];
$password = $_POST['password'];
$hashed_password = sha1($password);
$password_again = sha1('password again');
$username = $_POST['firstname'];
$password = $_POST['surname'];
//check if all fields have been filled
if(!empty($username)&& !empty($password) && !empty($password_again) &&
!empty($firstname)&& !empty($surname)){
if($password != $password_again){
echo 'Passwords do not match.';
} else {
//check if user is already registered;
$query = "SELECT username FROM user WHERE username = {$username} ";
$query_run = mysqli_query($connection, $query);
if (mysqli_num_rows ($query_run)==1){
echo 'User Name '.$username.' already exists.';
} else {
//register user
$query = "INSERT INTO `user` VALUES ('', '".$username."',
'".$password_hashed."','".$firstname."','".$surname."',)";
}
if($query_run = mysqli_query($connection, $query)){
header('Location: reg_succed.php');
} else {
echo 'Sorry we couldn\'t register you at this time. try again later';
}
}
}
} else {
echo 'All fields are required';
}
?>
<h2>Create New User</h2>
<form id="form" action="<?php echo $current_file ?>" method="POST">
<fieldset title="Login details" id="frame">
<legend>USER LOGIN DETAILS</legend>
<label>User Name:</label><br/>
<input type="text" name = "username" id = "username" value="<?php if(isset($username)){ echo $username; } ?>" maxlength="50" placeholder="Enter your Username" required/><br/>
<label>First Name:</label><br/>
<input type="text" name="firstname" id = "firstname" value="<?php if(isset($firstname)){ echo $firstname;} ?>" maxlength="50" placeholder="Enter your Firstname" required/><br/>
<label>Surname:</label><br/>
<input type="text" name="surname" id="surname" value="<?php if(isset($surname)) {echo $surname;} ?>" maxlength="50" placeholder="Enter your Surname" required/><br/>
<label>Password:</label><br/>
<input type="password" name="password" id="password" maxlength="50" placeholder="Enter your Password" required/><br/>
<label>Password Again:</label><br/>
<input type="password" name="password_again" id="password again" maxlength="50" placeholder="Enter your Password" required/><br/>
<input type="submit" name = "register" id = "register" value="Register">
</fieldset>
</form>
connection code
<?php
require_once("constants.php");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS, DB_NAME);
if (!$connection) {
die("Database connection failed: " . mysqli_error($connection));
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
?>
core.inc.php code
<?php
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];
if(isset( $_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])){
$http_referer = $_SERVER['HTTP_REFERER'];
}
?>