简体   繁体   中英

Trigger php script with ajax call

I'd like to make an ajax call to a php file; eventually this php file will write to a mongodb database. For now, I am debugging and would like to have the php file open and write to a text file. The php file works when I run it from the command line. Similarly, the ajax call returns a 'success' message. However, the ajax call does not result in the writing of a new text file.

From the relevant part of my javascript file:

$.ajax({
    type: "POST",
    url: "jq.php",
    data: {
        'myString': "blahblah",
    },
    success: function(data) {
        alert('worked');
    },
    error: function(){
        alert('failed');
    }
});

The php file:

<?php
$file=fopen("welcome.txt","w");
$str = "let's hope this works.";
fwrite($file, $str);
fclose($file);
?>

I have also tried wrapping the above content in: if ($_POST['ajax']) {...}.

For debugging, don't run the script from command-line but simply open it directly with your browser. When you're using the command-line, you're executing the script as the user you are (maybe "root"), but if it's called from your browser, it's executed by apache (or whatever webserver you're using) with it's own user.

Most likely, your own user account has writing permissions, but the apache-user doesn't - so the command-line works, but calls from a browser don't.

By the way: this is barely a good test case to replace a mongo-db (or any other database) interaction, where you won't have to worry about file-system-permission problems but could instead run into hundreds of other problems.

you should always use:

$file=fopen("welcome.txt","w");
if ($file) { // because fopen can return FALSE on error
  $str = "let's hope this works.";
  fwrite($file, $str);
  fclose($file);
}
else {
  // something wrong!
}

ref

EDIT also check for E_WARNING - it can show you the problem, you can activate it by error_reporting(E_ALL); if it's disabled by your server or look for error inside php log file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM