Bitz
Bitz

Reputation: 1148

Posting to text file using AJAX?

How do you post this AJAX request to a text file? The url it is posting to is something along the lines of submit.php, but I can't seem to figure out how to save it properly to a file named "data.txt"

function makeAjaxRequest(cData) {
    var promise = $.ajax({
        type: "POST",
        url: url,
        data: cData,
        dataType: 'json',
        async: true
    });

    promise.done(successFunction);
    promise.fail(errorFunction);
    promise.always(alwaysFunction);
}

The data itself is already fo the format using data = JSON.stringify(collectedData); in a previous statement.

EDIT: I guess the wording I used is poor, sorry. I intend to pass the data into submit.php using the POST method. I would like that submit.php file to concat the text to a text file.

Currently the submit.php file contains the following:

<?php  file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX); ?>

Upvotes: 1

Views: 1338

Answers (1)

meda
meda

Reputation: 45490

I didnt see how you retrieved the ajax data, since $data is undefined in your code, try this:

<?php  
    $data = file_get_contents('php://input');
    file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX); 
?>

This will write json strings to mydata.txt

Upvotes: 2

Related Questions