0

I'm testing Ajax with jQuery but I'm stuck. The ajax script below displays an alert with the message "Not connect. Verify network" (jqXHR.status === 0).

The fact is that the PHP file path specified is definitely correct and that Wamp server is started and works properly. Looks like it finds the PHP file but it won't execute it (Do I have to set parameters with header() in the PHP?).

Here is my .js file:

$(document).ready(function () {     
    $("#connectionButton").click(function () {    
        var formLogin = $('#login').val();
        var formPass = $('#pass').val();            
        $.ajax({
            url:        "http://localhost/cordova_test/check_login.php",
            type:       "POST",
            data:       {login: formLogin, pass: formPass},
            dataType:   "html",

            succes: function (data) {    
                alert("Success: " + data);
            },    
            error: function (jqXHR, exception) {    
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    msg = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    msg = 'Time out error.';
                } else if (exception === 'abort') {
                    msg = 'Ajax request aborted.';
                } else {
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                }    
                alert(msg);
            }
        });
    });
});

I use echo in my PHP script to send back the data (the comments are in french but the code is still in English ;) ):

<?php
    $formLogin = $_POST['login'];
    $formPass = $_POST['pass'];

    /* Connexion */
    require_once('./connexion.php');

    /* Etablissement de la requête */
    $sql = $conn->prepare("SELECT * FROM membre WHERE login = :formLogin AND pass = :formPass;");
    $sql->execute(array(
        'formLogin' => $formLogin,
        'formPass' => $formPass
    ));

    /* Récupération des données */
    $donnees = $sql->fetchAll(PDO::FETCH_ASSOC);

    /* Fermeture de la connexion */
    $sql->closeCursor();

    /* Vérification et renvoi des données */
    if( empty( $donnees ) ) {        
        echo "INCORRECT_LOGIN";
    }
    else {        
        echo $donnees;
    }
?>

I've been looking for a solution for 3 days but I really don't get it.

Bhaumik Pandhi
  • 2,655
  • 2
  • 21
  • 38
  • use `dataType:text,` – guradio May 24 '17 at 14:31
  • Where is the page you're triggering this from being accessed from? Is it on localhost also? – Tom May 24 '17 at 14:36
  • Someone I know would call that a `blessing in disguise` ^^ If you store plain-text passwords on localhost, don't do that online... you should look into PHP built-in function such as `password_hash` [HERE](http://php.net/manual/en/function.password-hash.php) and `password_verify` [HERE](http://php.net/manual/en/function.password-verify.php), then change this from now on and don't waste time : security 1st !... – OldPadawan May 24 '17 at 14:36
  • Yes the html page is also on localhost –  May 24 '17 at 14:37
  • Security first of course, but right now I'm trying to make it work ;) –  May 24 '17 at 14:38
  • can you try first with a small php example like ` – Edwin May 24 '17 at 14:39
  • what's in the console ? any error ? is there a path problem with localhost ? – OldPadawan May 24 '17 at 14:43

2 Answers2

0

I am posting this answer since I assume echo $sql->fetchAll(PDO::FETCH_ASSOC); does not work and is the main cause of this error.

You might want to consider modifying your PHP script to use JSON instead of plain data. This will be much more practical to process in your JavaScript since JSON is natively supported by JavaScript.

Furthermore I am not entirely sure how echo $sql->fetchAll(PDO::FETCH_ASSOC); will behave since normally it should not be possible to echo arrays.

This all could be achieved using this:

JavaScript:

$(document).ready(function () {     
    $("#connectionButton").click(function () {    
        var formLogin = $('#login').val();
        var formPass = $('#pass').val();            
        $.ajax({
            url:        "http://localhost/cordova_test/check_login.php",
            type:       "POST",
            data:       {login: formLogin, pass: formPass},
            dataType:   "json",

            succes: function (data) {    
                alert("Success: " + data);
            },    
            error: function (jqXHR, exception) {    
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    msg = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    msg = 'Time out error.';
                } else if (exception === 'abort') {
                    msg = 'Ajax request aborted.';
                } else {
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                }    
                alert(msg);
            }
        });
    });
});

I use echo in my PHP script to send back the data (the comments are in french but the code is still in English ;) ):

<?php
    $formLogin = $_POST['login'];
    $formPass = $_POST['pass'];

    /* Connexion */
    require_once('./connexion.php');

    /* Etablissement de la requête */
    $sql = $conn->prepare("SELECT * FROM membre WHERE login = :formLogin AND pass = :formPass;");
    $sql->execute(array(
        'formLogin' => $formLogin,
        'formPass' => $formPass
    ));

    /* Récupération des données */
    $donnees = $sql->fetchAll(PDO::FETCH_ASSOC);

    /* Fermeture de la connexion */
    $sql->closeCursor();

    /* Vérification et renvoi des données */
    if( empty( $donnees ) ) {        
        echo json_encode(["status" => "error"]);
    }
    else {        
        echo json_encode(["status" => "ok", "data" => $donnees]);
    }
?>
Pieter De Clercq
  • 1,951
  • 1
  • 17
  • 29
  • what's the answer in here? – Edwin May 24 '17 at 14:35
  • Some good recommendations, but there's no answer for the users actual issue. – Tom May 24 '17 at 14:36
  • @Edwin I assume echo array doesn't work and that is causing it to fail. – Pieter De Clercq May 24 '17 at 14:37
  • write that in your answer – Edwin May 24 '17 at 14:38
  • 1
    @Edwin I wrote it in my answer, first line, even in bold – Pieter De Clercq May 24 '17 at 14:38
  • you edited that :) and to let you know, I'm not the one responsible for the down vote – Edwin May 24 '17 at 14:42
  • So I tried with json_encode() but I still have the same error. The PHP file path is correct. –  May 24 '17 at 14:45
  • @MickaëlDebalme try TEMPORARILY changing the `$_POST` to `$_GET` so you can call your php script directly in your browser using http://localhost/cordova_test/check_login.php?login=login&pass=password, that way you can see if there are any errors in your PHP script. If that works then make sure to change it back to `$_POST` – Pieter De Clercq May 24 '17 at 14:47
  • @MickaëlDebalme are you opening the webpage that contains that JavaScript file using http://localhost/ or using for example file://C:/Users/Mickael/Documents/page.html ? You need to use the first option, the second option will give you Cross Origin Resource Sharing errors. – Pieter De Clercq May 24 '17 at 14:55
  • @thepieterdc I'm using localhost –  May 24 '17 at 14:58
  • Do you see any errors when you open the developer console? In Google chrome (Firefox too?) this can be accessed when pressing the F12 button on your keyboard. – Pieter De Clercq May 24 '17 at 15:00
  • @thepieterdc Nothing in the console. –  May 24 '17 at 15:11
0

This is the error you are suppose to be getting :

Notice: Array to string conversion in...

caused by : echo $donnees;

which is why you don't get the results you want.

this is what you can do :

<script type="text/javascript">
    $(document).ready(function () {     
    $("#connectionButton").click(function () {    
        var formLogin = $('#login').val();
        var formPass = $('#pass').val();            
        $.ajax({
            url:        "http://localhost/cordova_test/check_login.php",
            type:       "POST",
            data:       {login: formLogin, pass: formPass},
            dataType:   "json",
            encode : true,

            succes: function (data) { 

                if(data == "ok"){

                    alert('login succes');
                    setTimeout(' window.location.href = "SecurePage.php"; ', 6000);
                }else{

                    alert("login failed: " + data);                    
                }

            },    
            error: function (jqXHR, exception) {    
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    msg = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    msg = 'Time out error.';
                } else if (exception === 'abort') {
                    msg = 'Ajax request aborted.';
                } else {
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                }    
                alert(msg);
            }
        });
    });
});
</script>

Then php

<?php
    session_start();
    $message ="";
    $formLogin = $_POST['login'];
    $formPass = $_POST['pass'];

    /* Connexion */
    require_once('./connexion.php');

    /* Etablissement de la requête */
    $sql = $conn->prepare("SELECT * FROM membre WHERE login = :formLogin AND pass = :formPass;");
    $sql->execute(array(':formLogin' => $formLogin,':formPass' => $formPass));

    /* Récupération des données */
    $donnees = $sql->fetchAll(PDO::FETCH_ASSOC);

    if(count($donnees) > 0){

        foreach($donnees as $key=>$row){

            $message = "ok";
            $_SESSION['member'] = $row['memberID'];

            //everything is ok no need to display the result to the user just start the session and redirect the user to the next page in the ajax success
//set all the things you need here that u gonna need on other pages
        }

    }else{

        $message = "Unknow account";
    }

    echo json_encode($message);
?>

PS: You should not be storing passwords in plain text, use password_hash() and password_verify() available from the manual.

Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34
  • I can't do it this way (using sessions) because I'm making a Cordova (PhoneGap) app. So once deployed, the ajax will not be on a server anymore, and it will connect to a distant server to call the php. That's why I need to get my data back to ajax. –  May 24 '17 at 15:01
  • but you are just alerting the data u not doing anything about it @MickaëlDebalme – Masivuye Cokile May 24 '17 at 15:03
  • @MickaëlDebalme if u not gonna use sessions how you gonna identify logged in users? – Masivuye Cokile May 24 '17 at 15:20
  • I'm just using JavaScript (with Cordova I don't imagine an other possibility) –  May 24 '17 at 15:29