Submit form with Ajax and insert data to MySQL not working - javascript

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."')";

Related

Ajax is not sending data to PHP

I'm new at ajax and i am confused becouse i think my ajax file is not sending data to php file or php is not getting it, IDK, Help me please
This is the form
<form id="register-form" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="text" name="email" id="email" tabindex="1" class="form-control" placeholder="Email Address" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="password" name="confirm-password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
</div>
</div>
</div>
</form>
This is the .js
$(document).ready(function(){
$("#register-submit").click(function(){
var email = $("#email").val();
var username = $("username").val();
var password = $("password").val();
$.ajax({
type: "POST",
url: "register.php",
data: "email="+email+"&username="+username+"&password="+password,
success:function(data){
alert("succes");
}
});
});
});
This is the .php
<?php
require_once("functions.php");
$email = $_POST["email"];
$username $_POST["username"];
$password $_POST["username"];
mysqli_query($connection, "INSERT INTO users(email, username, password) VALUES('$email', '$username', '$password')");?>
First of all:
var username = $("username").val();
var password = $("password").val();
Should be:
var username = $("#username").val();
var password = $("#password").val();
data: "email="+email+"&username="+username+"&password="+password
Should be:
data: {email: email, "username": username, password: password}
And
$username $_POST["username"];
$password $_POST["username"];
Should be:
$username = $_POST["username"];
$password = $_POST["password"];
You have to send the data in JSON format like:
var data = { "email": email, "username": username, "password": password };
so pass data var in data Ajax function!
1st: instead of using submit input click event you can use form submit event
$("#register-form").on('submit',function(){
and while you use a submit sure you need to prevent the page from default reload .. I think you problem is this point .. so you need to prevent the form by using e.preventDefault(); you can use it like
$("#register-form").on('submit',function(e){
e.preventDefault();
// rest of code here
$(document).ready(function(){
$("#submit").click(function(event) {
event.preventDefault();
var inputEmail = $("#email").val();
var inputUsername = $("#username").val();
var inputPassword = $("#password").val();
$.ajax({
type: "POST",
url: "register.php",
data: ({ email: inputEmail, password: inputPassword, username: inputUsername}),
success: function(data){
var obj = jQuery.parseJSON(data);
alert("Success " + obj.username + " " + obj.password + " "+ obj.email);
}
});
});
});
Here in .js file I put at the top in .click(function(event) { event.preventDefault(); }
preventDefault();
this function prevent the page from realoding when you press the submit button
data: ({ email: inputEmail, password: inputPassword, username: inputUsername})
Here i send the data data: ({nameOfTheVarieableYouWantToReadWithPHP: nameOfTheVariableFromJs})
Here is the .php file
require_once("database.php"); //require the connection to dabase
$email = protect($_POST['email']); //This will read the variables
$username = protect($_POST['username']); //sent from the .js file
$password = protect($_POST['password']); //
$result = array(); //This variable will be sent back to .js file
//check if the variables are emtpy
if(!empty($email) && !empty($username) && !empty($password)){
//db_query is my function from database.php but you can use mysqli_query($connectionVariable, $sqlString);
db_query("INSERT INTO users (email, username, password) VALUES ('$email','$username','$password')"); //Here insert data to database
//we will set array variables
$result['username'] = $username; //Here we set the username variable fron the array to username variable from js
$result['password'] = $password; // the password same as the username
$result['email'] = $email; //the email same as the username and password
}else{ // if the variables are empty set the array to this string
$result = "bad";
}
echo json_encode($result); //transform the result variable to json
In the .js file
success: function(data){
var obj = jQuery.parseJSON(data); //create a variable and parse the json from the php file
//You can set the variables get from the json
var usernameFromPhp = obj.username;
var passwordFromPhp = obj.password;
var emailFromPhp = obj.email;
alert("Success " + usernameFromPhp + " " + passwordFromPhp + " "+ emailFromPhp);//
}

Form not running PHP

So I'm working on an assignment for my class in which I am supposed to take a username and password and check it against a list contained in a table on a database I am connecting too.
Problem is when I am clicking the submit button nothing is happening I think this is likely to be some sort of error in syntax. Since I am new to PHP there is a good possibility it is something obvious, but not so much to me.
I have my database data stored in two PHP arrays (one for each field). I then converted the arrays to json which I will use in my JavaScript function that will be checked against the user inputted data.
I am including a form, a PHP script, and a JavaScript script in one document could this cause the issue?
Here is my code and thank you for any help!
<html>
<body>
<?php
/*config is included in order to protect my login info*/
require('config.php');
Echo "Project 4";
/*SQL connection*/
$conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
/*Checking Connection*/
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM p4Data";
$data2 = mysqli_query($conn, $sql);
/*Display Data*/
echo "<table border = 1 style='float:left'>
<tr>
<th>Username</th>
<th>Password</th>
</tr>";
//Array Declarations
$usernameArr = [];
$passwordArr = [];
while($records = mysqli_fetch_array($data2)){
array_push($usernameArr,$records["username"]);
array_push($passwordArr,$records["password"]);
}
echo "</table>";
//JSON Conversion
$usernameJson = json_encode($usernameArr);
$passwordJson = json_encode($passwordArr);
mysqli_close($conn);
?>
<!-- JAVA SECTION -->
<script type="text/javascript">
var obj = JSON.parse('<?= $usernameJson; ?>');
var obj2 = JSON.parse('<?= $passwordJson; ?>');
function verifUser(){
var usernameData = document.getElementById("username").value;
var passwordData = document.getElementById("password").value;
for (i = 0; i < 30; i++){
if(usernameData == obj[i]){
alert("Username verfied at " + i);
indexLocated = i;
break;
}
}
}
</script>
<form name='form-main'>
Username: <input type="text" id="username"><br>
Password: <input type="password" id="password"><br>
<input type="button" value="Login >>" id="submitButton"
onclick="verifUser()">
</form>
</body>
</html>
You can use post method to get the value of user input like this
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" value="login">
</form>
and use this php code to get value when form is submitted
if(isset($_POST['submit'])){
$username_input = $_POST['username'];
$password_input = $_POST['password'];
}
Then make a query to sql where username = $username and password = $password. Like below
$sql query = " SELECT * FROM TABLE WHERE username = $username and password = $password";
And use
$num_rows = mysqli_num_rows($sql_query);
Now do a check of $num_rows = 1 that means input username and password is valid else echo Not valid
if($num_rows = 1){
**some code **
}else{
echo "Invalid information provided";
};

back-end error_msg is not giving a alert..!

I am using jquery to make a .php file execute but my major problem is when ever a error is thrown from back-end i used a alert to display that error_msg..but ever i submit with a error intentionally...its just moving on to page specified in action...no error alert poped up...plz help me out of this.!!pardon me if am wrong
here gose the DB_Function.php
<?php
class DB_Functions {
private $db;
// constructor for database connection
function __construct() {
try {
$hostname = "localhost";
$dbname = "miisky";
$dbuser = "root";
$dbpass = "";
$this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e)
{
die('Error in database requirments:' . $e->getMessage());
}
}
/**
* Storing new user
* returns user details of user
*/
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
return false;
}
/*to check if user is
already registered*/
public function isUserExisted($email) {
try{
$sql = "SELECT email FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
}
/*to check if user
exist's by mobile number*/
public function isMobileNumberExisted($mobile){
try{
$sql = "SELECT mobile FROM users WHERE mobile = '$mobile' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch(Exception $e){
die('Error accessing database: ' . $e->getMessage());
}
}
//DB_Functions.php under construction
//more functions to be added
}
?>
here gose the .php file to be clear on what am doing..!!
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate your password
if(strlen($password) > 6){
//validate your mobile
if(strlen($mobile) == 12){
//Check for valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
if($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}
} else {
$response["error"] = true;
$response["error_msg"] = "Mobile number is invalid!";
echo json_encode($response);
}
} else {
//min of 6-charecters
$response["error"] = true;
$response["error_msg"] = "password must be of atleast 6-characters!";
echo json_encode($response);
}
} else {
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
} else {
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
and here gose the main file .js
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
e.preventDefault();
}
});
});
});
and here gose the corresponding .html file
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="6Lc4vP4SAAAAABjh8AG"></div>
<!-- End Thumbnail-->
</div>
<?php include("js/captcha.php");?>
</div>
<div class="form-group">
<div cle the terms and policy </label></div>
</div>ass="checkbox i-checks"><label> <input type="checkbox"><i></i> Agre
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
<
/form>
From the comments:
So only after displaying Registeration successful! I want to submit the form and redirect it to login.html
Well the solution is quite simple and involved adding and setting async parameter to false in .ajax(). Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.
Your jQuery should be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
So the form will only get submitted if the registration is successful, otherwise not.
Edited:
First of all make sure that <!DOCTYPE html> is there on the top of your page, it stands for html5 and html5 supports required attribute.
Now comes to your front-end validation thing. The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method.
For the purpose of simplicity I removed your terms and conditions checkbox and Google ReCaptcha. You can incorporate those later in your code.
So here's your HTML code snippet:
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required />
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required />
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required />
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required />
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required />
</div>
<!--Your checkbox goes here-->
<!--Your Google ReCaptcha-->
<input type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b" value="Register" />
</form>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
And your jQuery would be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
var status = $('form')[0].checkValidity();
if(status){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
$('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
your form submit takes action before ajax action so its reloading the page and use form submit instead of submit button click
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
Ok steps to be sure that everthing works fine while you try to use ajax
1st : use form submit and use e.preventDefault(); to prevent page reloading
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
alert('Form submited');
});
if the alert popup and form not reloading the page then the next step using ajax
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
$.ajax({
url: "register.php",
type: "POST",
dataType: "JSON",
data: {success : 'success'},
success : function(data){
alert(data);
}
});
});
and in php (register.php)
<?php
echo $_POST['success'];
?>
this code should alert with "success" alert box .. if this step is good so now your ajax and php file is connected successfully then pass variables and do another stuff

Issue receiving a response using AJAX, jQuery and PHP

I am trying to figure out how to send values and receive the right response.
The only response that I can seem to get is 0.
This is the AJAX and form I am sending with:
<script type="text/javascript">
$(document).ready(function(){
$(':submit').on('click', function() {
var email = $("#txtEmail").val();
var password = $("#txtPassword").val();
$.ajax({ // ajax call starts
url: 'isValid.php',
data: {'email': $("#txtEmail").val(),
'password': $("#txtPassword").val()
},
dataType: 'json', // Choosing a JSON datatype
})
.done(function(data) {
$('#valid').html(data);
});
return false;
});
});
</script>
<form method="post" action="">
Email:<br/>
<input id="txtEmail" name="txtEmail" type=text/><br/>
Password:<br/>
<input id="txtPassword" name="txtPassword" type=text/><br/>
<input type="submit" value="Login"/>
<input type="reset" value="Clear"/>
</form>
<div id="valid"></div>
This is the php script I am using to try and send the response back:
<?php
$email = $_GET["login"];
$pass = $_GET["password"];
print json_encode($email + " " + $pass);
?>
All I am getting back is a 0 and am not sure why.
Thats because you are concatenating wrongly your response, and you have wrong parameters in your get:
<?php
$email = $_GET["email"];
$pass = $_GET["password"];
print json_encode($email . " " . $pass);
?>

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

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

Categories

Resources