javascript - PHP post request unidentified index error
977
I'm trying to write a page to make a POST request to a php script and I feel like I've done it right, it's worked everywhere else so it seems but I keep getting a "unidentified error" and it won't work, how can I get this to work?
Javascript:
$(document).ready(function() {
$("#x").click(function() {
var email = $("email").val();
var pass = $("password").val();
var confirmPass = $("confirmPassword").val();
var name = $("name").val();
var question = $("question").val();
var answer = $("answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "*********";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$email = $_POST["email"];
$pass = $_POST["pass"];
$name = $_POST["name"];
$question = $_POST["question"];
$answer = $_POST["answer"];
$sql = "INSERT INTO accounts (accountEmail, accountPassword, accountName, accountQuestion, accountRecover) VALUES ('$email', '$pass', '$name', '$question', '$answer')";
$conn->close();
if(mysql_affected_rows() > 0) {
$response = "Account added successfully!";
}
else {
$response = "Couldn't add account!";
}
$pre = array("Response" => $response);
echo json_encode($pre);
?>
Answer
Solution:
You need to properly use jquery.
For example
var email = $("email").val(); //IS WRONG
Should be (if you have input id="email")var email = $("#email").val();
If you have only name you can usevar email = $("[name='email']").val();
A bit offtopic: If you are using form ajax submit consider jquery method serialize https://api.jquery.com/serialize/ for getting all form values (or some jquery ajaxform plugin).
And please! don't make insecure mysql statements. For gods sake use prepared statements. If you need very basic stuff just use prepared statements or consider https://phpdelusions.net/pdo/pdo_wrapper
Also a small tip: before echo json make json header
<?php header('Content-type:application/json;charset=utf-8');
Answer
Solution:
I think you are mistaken with your jquery data, they should have identifier like id denoted by '#' and classes denoted by '.', do it this is you have id="name of the field" among the input parameters:
OR like this is you have class="name of the field" among the input parameters:
OR if you want to use the name directly follow this:
I hope this helps you
Answer
Solution:
There are lots of reasons your code is not working. @AucT and @gentle have addressed your Javascript side issues so I'll focus on PHP. Your query code is:
Notice that:
$sql
is just a string held in memory.mysqli
function withmysql_
function (mysql_affected_rows
); that won't workDo this instead: