0

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?

fdomn-m
28.8k8 gold badges39 silver badges70 bronze badges
asked Feb 24, 2018 at 17:59
3
  • 2
    data: "data" so you are just sending the string "data" and PHP is complaining about an undefined index but you're ignoring it. Commented Feb 24, 2018 at 18:01
  • data needs to be a query string e.g. data: 'data=something' or an object e.g. data: { data: 'something' }. Commented Feb 24, 2018 at 18:03
  • If you get the success: then it's most likely the php is not handling it correctly. Commented Feb 24, 2018 at 18:05

1 Answer 1

1

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.

answered Feb 24, 2018 at 18:06
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.