Jack T
Jack T

Reputation: 13

Save JavaScript variable to file via php

I am fairly new to programming, and was trying to save a JavaScript variable to an existing file:

<script src="./jquery.js"></script>
<script>
var data = inputs
function saveLists(){
$.ajax({
    type: 'POST',
    url: "save.php",
    data: "data",
    success: function(){
        alert("success!")},
    error: function(){
        alert("Failed!")},
    dataType: "text"
})
}
</script>

I define the inputs variable earlier, and I am using POST method and the following php server side:

<?php
$data = $_POST["data"];
$f = fopen('Inputs.txt', 'a+');
fwrite($f, $data);
fclose($f);
?>

When I call the saveLists() function the success alert comes up, but the data is not written to Inputs.txt. Any ideas on what I am doing wrong?

Upvotes: 0

Views: 88

Answers (1)

Luicy
Luicy

Reputation: 33

PHP is trying to read an index which doesn't exist, data is not a valid index & key. Try something like this:

data: {
    "data" : data
}

Also, don't trust all code that the server receives in PHP.

Upvotes: 1

Related Questions