Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use AJAX 'POST' to post data to a JSON file on my server?

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. :/

like image 307
user3648969 Avatar asked Dec 14 '22 14:12

user3648969


2 Answers

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);
?>
like image 189
Karthik Avatar answered Apr 12 '23 23:04

Karthik


Ajax is a term that more-or-less just means "Make an HTTP request from JavaScript".

You can use it to make a POST request. You can use it to make the body of that request a JSON text.

You can't POST to a file, only to a URL. You would need server side code that would be responsible for taking the data in the request and writing it to a file.

like image 23
Quentin Avatar answered Apr 12 '23 23:04

Quentin