-1

On index.php I have a button that calls a function on index.js which has an ajax call in it

on index.php

<div id="forgot" onClick="forgot();">Forgotten Password?</div>

on index.js

function forgot(){
'use strict';
var user = $("#input_1").val();
    jQuery.ajax({ 
       type: "POST", 
       url: "ajax/index_login.php",
       data: 'user='+user+'&action=forgot', 
       cache: false,
       success: function(response) {
          alert(response);
         }
    }); 
}

the php on index_login.php

if($_POST['action'] == 'forgot'){
    $clean['user'] = filter_var($_POST['user'], FILTER_SANITIZE_STRING);
    $sql_data['user'] = mysqli_real_escape_string($mysqli,$clean['user']);
    $sql = "SELECT * FROM user WHERE username = '{$sql_data['user']}'";
    $result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
    $row = mysqli_fetch_assoc($result);
    exit('success');
}

The correct values are being posted but regardless of what value I place in exit() the response is the complete HTML for index.php

tatty27
  • 1,553
  • 4
  • 34
  • 73

1 Answers1

1

You're using jQuery, so you don't need to "hard-code" the onclick event as attribute in the forgot div. So, in "index.php" use just this:

<div id="forgot">Forgotten Password?</div>

Why? You'll see in the following codes.

Since you want to use POST request, then you don't need to build a query string like 'user='+user+'&action=forgot', but an object. How? You'll see in the following codes.

If you want to receive a response, use echo "whatever response string";, not exit("whatever response string");. If you want to make sure that php stops executing after echo-ing the response, then use exit(); after echo "whatever response string";.

There are two methods of using ajax as a correct solution to your question: receiving the response as a JSON encoded content or as a HTML content.

Obs: About the used ajax functions read the notice at the end of the answer.

1) JSON encoded response:

index.js:

/**
 * On document ready.
 * 
 * @return void
 */
$(document).ready(function () {
    activateForgot();
});

/**
 * Activate click event on button "forgot".
 * 
 * @return void
 */
function activateForgot() {
    $('#forgot').click(function (event) {
        var user = $("#input_1").val();

        var ajax = $.ajax({
            cache: false,
            method: 'post',
            dataType: 'json',
            url: "ajax/index_login.php",
            data: {
                'user': user,
                'action': 'forgot'
            }
        });
        ajax.done(function (response, textStatus, jqXHR) {
            alert(response);
        });
        ajax.fail(function (jqXHR, textStatus, errorThrown) {
            alert(textStatus + '<br />' + errorThrown);
        });
        ajax.always(function (response, textStatus, jqXHR) {
            // Whatever you want to do, independent of received response.
        });

        // Important, because it prevents page refresh when a form is used.
        return false;
    });
}

Nota bene:

  • Notice the use of dataType: 'json'.
  • Notice the use of the data object.
  • I didn't tested that cache property, but it should make no difference.

index_login.php:

<?php
if (isset($_POST['action'])) {
    if ($_POST['action'] == 'forgot') {
        if (isset($_POST['user'])) {
            // ...
            echo json_encode('success');
        } else {
            echo json_encode('Please provide a user!');
        }
        exit();
    } else {
        echo json_encode('Not the proper action provided!');
        exit();
    }
} else {
    echo json_encode('Please provide an action!');
    exit();
}

Nota bene:

  • Notice the use of json_encode.
  • Always provide validation on NULL values first.
  • Always provide return values if some condition is not valid. You really don't want to allow the users to see all kind of unhandled errors, which often contain informations about your web server, file system, etc.
  • I didn't tested the use with exit(), but it should be no problem.

2) HTML response:

index.js:

/**
 * On document ready.
 * 
 * @return void
 */
$(document).ready(function () {
    activateForgot();
});

/**
 * Activate click event on button "forgot".
 * 
 * @return void
 */
function activateForgot() {
    $('#forgot').click(function (event) {
        var user = $("#input_1").val();

        var ajax = $.ajax({
            cache: false,
            method: 'post',
            dataType: 'html',
            url: "ajax/index_login.php",
            data: {
                'user': user,
                'action': 'forgot'
            }
        });
        ajax.done(function (response, textStatus, jqXHR) {
            alert(response);
        });
        ajax.fail(function (jqXHR, textStatus, errorThrown) {
            alert(textStatus + '<br />' + errorThrown);
        });
        ajax.always(function (response, textStatus, jqXHR) {
            // Whatever you want to do, independent of received response.
        });

        // Important, because it prevents page refresh when a form is used.
        return false;
    });
}

Nota bene: Just replaced the dataType: 'json' with dataType: 'html'.

index_login.php:

<?php
if (isset($_POST['action'])) {
    if ($_POST['action'] == 'forgot') {
        if (isset($_POST['user'])) {
            // ...
            echo 'success';
        } else {
            echo 'Please provide a user!';
        }
        exit();
    } else {
        echo 'Not the proper action provided!';
        exit();
    }
} else {
    echo 'Please provide an action!';
    exit();
}

Nota bene: Just used echo without json_encode.

Notices/General recommendations:

  • If alert(response); gives you some troubles, use alert(response.toString()). If it still doesn't work, fill a results div with the response content like this: $('#results').html(response);, etc.
  • Always use prepared statements and exception handling in php, especially when you are dealing with the data-access layers.

Here are some answers of interest for you, maybe:

Good luck!

  • Thank you you for taking the time to do this. Although it didn't answer the question it was very useful :) – tatty27 Jun 28 '17 at 17:55