Submit PHP Prepared statement with ajax - javascript

First i am just learning about PHP prepared statements and sql injection. And my first question is, is this php code good enough to stop sql injection. And my second question how do i submit this php statement with Ajax. Thanks in advance
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['submit_req']))
{
$req_title = $_POST['req_title'];
$req_min = $_POST['req_min'];
$req_entry = $_POST['req_entry'];
$req_payment = $_POST['req_payment'];
$post_req = $_POST['post_req'];
$stmt = $db->prepare('INSERT INTO users_request (req_title, min_order, poi, pay_method, req_brief) VALUES (:req_title, :min_order, :poi, :pay_method, :req_brief)');
$stmt->bindValue(':req_title', $req_title, SQLITE3_TEXT);
$stmt->bindValue(':min_order', $req_min, SQLITE3_TEXT);
$stmt->bindValue(':poi', $req_entry, SQLITE3_TEXT);
$stmt->bindValue(':pay_method', $req_payment, SQLITE3_TEXT);
$stmt->bindValue(':req_brief', $post_req, SQLITE3_TEXT);
$result = $stmt->execute();
if ($result)
{
echo "<p>Request post successful</p>";
}
}
Ajax code i have tried but didn't work
$('#post_form').submit(function () {
$.ajax({
url: "req_exec.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
$('.success').html(data);
}
});
The form
<div class="success"></div>
<div class="post_req">
<form action="req_exec.php" method="post" enctype="multipart/form-data" id="post_form">
<input type="text" name="req_title" id="req_title" placeholder="Request title. (Example: Dried Cashew Nuts)">
<input type="text" name="req_min" id="req_min" placeholder="Minimum Order. (Example: 2 Tons, 7800 units, 40 container, 1 Barrel)">
<div class="form_division">
<input type="text" name="req_entry" id="req_entry" placeholder="Point of Entry">
<input type="text" name="req_payment" id="req_payment" placeholder="Payment Method">
</div>
<textarea name="post_req" id="post_req" placeholder="Briefly describe your request" rows="6"></textarea><br>
<input type="submit" name="submit_req" id="submit_req" value="Post Request">
</form>
</div>
Thanks in advance.

Related

Ajax is not working when I fetch data from MySQL

I'm building an ecommerce.and for this I'm fetching data products from database, I want to let people add products in cart without refreshing the page, I have tried AJAX but I don't know why but it works only when data is not in a loop, I'm in PHP, and MySQL.
Code:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="upcart(<?php echo $list['id']; ?>)">
</form>
<?php
}
?>
<script>
$(document).ready(function() {
function upcart(id){
e.preventDefault();
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId"+ id).serialize(),
// dataType: "text",
success: function (response) {
alert("success");
}
// return false;
});
};
});
</script>
Use events instead of manually calling the javascript function.
We then don't need to generate id's for the forms since it we will have access to the correct form in the callback.
The PHP part:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" class="some-form-class">
<input type="hidden" name="name" value="value" />
<input type="submit" />
</form>
<?php
}
?>
The JS part:
<script>
$(document).ready(function() {
// Bind the forms submit event
$('.some-form-class').on('submit', function (event) {
event.preventDefault();
// Here we can use $(this) to reference the correct form
$.ajax({
method: "POST",
url: "data.php",
data: $(this).serialize(),
success: function (response) {
alert("success");
}
});
});
});
</script>
NOTE: Magnus Eriksson answer is far cleaner
since function upcart(id) is not in the global scope, onclick="upcart(<?php echo $list['id']; ?>)"> will fail due to the missing function
You need to declare that function in the global scope
Also, you need to prevent the form submission properly
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="return upcart(<?php echo $list['id']; ?>)">
</form>
<?php
note the return upcart .... - very important
NOT INSIDE $(document).ready(function() { since you don't need to wait for document ready to declare a function!
function upcart(id) {
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId" + id).serialize(),
success: function (response) {
alert("success");
}
});
return false; // to prevent normal form submission
}

AJAX not submitting fom

I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});

connecting HTML to PHP file using ajax [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have created an application using xampp (apache and mysql). I have the following HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Name</title>
</head>
<body>
<div id="main">
<h1>Details</h1>
<div id="name">
<h2>Name</h2>
<hr/>
<Form Name ="form1" Method ="POST" ACTION = "name.php">
<label>Name: </label>
<input type="text" name="per_name" id="name" required="required" placeholder="please enter name"/><br/><br />
<label>Age: </label>
<input type="text" name="per_age" id="age" required="required" placeholder="please enter age"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
</div>
</body>
</html>
and the following PHP code:
<?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "details";
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$sql = "INSERT INTO persons (person_name, person_age)
VALUES ('".$_POST["per_name"]."','".$_POST["per_age"]."')";
if ($connection->query($sql) === TRUE) {
echo "person added";
} else {
echo "person not added";
}
$connection->close();
}
?>
Instead of calling the php file using <Form Name ="form1" Method ="POST" ACTION = "name.php"> how would i create a simple ajax file to call the PHP file? i have tried to do this but can't seem to get anywhere, can anyone help me please? AJAX:
$(document).ready(function(){
$("#submit").click(function(){
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "name.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
});
}
return false;
});
});
Better to handle form submit :
Add ID to your form :
<Form id="form1">
Then :
$(document).ready(function(){
$("#form1").submit(function(e) {
e.preventDefault();
$.post('name.php', $('#form1').serialize(), function(data) {
alert(data);
});
return false;
});
In form
remove these in <form>
Method ="POST"
ACTION = "name.php"
add ID in submit button
<input type="submit" value=" Submit" id="submit" name="submit"/>
In AJAX
<script>
$(function(){
$( "#submit" ).click(function(event)
{
event.preventDefault(); # add this ++Important++
var name= $("#name").val();
var age= $("#age").val();
$.ajax(
{
type:"post",
url: "name.php",
data:{ name:name, age:age },
success:function(result)
{
alert(result);
}
});
});
});
</script>

issue with ajax login script

I'm very new to ajax, and I'm trying to make a login script that doesn't require a page reload - it's working well except I attempt to set a session variable on the processing page, but no session variable is set.
My form:
<div class="form-bottom">
<form role="form" class="login-form">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="submit" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
<? echo $_SESSION['Name']; ?>
</div>
My ajax:
<script type="text/javascript" >
$(function() {
$("#submit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+ username + '&password=' + password;
if(username=='' || password=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
});
}
return false;
});
});
</script>
My php script:
include('./static/config.php');
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
I was able to get it working the way I wanted it to.
Form:
<div id="box">
<div class="row">
<div class="col-sm-6 col-sm-offset-3 form-box">
<div class="form-top">
<div class="form-top-left">
<h3>Log-in</h3>
<span id="error" class="error"></span>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
</div>
<div id="box" class="form-bottom">
<form class="login-form" action="" method="post">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="login" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
</div>
</div>
</div>
</div>
AJAX Code:
<script src="js/jquery.min.js"></script>
<script src="js/jquery.ui.shake.js"></script>
<script>
$(document).ready(function() {
$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');},
success: function(data){
if(data)
{
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
else
{
$('#box').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
PHP (ajax/login.php):
<?php
include("../static/config.php");
session_start();
if(isSet($_POST['username']) && isSet($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,$_POST['password']);
$result=mysqli_query($con,"SELECT Name FROM techs WHERE Username='$username' and Password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION['Name']=$row['Name'];
echo $row['Name'];
}
}
?>
Since you've stated you're very new to Ajax, you start off pretty well.
There are however a couple of things to know how this works.
You want to avoid a page refresh, yet you don't print out any responses because you're not returning anything in the ajax request. You instead set a session variable which will show up at the next page request (so a refresh)
$.ajax({
type: 'POST',
url: 'ajax/login.php',
data: { username: $("#username").val(), password: $("#password").val() },
success: function (data) {
$('.form-bottom').html(data); // here we replace the form with output of the ajax/login.php response.
}
});
And for the PHP side of things:
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
if(($result = mysqli_query($con, $sql)) != false){ // always verify if your query ran successfully.
if(mysqli_num_rows($result)){ // or compare with == 1, but assuming a username is unique it can only be 1 so it equals to true.
echo mysqli_fetch_assoc($result)['name']; // index, columns, etc should always be lower cased to avoid confusion.
// Obviously you can store it in a session
// But for now just output the data so we can use it as our response.
// json is very usefull with sending large amounts of data.
}
}
The idea of Ajax is that you can request an update, but you need to update your page with javascript manually in order to make it work.
I think you forget to start the session.So start the session at the top of your script. Hope it will help.
session_start();
include('./static/config.php');
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
3 things you could try:
On the page where you are trying to set the session variable you would have to use proper php opening tags like <?php
Second thing is that you would have to put a value in your session like $_SESSION['hello'] = 'hello';
Third thing, on every page where you handle your session you would have to call <?php session_start(); ?> for it to work.
Goodluck!

AJAX request saves to database but alerts failed

I have a bootstrap modal contact form which uses AJAX and PHP to save the information sent by a user to a database:
<div class="modal fade" id="contact" role="dialogue">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<form id="myform" role="form">
<div class="form-group">
<label for="name">Name: </label>
<input type="name" name="name" class="form-control" id="name" >
</div>
<div class="form-group">
<label for="email">Email: </label>
<input type="email" name="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="msg">Message: </label>
<textarea class="form-control" name="msg" id="msg" rows="10"></textarea>
</div>
<!-- <a class="btn btn-primary" data-dismiss="modal">Close</a> -->
<button id="sub" type="submit" name="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
</div>
When I submit the form the page alerts that the AJAX request has failed but yet the information still saves to the database!? anybody know where I'm going wrong, I have attached my script.js and send.php file below:
Javascript/Ajax file:
$(document).ready(function(){
$('#myform').submit(function(){
$.ajax({
type: 'post',
url: 'send.php',
dataType: 'json',
async: true,
data: $('#myform').serialize(),
success: function(msg){
alert("It was a success");
return false;
},
error: function(jqXHR, textStatus, errorThrown){
alert("Fail");
console.log(jqXHR + '-' + textStatus + '-' + errorThrown);
return false;
}
});
});
});
PHP file for processing and saving to DB
<?php
include 'connect.php';
if(isset($_POST['name'])&&($_POST['email'])&&($_POST['msg']))
{
$sql = "INSERT INTO details (name, email, message) VALUES (:Name, :Email, :Msg)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':Email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':Msg', $_POST['msg'], PDO::PARAM_STR);
$stmt->execute();
echo "done";
}else{
echo "Nothing posted";
}
?>
P.S No errors are output to the console, just the alert saying failed.
according to your javascript, your ajax is expecting to receive a json result, look at this line
dataType: 'json',
but in your php code you are only echoing a string
echo "Nothing posted";
two solutions , delete this code in your javascript dataType: 'json'
or return a json in your php
$data['result'] = "nothing posted";
echo json_encode($data);
As Luis suggests, try to add proper header to the php file which saves to the database and make the output json object like so:
<?php
include 'connect.php';
//The json header
header('Content-type: application/json');
header("Content-Disposition: inline; filename=ajax.json");
if(isset($_POST['name'])&&($_POST['email'])&&($_POST['msg']))
{
$sql = "INSERT INTO details (name, email, message) VALUES (:Name, :Email, :Msg)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':Email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':Msg', $_POST['msg'], PDO::PARAM_STR);
$stmt->execute();
$result = array('success'=>true, 'message'=>'The data has been saved successfuly');
} else {
$result = array('success'=>false, 'message'=>'Can\'t save the data');
}
//Also is a good practice to omit the php closing tag in order to prevent empty characters which could break the posted headers
echo json_encode($result);
I would use the following alias instead of $.ajax, but it's a personal preference:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault(); //Prevent form submission, so the page doesn't refresh
$.post('send.php', $(this).serialize(), function(response){
console.log(response); //see what is in the response in the dev console
if(response.success == true){
//success action
//...some code here...
} else {
//error action, display the message
alert(response.message);
}
});
});
});
Hope that helps

Categories

Resources