phpjavascriptxmlhttprequestdomexception

Redirect once XMLHttpRequest Complete Error


I'm using the kineticjs library and i have a script which saves the stage as an image using the toDataURL method and uploads it onto the server with an XMLHttpReuest. All works as expected in getting the image saved onto the server but i cannot get the page to redirect or change once completed.

My javascript/kineticjs code for generating the image is:

function save() {
    stage.toDataURL({
        callback: function(dataUrl) {
            var ajax = new XMLHttpRequest();
            ajax.open("POST",'upload_screenshot.php?newname=<?php echo $newname;?>',false);
            ajax.setRequestHeader('Content-Type', 'application/upload');
            ajax.send(dataUrl);
        }
    });
}

My code for upload_screenshot.php is:

<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])){

    $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
    $newname = $_GET['newname'];
    $imagefile = 'final_images/'.$newname.'.png';

    $filteredData=substr($imageData, strpos($imageData, ",")+1);
    $unencodedData=base64_decode($filteredData);

    $fp = fopen($imagefile, 'wb');
    fwrite($fp, $unencodedData);
    fclose($fp);

    header('Location: http://www.example.com');
}
?>

So the image is saved on the server but i get the following error in the chrome javascript console:

Uncaught Error: NetworkError: DOM Exception 19 

What does this mean?

If i change the open call from false (synchronous):

ajax.open("POST",'upload_screenshot.php?newname=<?php echo $newname;?>',false);

to true (asynchronous):

ajax.open("POST",'upload_screenshot.php?newname=<?php echo $newname;?>',true);

I now get the file saved onto the server without the error but again no redirect to example.com


Solution

  • Your header() call in your php script isn't going redirect your page via an ajax request. You'll need to examine the response from your ajax request and perform the redirect in javascript using document.location = "http://example.com".

    Here's an example of how to perform a callback function on the ajax response.

    Also, I'm not sure how or where your executing this javascript but if it's in an external js file your <?php echo $newname; ?> won't be executed. You'll need to find a more clever way of passing this information to your javascript function.