0

I'm having a HTML page where you can enter a password to be redirected to an intern page called "Files.php". If the entered password is wrong, I give a feedback in my form, if it is correct, I want to redirect to the intern page.

My HTML looks like this:

<form name="download" id="download">
                        <label for="password">Passwort</label><br>
                        <div id="wrongpassword"></div>
                        <input type="password" id="password" name="password" required> <br>
                        <input type="submit" id="submit" value="Download">
</form>

My AJAX request like this:

$(document).ready(function () {

        var request;

        $("#download").submit(function(event){


            event.preventDefault();

            var $form = $(this);

            var $inputs = $form.find("input, select, button, textarea");

            var serializedData = $form.serialize();

            $inputs.prop("disabled", true);

            request= $.ajax({
                url: "download.php",
                type: "post",
                data: serializedData
            });


    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        if(response=="Success"){
            window.location.replace("Files.php");
        }else{
            $("#wrongpassword").html(response);
        } });});

And my PHP like this:

<?php


session_start();
$db = new PDO('mysql:host=localhost;dbname=nachhilfe', 'root', 'secret');



/*if(!$db)
{
exit("Verbindungsfehler: ".mysqli_connect_error());
}
else{
    echo "Success!";
}*/

$pw = ($_POST['password']);

$statement = $db->prepare("SELECT passwort FROM downloads WHERE id= :id");
$result = $statement->execute(array(':id' => 4));
$stored = $statement->fetch();

if(password_verify($pw, $stored['passwort'])){
    $_SESSION['verified'] = true;
    echo "Success";
}
else{
    echo "Wrong password";
}?>

So far, everything is working, except from the response compare if(response=="Success"), which is always false.

How can i compare my AJAX response or is there a nicer way to achieve the redirect?

Q.uestion
  • 183
  • 1
  • 11
  • Try `data: {password: $('#password')}` – RiggsFolly Mar 15 '18 at 16:16
  • Where should I put it? Sorry, but im relatively new to PHP and especially AJAX. – Q.uestion Mar 15 '18 at 16:20
  • put it instead of `data: serializedData` – Jeff Mar 15 '18 at 16:26
  • Why just not do a `success()` function in the ajax call `success: function(response){alert(response); }` Then in your php at the top just do `die(print_r($_POST,1));` and see if that pops up in the alert. Also before that, put `ini_set('display_errors',1); error_reporting(E_ALL);`. If things show up, then from there you should be able to determine where it's going wrong by moving the `die()` line down to key parts of your PHP until something doesn't return into the alert. Then you know at that point is where it breaks. – Rasclatt Mar 15 '18 at 16:28
  • The only thing that changes with `data: {password: $('#password')}`, is that it seems to be slower... But still not the desired behaviour :( – Q.uestion Mar 15 '18 at 16:54
  • I would leave what you have for that part alone. Serializing the form is fine, as long as `console.log(serializedData);` produces the form data, leaving that serialized is fine. – Rasclatt Mar 15 '18 at 16:56
  • The serializing and verifying totally works. I'm just not sure about how to redirect on success and how to put out the error message on failure. – Q.uestion Mar 15 '18 at 17:10
  • But do you get content in the `response` or no? – Rasclatt Mar 15 '18 at 17:12
  • Yes, if i enter the correct password, i get "Success" written in my form and if i enter the wrong one i get "Wrong password", so my php is working. But I cant compare the response with "Success" for example, cause this never is "true". – Q.uestion Mar 15 '18 at 17:16
  • Oh, so `if(response=="Success")` is not working in your js then is what you are saying? – Rasclatt Mar 15 '18 at 17:20

1 Answers1

0

Based on the comments, I would maybe try using a json string:

$("#download").submit(function(event){
    event.preventDefault();
    var $form = $(this);
    var $inputs = $form.find("input, select, button, textarea");
    var serializedData = $form.serialize();
    $inputs.prop("disabled", true);
    $.ajax({
        url: "download.php",
        type: "post",
        data: serializedData,
        dataType: 'json',
        success: function(response) {
            if(response.success === true){
                window.location.replace("Files.php");
            }
            else {
                $("#wrongpassword").html(response.msg);
            }
        }
    });
});

Then in the php:

<?php
session_start();
$db        = new PDO('mysql:host=localhost;dbname=nachhilfe', 'root', 'secret');
$pw        = $_POST['password'];
$statement = $db->prepare("SELECT passwort FROM downloads WHERE id= :id");
$result    = $statement->execute(array(':id' => 4));
$stored    = $statement->fetch();

if(password_verify($pw, $stored['passwort'])){
    $_SESSION['verified'] = true;
}
# Create a response array
# Note, I am using new syntax for array, you can use array('success'=>false,'msg'=>'Bad Password') if using an unsupported version
$response = (!empty($_SESSION['verified']))? ['success'=>true,'msg'=>'Success'] : ['success'=>false,'msg'=>'Bad Password'];
# Send back the json string to ajax
# Die so you don't get any empty space afterwards by accident
die(json_encode($response));

Also at the end of the document, if it ends in php, you don't have to close using ?>. You only need to close it if the script will break to html content such as:

?> <div>Stuff</div>

Here is an explanation of the benefits of this: PHP end tag "?>"


EDIT:

Since you can get {"success":true,"msg":"Success"} when commenting the dataType: 'json' line, try this version for the ajax:

    $.ajax({
        url: "download.php",
        type: "post",
        data: serializedData,
        success: function(response) {
            // Parse here
            var json = JSON.parse(response);
            // You should get an object now
            alert(json.msg);
            // Now you should be able get the boolean here
            if(json.success === true){
                // Try redirecting this way here
                window.location = "Files.php";
            }
            else {
                $("#wrongpassword").html(json.msg);
            }
        },
        error: function(response) {
            alert(response);
        }
    });
Rasclatt
  • 12,498
  • 3
  • 25
  • 33
  • Thank you for your answer and your additional information about the closing tag. Unfortunately, this solution does not generate any feedback at all for me and does not redirect either. – Q.uestion Mar 15 '18 at 19:00
  • Hmm..strange. Comment out this line: `dataType: 'json',` then do `console.log(response);` in the success. See if it comes back a string – Rasclatt Mar 15 '18 at 19:02
  • Do you have this in a live space or just local? – Rasclatt Mar 15 '18 at 19:02
  • Local running on Xampp – Q.uestion Mar 15 '18 at 19:04
  • did you try commenting out the line above and seeing if there was output from `response`? You should get back (in a string) `{"success":true,"msg":"Sucess"}` from `response`. – Rasclatt Mar 15 '18 at 19:05
  • I do get `{"success":true,"msg":"Success"}` – Q.uestion Mar 15 '18 at 19:07
  • Alright, then if you uncomment that line again, then in the console log, you should get that same thing, only not as a string but rather an object so `alert(response.msg);` should come back as `Success` in an alert. Does that happen? – Rasclatt Mar 15 '18 at 19:09
  • No, I don't get any alert :/... Like it's not even triggering. – Q.uestion Mar 15 '18 at 19:12
  • Wait, sorry, made a mistake...one second – Rasclatt Mar 15 '18 at 19:18
  • Ok now try. the parameter `json` should be what `response` was supposed to be returned as, which is an data object. – Rasclatt Mar 15 '18 at 19:19
  • so like `alert(json.msg)`? – Q.uestion Mar 15 '18 at 19:39
  • Yeah, `json` should be an object `{"success":true,"msg":"Sucess"}` and so it should have two keys `msg` and `success` so that should write the message from the PHP. – Rasclatt Mar 15 '18 at 19:41
  • Now i do get an alert which says "undefined" – Q.uestion Mar 15 '18 at 19:43
  • Man, this is not as straight-forward as it should be! See what `console.log(json)` is. See if it's empty or what it is exactly. It should be an object, not string – Rasclatt Mar 15 '18 at 19:46
  • The same output: `{"success":true,"msg":"Success"}` – Q.uestion Mar 15 '18 at 19:49
  • Maybe I did something wrong. This is what I have ` request= $.ajax({ url: "download.php", type: "post", data: serializedData, dataType: 'json', success: function(json) {console.log(json);if(response.success === true){ window.location.replace("Files.php"); } else { $("#wrongpassword").html(response.msg); } }` – Q.uestion Mar 15 '18 at 20:15
  • Replace that entire block you just wrote with the second example I gave (you can just comment out your block with `/* your code here */` so you don't lose it. See what happens – Rasclatt Mar 15 '18 at 20:17
  • I do get the following error message: Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at Object.success (Login.html:228) at u (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at k (jquery.min.js:2) at XMLHttpRequest. (jquery.min.js:2) – Q.uestion Mar 15 '18 at 20:26
  • Line 228 is `var json = JSON.parse(response);` – Q.uestion Mar 15 '18 at 20:28
  • Now I dont get an error, but again nothing is happening. – Q.uestion Mar 15 '18 at 20:34
  • `Unexpected token <` means that your PHP is likely sending an error/warning back in the form of html wrecking the json string. `<` indicates the beginning of the html as in `Warning...etc.` – Rasclatt Mar 15 '18 at 20:36
  • Although this `` inside the `json_encode()` is strange...let me try this on my server. – Rasclatt Mar 15 '18 at 20:38
  • i added `dataType: 'json',` and now i dont get an error but also nothing happens – Q.uestion Mar 15 '18 at 20:40
  • I am almost positive it's your PHP having a warning. When you do the `dataType: 'json'` you are just bascially allowing jQuery to parse, so if you get nothing back, it's because it can't parse the return from the php as json. Add error to the ajax (see my edit) – Rasclatt Mar 15 '18 at 20:44
  • Here is a demo of the script exactly as written: http://www.iwantcreative.com/test.php – Rasclatt Mar 15 '18 at 21:01
  • okay, so now I worked on it, and i do get alert messages like "Success". But if I type a wrong password, i get redirected and if i enter the right one, i get an error message – Q.uestion Mar 15 '18 at 21:14