3

I am calling a file_put_contents() inside of a PHP script that is executed via AJAX. Whenever I execute this script the client page gets reloaded which is not desirable. Is there a way to prevent the PHP script from reloading the page?

I have tried modifying the headers using the following and passing it as the context parameter in the file_put_contents function:

$context = stream_context_create(
    array(
        'http' => array(
            'follow_location' => false
        )
    )
  );
Matt Butler
  • 476
  • 6
  • 21
  • 1
    Unless you're explicitly including some JavaScript in your Ajax response that causes a reload or redirect, it's almost certain that your problem is elsewhere. Maybe your Ajax call is being triggered by a browser event that you are allowing to bubble up? – Greg Schmidt Jun 12 '18 at 02:45
  • @GregSchmidt when I remove the file_put_contents call the problem is resolved. Do you think there is something behind the scenes that is causing a redirect back to the parent script once the actions have been performed with the file? – Matt Butler Jun 12 '18 at 02:48
  • There's nowhere near enough information here to make any kind of suggestion on that. Show us the HTML that calls the Ajax, and the code that calls `file_put_contents`. – Greg Schmidt Jun 12 '18 at 02:51
  • @GregSchmidt I am talking more in terms of the behind the scenes of the file_put_contents function itself. Not my code in particular – Matt Butler Jun 12 '18 at 02:53
  • `file_put_contents` simply writes output to a file. An Ajax request that generates plain HTML output cannot cause a redirect. The problem will be somewhere in your initial HTML / JavaScript or else in the content that you are putting to the file. Without seeing any of this, we can only make wild guesses. – Greg Schmidt Jun 12 '18 at 02:56
  • @GregSchmidt Ok I have found out some additional info. When commenting out the AJAX return code nothing happens so it isn't on the client side. When commenting out the file_put_contents the problem is fixed. However, the only FPC call that is causing problems is one where I create an HTML file. The other call creates a JSON file and does not cause any issues with respect to redirection. – Matt Butler Jun 12 '18 at 03:26
  • @GregSchmidt I have fixed the issue by saving both files as .txt. There was no real necessary reason for me to store them in any other extension. Thanks for your time! – Matt Butler Jun 12 '18 at 04:31
  • I'm having the same issue, and my files are .txt. Any solution to this? Thanks. – Gregory R. May 25 '22 at 16:12

1 Answers1

0

Try runnning script in incognito mode. Had same problem with file_put_contents(), and it was live reload VSCode extension that for some reason was refreshing the page.

Voj
  • 11
  • 1