views:

477

answers:

1

Hello,
I have a PHP application containing these files: landing.php, redirect.php, ajax.php

on a page call to landing.php, I execute a javascript code to capture certain data, and issue an AJAX POST to ajax.php which inserts them into DB. Finally php header() redirects to redirect.php

Currently the above feature is using output buffering, but the header() is executed too soon that the AJAX POST is not finished..ie, no DB query is made.

I tried using sleep() usleep() before header() but they are not working. As I am not very familiar with output buffering, would you please offer a kind hand?

Thank you.

<?php ob_start(); ?>

<scripts type="text/javascript">
var data = 'blah..blah..blah..';
ajaxPost('ajax.php', data);
</scripts>

<?php
sleep(2);    // <---- I want the script to sleep here and wait for the AJAX to finish
header('c.php)
ob_end_flush();
?>
+2  A: 

If I understood you correctly, you have a fundamental misunderstanding on how web applications work.

Your PHP script can't wait for the AJAX bit to execute, because the whole script is first run on the server, and the output -- part of which the AJAX call is -- is then sent to the browser. You have to rethink the way you're doing this.

For instance, you could have the JavaScript first make the AJAX call, and then redirect the browser.

Edit: OK, now that I've thought about this for a while more, I can see how something like this might work when you're not using output buffering, if the browser executes the script as soon as it sees it (without having the full page loaded). If that is indeed the case, then you're still relying on the browser's timing, the quality of the user's internet connection and so on to keep things in sync. That is decidedly not a good thing.

However, the only way that could work is if the AJAX call got outputted to the browser before your header call -- which is not possible! Headers need to be sent before the content in the HTTP response (which is why you're using output buffering in the first place), so either you won't output the JavaScript or the header call will fail. So I recommend you rethink your approach.

Rytmis
Thanks! I really ignored the fundamentals about them.It appears to me that redirection via Javascript will change the HTTP Referer value. I am however required to retain the HTTP Referer upon the above redirections, may I know if there are better method to solve this?
hoball
Is there a reason you are saving things via the AJAX call? If you want to first save things to the DB and then redirect, why not do it all in the PHP script? That's the obvious way to do it, anyway. :)
Rytmis
This is because the data i am capturing are javascript only --- window.screenX, window.screenY and etc.. Unfortunately header() and javascript are not compatible!Thanks for your help anyway. I am looking for a redesign =P
hoball