简体   繁体   中英

use ajax to call php to write timestamp to file

I'm trying to call a function in javascript to write to a text file. This function uses ajax to to run some code in a php file. All my code seems to be working fine, but I havent gotten any output (If the file doesn't exist, I want it to be created when the php code runs). Everything is being run locally and must be run in chrome. I've found some other people with similar questions, but I wasn't able to apply those solutions. I am very new so please be explicit. Also, if there is a better way to do this (get the system timestamp and write/append to a text file) I am more than open. I just need to record the timestamp whenever a particular javascript function is called. In addition, I would like to eventually pass a string from my running javascript to be saved with each timestamp (the string is determined by the running javascript). Note that running in "Data: running" is a dummy variable. Eventually this will be used to pass a string.

im using this script to use ajax (in html script)

script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"

javascript code..... call recordTone().... javascript code


function recordTone() {
    $.ajax({
        url: "file:///C:/Users/ryan/Desktop/New%20folder/saveTimeStamp.php",
        type: "POST",
        data: running,
        success: function (msg) {
            alert(msg);
        }
    });
}

saveTImeStamp1.php in entirety

<?php
    $my_file = 'session1.txt';
    $handle = fopen($my_file, 'w') or die('Cannot open file:  '$my_file);
    $data = microtime();
    fwrite($handle, $data);
    fclose($handle);
    echo "YES";  
?>

You need a web server and then have a URL to it. Easy to install Apache and PHP

Not

file:///C:/Users/ryan/Desktop/New%20folder/saveTimeStamp.php

As this will not work

Install XAMPP ( http://www.apachefriends.org/en/xampp-windows.html ), and then reference your file relatively. If the html file is in C:/Users/ryan/Desktop/New%20folder/, just change the url to "saveTimeStamp.php".

Another option if you don't want to install your own webserver is to purchase some hosting online, from somewhere like http://www.arvixe.com/ .

You need a web server and then have a URL to it. Easy to install Apache and PHP Like "Ed Heal" said...

or you can use web service to call you procedure/function ...

function recordTone() {
  $.ajax({ 
    url: "localhost/yousite/saveTimeStamp.php",
    type: "POST",
    data: running,
    success: function(msg){
      alert(msg);
    }          
  });
}

look at 'url', change to your local site...

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