0

I can't find on the web so I'm asking some help over here. I'd like to create a log file, when someone press on a button it will a text to a log.txt file. I'm just looking for the the base code based on Jquery ajax and PHP

Thanks

Michael HEYRAUD
  • 57
  • 1
  • 10

2 Answers2

0

there is no base code for jquery logging to sever

  1. first of, you have to decide how many times you want to call the server,
    • each log entry will be too much load on server,
    • append all to js array and post on session ending? when doe's session ends? and what if user closes browser? all the log gone? (see my suggestion bellow)
  2. you'll have to make an endpoint on server to get log entries and append them to file, then you should think of storage, and how to organize log enries from multiple clients

I would recomend using log4javascript library with AjaxAppender, see example here, you can then use setBatchSize to send in batches or setTimed to send with time intervals, see documentation here, also you can setSendAllOnUnload to don't lose messages on browser close (in most cases).

in the server i would use log4php with LoggerAppenderRollingFile see here

0

I don't have to time to code it for you but here is the basic logic. You can look up how to do each item individually.

You need to add an event listener with jquery for the click event and bind it to the button.

Inside that, have an ajax request to some endpoint or script on your server that will update the log file.

When that script is executed (via the ajax call), you can have PHP open the file and append a line to it that has whatever data you want.

JavaScript:

$('button').on('click', function() {
  $.ajax({
    // do ajax request here
  });
});

PHP:

$file = fopen("log.txt","rw");
$fileContents = fread($file, filesize("log.txt"));
fwrite($file, $fileContents."Someone clicked button\r\n");
fclose($file);

Something like that. Sorry for not giving a full explanation but I hope it helps.

Mike
  • 375
  • 1
  • 14
  • Also do not put anything sent from ajax into the file contents. You can easily have a security risk here. Be careful. – Mike Jun 29 '17 at 21:40