AJAX and JQuery for server-side actions

I wanted to do this: click on something and have that data saved to a file.

Found this: save data through ajax jquery with form submit and used the click instead from another page on the web and BAM! This POC accomplishes that. Knowing this, it is easy to make a database call or something. Then end goal is to add this to a home-coded gallery so we can wheat/chaff/tag 50k of photos. Also it's an excuse to learn Javascript.

Note: Being this is a POC, there is no input sanitizing, or protections of any kind. It's just a POC.

Files

There are two files for this POC: html and a php file. Also This is set in /etc/httpd/conf.d/php.conf:

AddType application/x-httpd-php .html

Set the paths as needed and test out.

HTML File

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>click demo</title>
<style>
p {
color: red;
margin: 5px;
cursor: pointer;
}
p:hover {
background: yellow;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>

/* works
$( "p" ).click(function() {
    alert("Sending data: " + this.innerHTML + " " + this.offsetWidth);
    $( this ).slideUp();
});
*/

$( "p" ).click(function(e) {
    e.preventDefault();
    //alert("Sending data: " + this.innerHTML + " " + this.id);

    $.ajax({
        type: "POST",
        url: "script.php?file=data/thumbs-www/log/file.txt",
        data: { text : this.innerHTML, id : this.id },
        success:function(data) {
            //alert(data);
        }
    });

});

</script>

</body>
</html>

PHP File

<?php

$ts=time();
$file = "/var/www/html/" . $_GET['file'] . $ts;

// create a json string of the data passed
$contents = '{ ts : ' . $ts . ', ';
foreach ($_POST as $name => $value) {
    $contents .= "$name : \"$value\", ";
}

// cleanup
$var = '/,\s*$/';
$contents = substr_replace($var, $contents, 0); 
$contents .= ' }' . "\n";


file_put_contents($file, $contents);

?>

Published on in