ElcompJR ElcompJR - 6 months ago 34
Javascript Question

Redirect from Ajax's PHP script

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.

Answer

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');
}