0

What I want to do is: when a user types their email, my ajax code will run and show the user pass in the password inputbox.

The problem is that while my ajax code is sending the email to search.php, my search.php isn't giving the data to my ajax to show.

I think the problem is in my search.php because when i go to search.php after i type an email in my index the search.php is just blank no data is showing.

Index (Form):

email <input type="text" id="query" name="myemail" class="search_textbox" /><br />
Your Password <input type="text" id="mypass" name="mypass" readonly="readonly" /><br />
<script>
$(document).ready(function(){
    $('.search_textbox').on('blur', function(){
                $('#query').change(updateTextboxes);
                updateTextboxes()  
            })
    $('.search_textbox').on('keydown', function(){
                $('#query').change(updateTextboxes); 
                updateTextboxes() 
            })
    $('#query').change(updateTextboxes);

    var  $mypass = $('#mypass');

    function updateTextboxes(){
        $.ajax({
        url:"search.php",
        type:"GET",
        data: { term : $('#query').val() },
        dataType:"JSON",
        success: function(result) {

        var ii = 1;

        for (var i = 0; i < result.length; i++) { 
                    $mypass.val(result[i].value).show().trigger('input');                           
            ii++;
            }

        }


    });


};



});      
</script>

search.php

<?php
error_reporting(-1);
ini_set('display_errors', 'On');

$host = "localhost";
$user = "root";
$pass = "";
$db = "test";

$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (isset($_GET['term'])) {

    $q = $_GET['term'];

    $sql = "SELECT password FROM students WHERE email = :term";
    $query = $dbc->prepare($sql);
    $query->bindParam(':term', $q);
    $results = $query->execute();

    $data = array();

    while ($row = $results->fetch()) {
        $data[] = array(
            'value' => $row['password'] 
        );
    }

    header('Content-type: application/json');
    echo json_encode($data);

}

?>
user3842025
  • 75
  • 1
  • 1
  • 8
  • Try to `echo $_GET['term'];` to know whether you are getting the value from `index.php`. – afaolek Jul 16 '14 at 11:11
  • @afaolek i tried it and it echo the email that i type in the index page – user3842025 Jul 16 '14 at 11:58
  • **3 things**. **first**: i would use `POST` instead of `GET`!, **second**: add a `print_r($result);` after execute and **third**: what do you think how many passwords one user have? i think just one so you don't really need a while loop. and `while` isn't needed anyway. if you expact more than one result, use `$results->fetchALL()`. Oh and `header('Content-type: application/json');` not needed – Dwza Jul 16 '14 at 12:12
  • @Dwza i use while to fetch all and put all the values in an array and send it to ajax to show the password value in and inputbox if the user type his registered email. – user3842025 Jul 16 '14 at 12:56
  • The statement `$results = $query->execute();` returns a `bool`. Check [here](http://php.net/manual/en/pdostatement.execute.php); – afaolek Jul 16 '14 at 12:56
  • @Dwza im doing this so that if the user forgot his password he just need to type his registered email in the website and il make a function to send it to his email address his password. – user3842025 Jul 16 '14 at 12:58
  • Actually, it's not safe to store raw passwords. Try Binging [forgotpasswordphp](http://www.bing.com/search?q=forgot+password+implementation+php) – afaolek Jul 16 '14 at 13:07
  • @afaolek il need it so that i can send his password to his email after typing his email to retrieve if he forgot his password. – user3842025 Jul 16 '14 at 13:10
  • don't save the password plain text. make a md5($password) befor saving to DB. if usere looses password, send him a link where he can set his password new. otherwise you will have a lot of unregistrations :D and you use `SELECT password FROM students WHERE email = 'foo@bar.de'`. first i hope email is a unique column :) this results exact 1 return value! so no while needed. and like i sayed befor, if you expact more values, use fetchALL – Dwza Jul 16 '14 at 13:46
  • @Dwza `md5()` should ***not*** be used for passwords. It's so overused and easily broken. For PHP >= 5.5 you should use [`password_hash()`](http://us1.php.net/password_hash). For PHP > 5.37 but < 5.5 you should use [`bcrypt()`](http://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php). – War10ck Jul 16 '14 at 14:10

1 Answers1

0

I noticed header('Content-type: application/json');. I don't think it is necessary. Remove the line and try again. I am not sure but I think php header is needed for a new page. Since you have echo json_encode($data); and in your AJAX call, you are already processing the return data as json, the header(...) is not needed.

EDIT

$q = $_GET['term'];

$sql = "SELECT password FROM students WHERE email = :term";
$query = $dbc->prepare($sql);
$query->bindParam(':term', $q);
if($query->execute() && $query->rowCount()){
    echo json_encode($query->fetch(PDO::FETCH_ASSOC));   
}

SCRIPT

function updateTextboxes(){
    $.ajax({
    url:"search.php",
    type:"GET",
    data: { term : $('#query').val() },
    dataType:"JSON",
    success: function(result) {
        //check here if you have a result, if yes than...
        $("#mypass").val(result.password);
    }
}
afaolek
  • 8,452
  • 13
  • 45
  • 60
  • i got this error now "Fatal error: Call to a member function fetch() on a non-object " – user3842025 Jul 16 '14 at 12:00
  • I just noticed you were not properly processing the result as `json` in your `success` callback. in a minute, I will update my answer to account for that. – afaolek Jul 16 '14 at 12:02
  • Better still, read this [question](http://stackoverflow.com/questions/7089368/how-to-process-json-using-jquery-javascript). – afaolek Jul 16 '14 at 12:05
  • just wanted to make a post, but at the moment i wanted to start, you made an update :D could save a row if using `$results->rowCount()`direktly in the if. Like: `if($result)` or `if ($result->rowCount())`. don't know if the first one would work but i think. – Dwza Jul 16 '14 at 12:17
  • @afaolek error in ur code "Fatal error: Call to a member function rowCount() on a non-object". – user3842025 Jul 16 '14 at 12:45
  • @afaolek i want to pass the value of the password to ajax to show it in the inputbox in index page. – user3842025 Jul 16 '14 at 12:46
  • @afaolek i use array cuz i want the real value of the password not a binary result – user3842025 Jul 16 '14 at 12:47
  • Found the error. Editing my answer again. There are comments in front of the edits. – afaolek Jul 16 '14 at 12:53
  • @afaolek i saw the value of the password in search.php now but how come it doesnt show in inputbox in my index page? Is there wrong in my ajax script in receiving the value? – user3842025 Jul 16 '14 at 13:04
  • 1
    It's never a bad thing to specify a header like the one above. Technically, to be correct symantically, I believe you're supposed to pass along a header in the response. – War10ck Jul 16 '14 at 14:07
  • Omitting the header will probably work in some cases. But adding a header has some benefit and will not cause any problems. So leave it in. If you don't have it you are technically sending the results as malformed html. – mcrumley Jul 16 '14 at 14:30