0

I tried all the solutions in here (How to Pass Variables and Data From PHP to JavaScript) and here (Submit Form Without Reloading Using jQuery AJAX).

What I want to accomplish is that when I submit a form, it gets sent to a .php file without the user getting redirected to the .php file or the website getting restarted.

Then I want PHP to return a value which either says that registration was successful or that something failed (e.g. username is too long or the email is incorrect).

I've been stuck on this for two days now, I've been trying multiple solutions I found including putting the PHP and HTML code in the same file and somehow run the PHP function on submit (and it would display an error message using echo and script tags).

HTML/JS CODE:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    var oReq = new XMLHttpRequest();

    function reqListener() {
      console.log(this.responseText);
    }

    $('#register').submit(function () {
      oReq.onload = function () {
        alert(this.responseText);
      };
      oReq.open("post", "registeruser.php", true);
      oReq.send();
    });
</script>
</head>
<body>
<form id="register" method="post" accept-charset="UTF-8">
  Username:<br>
  <input type="text" name="u_username" id="id_username" required><br>
  First Name:<br>
  <input type="text" name="u_first" id="id_first" required><br>
  Last Name:<br>
  <input type="text" name="u_last" id="id_last" required><br>
  <input type="submit" value="SUBMIT!">
</form>
</body>
</html>

PHP CODE:

<?php

echo "Starting<br>";

submitRegister();

function submitRegister() {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors',1);

function displayAlert($message) {
    echo $json_encode($message);
    die();
}

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $username = $_POST['u_username'];
        $pwd = $_POST['u_firstname'];
        $pwdconfirm = $_POST['u_lastname']);
        // And here go tons of other things like sql/validation/sanitization etc.
        displayAlert("Done.");
    }
    else {
        displayAlert("Failed.");
    }
?>

And yes I know that the AJAX code is completely horrible and invalid, even though I can't seem to find out why.

Marked as Duplicate
  • 1,117
  • 4
  • 17
  • 39

2 Answers2

1

Since you're already loading jQuery, why not just use jQuery? (I've used #register_submit as an id for the click-function, which means you will need to add that id to the submit in the form)

$(document).ready(function() {
 $('#register_submit').click(function(e) {
  e.preventDefault();
  $.post('registeruser.php',$('#register').serialize(),function(data) {
    //parse return data here
  }
 });
});
junkfoodjunkie
  • 3,168
  • 1
  • 19
  • 33
  • I replaced the 'parse return data here' comment with `alert(this.responseText);` (also tried `$('#register').onload`, but didn't work). When I do it with `this.responseText`, I always get "undefined" in the alert box (also tried `this.message`, when I clicked the submit button came a 10-second-pause and just then the undefined message). – Marked as Duplicate Dec 18 '16 at 13:07
  • 1
    First, the return data is named `data` in the function, also you return content from the php file will probably not return properly - have a look at what you do get in return via console in your browser. Echoing out something before you send the json-encoded string doesn't really work. Also, you're not naming the json-element, so the json you do get back will be basically "done" or "failed", without a named key. – junkfoodjunkie Dec 18 '16 at 13:08
  • `this.data` returns 'field1=value1&field2=value2&field3=value3', but what do I have to replace `this.data` with for it to display the actual message? When I open Dev Tools in Chrome and go to Network Tab, record me submitting registeruser.php, click on it and go to the "Response" tab, the message is there. So I believe there has to be a way to show it? Trying to use responseText returns 'undefined'. – Marked as Duplicate Dec 18 '16 at 13:30
  • Then just use data.name_of_field – junkfoodjunkie Dec 18 '16 at 15:47
0

You can use the following method:


  1. On the HTML page, call the PHP page. And parse the json ajax response, and analyze a specific return code. Ex:

    • {code: 0, message: "Success"}
    • {code: 1, message: "Generic error message : failed"}
    • {code: 4: message: "Data not found"}

And to parse the response:

oReq.onload = function () {
  var data = JSON.parse(this.responseText);
  alert('Code ' + data.code);
  alert('Message ' + data.message);
};

  1. On the PHP page: add your code and return value:

Ex:

Header('Content-Type: application/json');
echo json_encode(['code' => $errorCode, 'message' => $message]);
Georges O.
  • 972
  • 1
  • 9
  • 21