Ad

Is It Possible To Prevent The Header("location: Url") From Being Sent To AJAX?

- 1 answer

I've a html form on a page. The form data is sent via AJAX to a PHP script. Within this PHP script, each of the $_POST's from the inputs are checked conditionally using a variety of if statements. If the condition doesn't meet a specific strlen / other criteria then I echo a message into the AJAX returndata and exit() the PHP script.

Assuming all conditions are met, at the bottom of my PHP script I have applied a url that is built from variables within the PHP script itself and concatenated inside, like so:

header("location: view_topic.php?tid='".$tid."'&page='".$page."'");

The issue:

Since I am generating the url within the PHP script, and am only able to generate it in there, I am having to either use PHP header("location: ...") as a redirect, or having to echo the url, which in turn sends it to the returndata, then use window.location(returndata) in my JavaScript/AJAX.

I've done some homework and have noticed a known issue with the header method, when set is being sent to the AJAX returndata. This means that the entire header location page is being displayed in a tiny invisible div where I display my errors for the above mentioned conditional error messages generated in the PHP script.

The question:

In the below code is my alternative method of setting the window.location(returndata).

Here I am echoing the actual url generated by my PHP variables, which sends it to the returndata. However when submitting the form I am returned to the same page, and the returndata is simply echo'd out from the PHP at the top.

Does anyone know how to prevent the header("location: ..."); from being sent to the AJAX returndata, or have any other solutions on the method below?

Thanks in advance, Richie.

My AJAX:

$("#topic_form").submit(function(event){
    var formData = new FormData($(this)[0]);
    $.ajax({
    url: 'create_topic_parse.php',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
        success: function (returndata) {
            if(returndata.indexOf("view_topic") != true){
                $('#message').css("color", "red").html(returndata);
                } else {
                window.location(returndata);
            }
        }
    });
    return false;
});
Ad

Answer

instead of returning html, return json:

{"action": "display","html":"..."}

or

{"action":"redirect","location":"url"}

and change:

    success: function (response) {
        if(response.action == "display"){
            $('#message').css("color", "red").html(response.html);
        } else if (response.action == "redirect") {
            window.location(response.location);
        }
    }
Ad
source: stackoverflow.com
Ad