Reputation: 31
Hello guys that is not normal :) !!
foo.php
<?php
if (isset($_POST['data']))
$stringData = $_POST['data'];
$file = "ciao.txt";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $stringData);
fclose($fh);
?>
file.js
function WriteToFile() {
var dataa = "foo bar";
$.post("foo.php", {data: dataa}, function(result){ alert("ciaoooo!!");}
, "json");
}
this is the error and i can't write on my file.txt
Notice: Undefined variable: stringData
I tried also with that kind of function
function WriteToFile() {
var data = "foo bar";
$.ajax({
url: 'foo.php',
type: 'POST',
data: { 'data' : 'data'},
success: function() {
alert('the data was successfully sent to the server');
}
});
but the result is the same!! Anyone have some idea???
Upvotes: 2
Views: 3184
Reputation: 12834
Ok, I think here's what is happening:
The code you have posted (foo.php/file.js in example 1) is correct, and will work without issues. I am not sure if you are trying to hit the foo.php URL directly in the browser. In that case there is nothing posted, so $stringData will be undefined, and it will throw the notice you are seeing.
What you need to do is: 1. Include the file.js script in an HTML file. 2. Make sure you have included jquery library 3. Make sure that the PHP (foo.php) file path is correct in $.POST 4. Call WriteToFile() on the HTML body onLoad function
Here is a sample HTML which should work (update path to foo.php if needed)
<script src ="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
function WriteToFile()
{
var dataa = "foo bar";
$.post("foo.php", {data: dataa}, function(result){ alert("ciaoooo!!");}, "json");
}
</script>
Upvotes: 2
Reputation: 2948
I think you want something like this:
function WriteToFile() {
var data = "foo bar";
$.ajax({
url: 'foo.php',
type: 'POST',
data: data,
success: function() {
alert('the data was successfully sent to the server');
}
});
Upvotes: 0
Reputation: 59709
You're missing curly brackets:
if (isset($_POST['data'])) {
$stringData = $_POST['data'];
$file = "ciao.txt";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $stringData);
fclose($fh);
}
Without them, you essentially have this:
if (isset($_POST['data'])) {
$stringData = $_POST['data'];
}
$file = "ciao.txt";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $stringData);
fclose($fh);
Which explains why you're getting undefined $stringData
, because the POST is not being executed properly.
Note that this doesn't solve your JS / jQuery problems. For that, see the other answers.
Upvotes: 4
Reputation: 14187
Don't use quotes at this point:
data: { 'data' : 'data'},
replace it with:
data: {data : data},
Also, in the first code snippet you need brackets, correct it like this:
if (isset($_POST['data'])) {
/* Your code here */
}
Upvotes: 0