JavaScript

Farnoosh M
Farnoosh M
10,921 Points

Sending 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
Seth Kroger
56,372 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
Farnoosh M
10,921 Points

Worked like magic. Thank you so much Seth :)