0

I have a form like this:

<form action="process.php" method="post">
    <input type="text" name="input" />
    <button type="submit">Submit</button>
</form>

And I have an Ajax script like this:

$("button").click(function(event) {
    var $ajaxData = {
        "input-val" : $("input").val();
    }

    $.ajax({
        type : "POST",
        url : "process.php",
        data : $ajaxData,
        dataType : "json",
        encode : true
    });
    .done(function($data) {
        alert($data["stat"]);
    });

    event.preventDefault();
    $("form").unbind();
});

Also a PHP script (process.php) where the form data is send:

<?php
if(isset($_POST['input-val'])) {
    $data['stat'] = 'success';
    echo json_encode($data);
}
?>

All is correct and set, but, if I want to stop the users of seeing or going (manually) to the "process.php" page I add a redirect function:

<?php
if(isset($_POST['input-val'])) {
    $data['stat'] = 'success';
    echo json_encode($data);
}
header('Location: index.php');
?>

That makes Ajax's request fail automatically. How can I stop users of going or seeing the PHP script?
As I said, the "event.preventDefault();" is stopping Ajax of sending the users to the PHP script, but users can go there by themselves.

  • 1
    You could redirect (or just terminate the script) conditionally, only if the posted value is not present. But consider that users can post their own data to your PHP script. Also see [How to tell if a page is being called via Ajax, or on it's own](http://stackoverflow.com/questions/9828420/how-to-tell-if-a-page-is-being-called-via-ajax-or-on-its-own). – showdev Jun 07 '16 at 21:55
  • You could just put the header in an `else` statement: `if(isset(...)){ /*do something*/ } else { header('...'); }` – Jonathan Kuhn Jun 07 '16 at 21:58
  • Are you missing an equal sign in your `var $ajaxData` defn? – cssyphus Jun 07 '16 at 22:08
  • @gibberish Yeah, it was when I was writing the question in here :| –  Jun 07 '16 at 22:11
  • No worries, just wanted to point it out. Hope your question is now resolved. – cssyphus Jun 07 '16 at 22:16

1 Answers1

3

The problem is, the script is expecting a JSON, while your "redirect" code sends a HTTP 301 to a HTML file. Ultimately, the AJAX XHR is not seeing your JSON, but gets the HTML output.

Revert back your code to how it was before:

<?php
if(isset($_POST['input-val'])) {
    $data['stat'] = 'success';
    echo json_encode($data);
}

Instead, do it in the AJAX handler:

.done(function($data) {
    alert($data["stat"]);
    if ($data["stat"] == "success")
        location.href = 'index.php';
}) // And you are also missing a ) here.

According to comments:

If you are redirecting if the $_POST is not set, please use the else:

if (isset($_POST['input-val'])) {
    $data['stat'] = 'success';
    echo json_encode($data);
} else {
    header('Location: index.php');
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252