Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFarnoosh M
10,921 PointsSending an AJAX request by jQuery to write to a text file using PHP
Hi! I have a text area in my html with the id of #myText and an input button (type=submit) and the id of #btn. I want to make an AJAX request to get the value of the textarea and write it to a text file. But it's not working because the value of the sent data is Null in the save.php file. All files are in the same directory.
<textarea name="message" placeholder="Write something" id="myText">I am trying to post data with AJAX!
</textarea>
<input type="submit" id="btn" value="Send it">
jQuery:
$("#btn").click(function(){
var myText = $("#myText").val();
console.log('Textarea: '+myText);
var url ="save.php";
$.post(url, myText, function(data){
console.log('response from the callback function: '+ data);
}).fail(function(jqXHR){
alert(jqXHR.status +' '+jqXHR.statusText+ ' $.post failed!');
});
});
PHP:
<?php
print_r('The php script is called....');
print_r('The value of $_POST["myText"] is : ');
var_dump($_POST['myText']);
$post_data = $_POST['myText'];
$filename ='data.txt';
$handle = fopen($filename, "w");
if (empty($post_data)) {
fwrite($handle, ' Hmm, I did NOT get any data from AJAX. myText is: '. $post_data);
}
if (!empty($post_data)) {
fwrite($handle, ' ... Recieved data from AJAX! myText: ');
fwrite($handle, $post_data);
}
fclose($handle);
?>
1 Answer
Seth Kroger
56,412 Points$.post() the data is either a string that is sent straight or an object that is sent as properties and values. If you want to refer to the "myText" property in the PHP try sending it as:
$.post(url, { myText: myText }, function(data){ // ...
Farnoosh M
10,921 PointsFarnoosh M
10,921 PointsWorked like magic. Thank you so much Seth :)