1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

logging javascript form entry to a txt file?

Discussion in 'General Programming Chat' started by kickapooh, Dec 22, 2013.

  1. kickapooh

    kickapooh Regular Member

    Joined:
    Apr 16, 2010
    Messages:
    431
    Likes Received:
    844
    I'm looking for an easy way to log a javascript value to a txt file on the server/host. Anyone do this before and mind helping a brotha' out?
     
  2. rob1977

    rob1977 Power Member

    Joined:
    Mar 25, 2013
    Messages:
    773
    Likes Received:
    666
    I was trying to find a way to do it and confused myself.

    Even though jquery does Ajax calls to the server it apparently can not write to the server.

    My solution was a php script,
     
    • Thanks Thanks x 1
  3. sirgold

    sirgold Supreme Member

    Joined:
    Jun 25, 2010
    Messages:
    1,260
    Likes Received:
    645
    Occupation:
    Busy proving the Pareto principle right
    Location:
    A hot one
    You're one of the good ones, so here we go tested and ready to rock for ya! ;)

    cut-paste into a plain html file like mypage.htm
    Code:
    <html>
    <head>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.9.1.min.js">
    </script>
    </head>
    <body>
     
    <script type="text/javascript">
    function save(data) { // might want to use an external js file to cloak it
      $.ajax({
        url : "write.php",
        type: "POST",
        data : data,
        success: function(serverResponse, textStatus, jqXHR) {
          /* serverResponse -> response from write.php */
          alert(serverResponse); // comment out, just to see how it works
        },
        error: function (jqXHR, textStatus, errorThrown) { }
      });
    }
    </script>
      
    <a href="javascript:void()" onclick="save({'user':'bhw','ip':'1.1.1.1'})">save this</a>
    
    </body>
    </html>
    
    and cut-paste this into a php file called write.php in the same folder where the previous file is located

    Code:
    <?php
    if (!empty($_POST)) {
      echo "PHP wrote: ".json_encode($_POST); // comment out
      file_put_contents("log.txt", json_encode($_POST)."\n", FILE_APPEND);
    } else echo "Nothing to see here. Fuck off";
    ?>
    
    Make sure to upload these two files to a working website, pass a well-formatted json string with as many parameters as you like to save() and the use should be self-explanatory. You'll end up with a file called log.txt where these values are appended... Black magic ;)
     
    • Thanks Thanks x 2
  4. kickapooh

    kickapooh Regular Member

    Joined:
    Apr 16, 2010
    Messages:
    431
    Likes Received:
    844
    Thanks a ton guys! Helped me out alot.