Javascript – use AJAX ‘POST’ to post data to a JSON file on the server

ajaxjavascriptjqueryjsonpolymer

I just want the easiest/most simple way to get my data from an AJAX form using 'POST' the data the user entered on my server.

So if the user leaves their name in the input form on the page, then AJAX POST's the data to a JSON file on my server.

Is this possible? Is this the quickest way to get the data that is entered?

Thanks in advance!

*can someone tell me why this got downvoted? Am I violating any terms? I would just like to know in the future. Thanks. :/

Best Solution

Ajax file directly can not write to a file in your server. But you can achieve this by creating simple php script say savejson.php on your server.
Your form:

<form>
    <input type="text" id="name" name="name">
    <button type="submit" id="submit-btn">
</form>

<script>
$('#submit-btn').on('click', function(e) {
    e.preventDefault();
    if( $('#name').val() ){
        $.ajax({
            url     : 'savejson.php',
            method  : 'post',
            data    : { 'name': $('#name').val() },
            success : function( response ) {
                alert( response );
            }
        });
    }
});
</script>

Your savejson.php:

<?php
    $fp = fopen('names.json', 'w');
    fwrite($fp, json_encode($_POST['name']));
    fclose($fp);
?>