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);
?>
201

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 use var 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');

786

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:

$(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";
    }});
});
});

OR like this is you have class="name of the field" among the input parameters:

$(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";
    }});
});
});

OR if you want to use the name directly follow this:

$(document).ready(function() {
$("#x").click(function() {
    var email = $("input[name='email']").val();
    var pass = $("input[name='pasword']").val();
    var confirmPass = $("input[name='confirmPassword']").val();
    var name = $("input[name='name']").val();
    var question = $("input[name='question']").val();
    var answer = $("input[name='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";
    }});
});
});

I hope this helps you

602

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:

$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "...";
$conn->close();

Notice that:

  • you never execute you query.$sql is just a string held in memory.
  • you're mixingmysqli function withmysql_ function (mysql_affected_rows); that won't work
  • You're inserting POST data directly into your queries, so you are very vulnerable to SQL injection
  • At the end, you echo JSON, but you haven't told the browser to expect this format

Do this instead:

$conn = new mysqli(...);
//SQL with ? in place of values is safe against SQL injection attacks
$sql = "INSERT INTO accounts (accountEmail, accountPassword,
          accountName, accountQuestion, accountRecover) VALUES (?, ?, ?, ?, ?)";

$error = null;
//prepare query and bind params. save any error
$stmt = $conn->prepare($sql);
$stmt->bind_param('sssss',$email,$pass,$name,$question,$answer)
        or $error = $stmt->error;

//run query. save any error
if(!$error) $stmt->execute() or $error = $stmt->error;

//error details are in $error
if($error) $response = "Error creating new account";
else $response = "Successfully created new account";

//set content-type header to tell the browser to expect JSON
header('Content-type: application/json');
$pre = ['Response' => $response];
echo json_encode($pre);

People are also looking for solutions to the problem: php - HTTP request using cURL after queuing in Laravel returns null

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.