Trying to add form data to a database using an Ajax request with PHP - javascript

I cant quite get my form to add its data to a local database I have setup.
I have a addproducts.php page:
<?php
$title = "Products";
include("Header.php");
include("PHPvalidate.php");
?>
<script src="AjaxProduct.js"></script>
<article>
<section>
<fieldset><legend><span> Add a product to the database </span> </legend>
<form id ="productsform" method="post" onsubmit="return false;">
<input type="hidden" name="submitted" value="true">
<label> Enter a product name: <input type="text" id="name" name="name"/> </label>
<label> Enter a product quantity: <input type="number" id="quantity" name="quantity"/> </label>
<label> Enter a product description: <input type="text" id="description" name="description"/> </label>
<label> Enter a product price: <input type="text" id="price" name="price"/> </label>
<label> Upload a image of the product: <input name="image" accept="image/jpeg" type="file"></label>
<input id="submit" name="submit" type="button" class="reg" value="Add Product">
<div id="check"></div>
</form>
</fieldset>
</section>
</article>
I then have a ajax fetch request to gather up the data to get ready to be posted to the database:
fetch = function () {
var xhr, name, quantity, description, price, target;
xhr = new XMLHttpRequest();
target = document.getElementById("check");
name = document.getElementById("name").value;
quantity = document.getElementById("quantity").value;
description = document.getElementById("description").value;
price = document.getElementById("price").value;
var vars = "name="+name+"&quantity="+quantity+"&description="+description+"&price="+price;
changeListener = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
target.innerHTML = xhr.responseText;
} else {
target.innerHTML = "<p>Something went wrong.</p>";
}
};
xhr.open("POST", "addSQL.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = changeListener;
xhr.send(vars);
}
pageLoaded = function() {
var fetchbutton = document.getElementById("submit");
if(fetchbutton) {
fetchbutton.addEventListener("click", fetch);
}
}
window.onload = pageLoaded;
And finally an addSQL.php
That send the data to the database:
//Stores all information passed through AJAX into the query
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$price = $_POST['price'];
//Adds information to database
$query = "INSERT INTO products (name, quantity, description, price) VALUES ('$name','$quantity','$description','$price')";
//Runs the query
$result = $mysqli->query($query) OR die("Failed query $query");
echo $mysqli->error."<p>";
//
?>
When i try to add dummy data into the form and submit nothing happens with no errors or anything so Im not sure where the point of failure is.
Any help would be appreciated.

I think you're missing this:
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Edit: also now that I look at it, you're vulnerable to SQL injection and an apostrophe in your data will break the query:
$name = $mysqli->real_escape_string($_POST['name']);
$quantity = $mysqli->real_escape_string($_POST['quantity']);
$description = $mysqli->real_escape_string($_POST['description']);
$price = $mysqli->real_escape_string($_POST['price']);

You add some alert() in your code to find the error.
add alert in the every line when you get a value in variable like alert(vars); after the assign value in vars variable

Related

XMLHttpRequest responding with undesired response

I ran into trouble that i have failed to understand at all. I have a sign up form,ajax script and php script.My goal is that,i want to submit data to the php from the sign up form using ajax. My problem is that i can send but do not get the results that i desire as the response.
This is my sign-up form
<form method="post" action="../../includes/seller.inc.php" id="form">
<label for="names">First name and last name: </label><input type="text" name="names" id="names"> <br><br>
<label for="phone">phone number: </label><input type="text" name="phone" id="phone"> <br><br>
<label for="shopName">shop name: </label><input type="text" name="shopName" id="shopName"> <br><br>
<label for="email">Email: </label><input type="text" name="email" id="email"> <br><br>
<label for="pwd">Password: </label><input type="password" name="pwd" id="pwd"> <br><br>
<label for="pwd2">Retype Password: </label><input type="password" name="pwd2" id="pwd2"> <br><br>
<label for="description">Provide a brief Description</label><textarea name="description" id="description" cols="30" rows="5"></textarea> <br><br>
<button type="submit" name="submit">submit</button><br>
</form>
And this is my PHP script(action specified by the form):
$names = mysqli_real_escape_string($conn, $_POST["names"]);
$phone = mysqli_real_escape_string($conn, $_POST["phone"]);
$shopName = mysqli_real_escape_string($conn, $_POST["shopName"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$pwd = mysqli_real_escape_string($conn, $_POST["pwd"]);
$pwd2 = mysqli_real_escape_string($conn, $_POST["pwd2"]);
$description = mysqli_real_escape_string($conn, $_POST["description"]);
//validating the user input data
if(!empty($names && $phone && $shopName && $email && $pwd && $pwd2)){
if (preg_match("/^[a-zA-Z\s]+$/",$names)) {
if (preg_match("/^[0-9+](\d)+$/",$phone)) {
if(preg_match("/^[a-zA-Z\s]+$/",$shopName)) {
if(filter_var($email,FILTER_VALIDATE_EMAIL)) {
if ($pwd !== $pwd2) {
header("Location: ../sell/auth/sell.signup.php?passwordsdoNotMatch");
} else {
$hashed_pwd = password_hash($pwd, PASSWORD_DEFAULT);
$sql = "INSERT INTO seller(name,phone,shopName,email,password,description,approval_status) VALUES ('$names','$phone','$shopName','$email','$hashed_pwd','$description','0');";
if(!mysqli_query($conn, $sql)) {
echo "sorry not added".mysqli_error($conn);
} else {
header("Location: ../index.php");
$_SESSION['actionmsg-success'] = "successfully Added .Wait for approval!! so that you may post your products.";
}
}
And this is the ajax
function loadFunc() {
const names = document.getElementById('names');
const phone = document.getElementById('phone');
const shopName = document.getElementById('shopName');
const email = document.getElementById('email');
const pwd = document.getElementById('pwd');
const pwd2 = document.getElementById('pwd2');
const description = document.getElementById('description');
var form = document.getElementById('form');
form.addEventListener('submit', function (e) {
e.preventDefault();
var params = `names=${names}&phone=${phone},shopName=${shopName},email=${email}&pwd=${pwd}&pwd2=${pwd2}&description=${description}`;
var xhr = new XMLHttpRequest();
xhr.open('post', '../../includes/seller.inc.php');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
if (this.readyState == 4) {
console.log(this.responseText);
}
}
xhr.send(params);
});
}
When running them i dont get an error but i get a response of my own html code printed to the browser.

Submit form with Ajax and insert data to MySQL not working

I am trying to submit a form using PHP and MySQL via Ajax, I am getting alert that form is submitted but no data inserted:
Following my code:
<script>
function myFunction() {
var fname = document.getElementById("fname").value;
var phone = document.getElementById("phone").value;
var faddress = document.getElementById("faddress").value;
var surveyername = document.getElementById("surveyername").value;
var surveyurl = document.getElementById("surveyurl").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'fname1=' + fname + '&phone1=' + phone + '&faddress1=' + faddress + '&surveyername1=' + surveyername + '&surveyurl1=' + surveyurl;
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function(html) {
alert("Form Submitted");
}
});
return false;
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
<label>Name :</label>
<input id="fname" type="text"><br>
<label>Phone :</label>
<input id="phone" type="text">
<label>Address :</label><br>
<input id="faddress" type="text">
<label>Surveyer Name :</label><br>
<input id="surveyername" type="text">
<input id="surveyurl" type="hidden" value="survey-url"><br>
<input id="submit" onclick="myFunction()" type="button" value="Submit">
<button type="submit" class="btn btn-lg custom-back-color" onclick="myFunction()">Submit form</button>
</div>
<!-- PHP code -->
<?php
// Fetching Values From URL
$fname2 = $_POST['fname1'];
$phone2 = $_POST['phone1'];
$faddress2 = $_POST['faddress1'];
$surveyername2 = $_POST['surveyername1'];
$surveyurl2 = $_POST['surveyurl1'];
$connection = mysqli_connect("localhost", "dbuser", "dbpass"); // Establishing Connection with Server..
if($connection === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO form_element (fname, phone, faddress, surveyername, surveyurl) VALUES ('$fname2', '$phone2', '$faddress2','$surveyername2','$surveyurl2')";
if(mysqli_query($connection, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($connection); // Connection Closed
?>
EDIT:
CREATE TABLE form_element(
fname varchar(255) NOT NULL,
phone varchar(255) NOT NULL,
faddress varchar(255) NOT NULL,
surveyername varchar(255) NOT NULL,
surveyurl varchar(255) NOT NULL
);
First,it's bad practice to write parameter directly into your sql,it might led to SQL Injection,you had better use preparestatement to set the parameter.
Just for your problem,the reason is that,you have not pass the parameter directly to the sql
change
$sql = "INSERT INTO form_element (fname, phone, faddress, surveyername, surveyurl)
VALUES ('$fname2', '$phone2', '$faddress2','$surveyername2','$surveyurl2')";
to
$sql = "INSERT INTO form_element (fname, phone, faddress, surveyername, surveyurl)
VALUES ('".$fname2."', '".$phone2."', '".$faddress2."','".$surveyername2."','".$surveyurl2."')";

PHP login and set cookie properly

I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.

Rating script wont update when multiple rate

Hi i am currently making a rating script and i have a few problems
Right now the script "kinda" works -> http://xch07.wi2.sde.dk/sandbox/rating2/index.php
The problem is that if i open up 2 browsers and load image 1 on both browsers and rate the image on both the browsers the last query sent will override anything inbetween so basically in the end only 1 vote out of the 2 is submitted?.
Right now my db looks like this:
id - votes - rating
Currently i just increment the votes with 1 when a vote is submitted
And i raise the raiting with whatever value has ben voted
Could someone tell what i have to do to overcove this problem? and any other thoughs on my code are greatly appreciated :)
OBS: Does anyone have an idea of how i can check if a person has already voted a given image?
HTML
<div class="flex">
<div class="imageWrapper mauto relative fadeInClass">
<img id="imgSrc" src="assets/img/<?php echo $id ?>.png" class="carImg">
<input id="imgValue" class="absolute displayn" type="radio" value="<?php echo $id ?>">
<input id="imgVotes" class="absolute displayn" type="radio" value="<?php echo $votes ?>">
<input id="imgRating" class="absolute displayn" type="radio" value="<?php echo $rating ?>">
<form action="" method="post" class="flex flex-drr absolute bot0 left0">
<input id="vote5" class="vote displayn" type="radio" name="vote" value="5">
<label for="vote5"></label>
<input id="vote4" class="vote displayn" type="radio" name="vote" value="4">
<label for="vote4"></label>
<input id="vote3" class="vote displayn" type="radio" name="vote" value="3">
<label for="vote3"></label>
<input id="vote2" class="vote displayn" type="radio" name="vote" value="2">
<label for="vote2"></label>
<input id="vote1" class="vote displayn" type="radio" name="vote" value="1">
<label for="vote1"></label>
<input type="submit" id="voteSubmit" class="displayn">
</form>
</div>
</div>
Javascript/Ajax
var vote = document.getElementsByClassName('vote');
var voteL = vote.length;
for (let i = 0; i < voteL; i++) {
vote[i].addEventListener('click', function () {
let imgValue = document.getElementById("imgValue");
let imgVotes = document.getElementById("imgVotes");
let imgRating = document.getElementById("imgRating");
let imgValueVal = imgValue.value;
let imgVotesVal = imgVotes.value;
let imgRatingVal = imgRating.value;
let voteValue = vote[i].value;
newImage(imgValueVal, imgVotesVal, imgRatingVal, voteValue);
});
}
function newImage(id, votes, rating, voteValue) {
var http = new XMLHttpRequest();
var url = "pages/newImage.php";
var params = "id=" + id + "&votes=" + votes + "&rating=" + rating + "&voteValue=" + voteValue;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {//Call a function when the state changes.
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
var Data = JSON.parse(this.responseText);
alert(Data.id);
let imgSrc = document.getElementById('imgSrc');
imgSrc.src = Data.imgSrc;
let imgValue = document.getElementById('imgValue');
imgValue.value = Data.id;
let imgVotes = document.getElementById('imgVotes');
imgVotes.value = Data.votes;
console.log(Data.votes);
let imgRating = document.getElementById('imgRating');
imgRating.value = Data.rating;
}
}
http.send(params);
}
THE PAGE AJAX REQUESTS
<?php
require_once '../includes/db.php';
require_once '../includes/functions.php';
$dbCon = dbCon();
//UPDATERE DATABASED
$id = $_POST['id'];
$votes = $_POST['votes'];
$rating = $_POST['rating'];
$voteValue = $_POST['voteValue'];
$votes++;
$rating = $rating + $voteValue;
$stmt = $dbCon->prepare("UPDATE rating SET
votes = ?,
rating = ? WHERE id = " . $id);
$stmt->bind_param('ii', $votes, $rating);
$stmt->execute();
//SENDER NY QUERY AFSTED
define("SQL", "SELECT * FROM rating ORDER BY rand() LIMIT 1");
$result = $dbCon->query(SQL);
$result = $result->fetch_object();
$id = $result->id;
$votes = $result->votes;
$rating = $result->rating;
$imgSrc = "assets/img/" . $id . ".png";
$arr = array('imgSrc' => $imgSrc, 'id' => $id, 'votes' => $votes, 'rating' => $rating);
echo json_encode($arr);
Why don't you replace the prepared statement with the following:
$stmt = $dbCon->prepare("UPDATE rating SET
votes = ?,
rating = rating + ? WHERE id = " . $id);
Held og lykke :-)
By submitting the current rating/votes to your PHP script, you open yourself up to potentially updating your database based on stale information. You can UPDATE values in the database based on current row values, so the following would work as well:
$stmt = $dbCon->prepare("UPDATE rating SET votes = votes + 1, rating = rating + ? WHERE id = ?");
$stmt->bind_param('ii', $_POST['voteValue'], $_POST['id']);
$stmt->execute();
Just amend your query to add 1 to what is currently in the column like this
$stmt = $dbCon->prepare("UPDATE rating
SET votes = votes + 1,
rating = rating + ?
WHERE id = ?");
$stmt->bind_param('ii', $_POST['voteValue'], $_POST['id']);

How to retain the values displayed in the HTML after it is fetch from the PHP?

I have an HTML page that takes the user input and displays the output based on the database. I have a hyperlink to the other pages. I want when I navigate from first page to other HTML page, I add a back button and it shoud return to the first page but it should show the fetched values. Here is the code below.
1st HTML:
<script>
function PostData() {
var online = navigator.onLine;
if(online){
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var userid = document.getElementById("userid").value;
var pid = document.getElementById("pid").value;
// var image = document.getElementById("image").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'login3.php');
//xhr.open('POST', 'config.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("userid=" + userid + "&pid=" + pid);
//xhr.send("&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
else{
alert("You are offline");
}
}
</script>
</head>
<body>
<form>
<label for="userid">User ID :</label><br/>
<input type="text" name ="userid" id="userid" /><br/>
<label for="pid">Password :</label><br/>
<input type="password" name="password" id="pid" /><br><br/>
<div id="div1">
<input type="button" value ="Login" onClick="PostData()" />
</div>
</form>
</body>
PHP:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
?>
2nd HTML:
<body>
<form enctype="multipart/form-data" id="form" action="" method="post">
<input type="file" id="imageid" name="image" onchange="readURL();" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type="button" value="upload" onclick="javascript:uploadInage();" />
BACK
</form>
</body>
I want to retain the values fetched on the 1stHTML.html
It's best to use session. Once the user has completed the first form set a session to signal that, so when they return to the first page it will read the session and automatically redirect them to the necessary page.
You'll need to put this at the top of your 1sthtml.php and 2ndhtml.php page to signal that you want to use sessions:
<?php
session_start();
On your 1sthtml.php page you'll need to set the session information:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
// ---- SET SESSION HERE ---
$_SESSION['stage'] = 1;
}
?>
And then, on the 1sthtml.php again you'll need to check to see if that session variable exists, if it does then forward onto the page you want. So, at the top of your 1sthtml.php, next to your previous session_start():
<?php
session_start();
if (isset($_SESSION['stage'])) {
header('Location: 2ndhtml.php');
exit();
}

Categories

Resources