1

I am simply trying to pass some information to a PHP script using jquery $.post() and then write that information to a text file. The post is working just fine. No errors are thrown, as far as I know...but the files aren't created and when I put the file there it isn't written to. Am I missing something? Here's my code.

JavaScript

  var ajaxData = { IGC: JSON.stringify(containerObj), filename: newFilePath };
  $.post( "../php/generateIGC.php", ajaxData, function(data) {
        $('#generated_textarea').val(data)
  })

Originally I tried to interpret what was being sent and write it to the file.

PHP

<?php
  $data = json_decode(stripslashes($_POST['IGC']), true);
  $myFile = $_POST['filename'];
  $handle = fopen($myFile, 'w'); //or die('Cannot open file:  '.$myFile); 
  fwrite($handle,$data);
  fclose($handle);
  echo "File successfully created";
?>

Then I gave up and just tried to write to a file that I created for testing, and even this won't work.

<?php

  $data = 'dfjlsdkfsdlfkj';
  $handle = fopen('test.txt', 'w'); //or die('Cannot open file:  '.$myFile); 
  fwrite($handle,$data);
  fclose($handle);

 ?>

I'm not getting any error in the browser, and the post succeeds. The only indication I have that something isn't working is the file not being written to or created, and when I access (data) I just get a string of the php script. What am I doing wrong here?

UPDATE:

I changed the php script to this

<?php
 $data = json_decode(stripslashes($_POST['IGC']), true);
 $myFile = $_POST['filename']
 $handle = fopen('test.txt', 'w') or die('Cannot open file:  '.$myFile); 
 fwrite($handle,$data);
 fclose($handle);
 return $data;
 ?>

and now I get the error:

kCFErrorDomainCFNetwork error 1.)

Here is the post function if it helps

    function genCode() {
  var path = $('#path_to_image').val();
  var index = path.length
  for (var i = 1; i<=3; i++) {
    index = path.lastIndexOf('/',index-1)
  }
  var fileToCreate = path.substring(path.lastIndexOf('/')+1,path.lastIndexOf('.'))+'.igc'
  var newFilePath = path.substring(0,path.lastIndexOf('.'))+'.igc'
  containerObj["target_container"] = $('#target_container').val();
  containerObj["img_path"] = path.substring(index+1);
  containerObj["img_dims"] = {x: w, y: h};
  containerObj["mode"] = $('#number_of_axes').val();
  containerObj["sd"] = {x1: $('#sd_x1').val(), y1: $('#sd_y1').val(), x2: $('#sd_x2').val(), y2: $('#sd_y2').val()};
  containerObj["number_of_graphs"] = $('#number_of_graphs').val();
  var show_waypoints = false;
  containerObj["show_waypoints"] = false;
  //$('#generated_textarea').val("attachGraph.addGraph(" + JSON.stringify(containerObj, null, '\t') + ");");
  var ajaxData = { IGC: JSON.stringify(containerObj), filename: newFilePath };
 /*   $.ajax({
      type: "POST",
      url: "../php/generateIGC.php",
      data: ajaxData,
      success: function() {
        $('#generated_textarea').val("File created.")
      }
      })
    })
   */ $.post( "../php/generateIGC.php", ajaxData, function(data) {
        $('#generated_textarea').val(data)
    } )
}
13
  • You might try adding the full path to where the file should be opened/written and see if that resolves it for you.
    – Diemuzi
    Commented Oct 10, 2013 at 19:58
  • Do you have full error reporting enabled?
    – Barmar
    Commented Oct 10, 2013 at 19:58
  • 2
    For one thing you have a missing closing semi-colon in $myFile = $_POST['filename'] - plus $myFile is just a variable, nothing else is using it/passed to it. Commented Oct 10, 2013 at 19:58
  • i would console log data in your $.post() just to make sure there's something there. and again in your PHP i would output $data just to make sure it isn't empty. you might try escape(data) in your js. there may be characters that are choking your js or even you php i suppose
    – b_dubb
    Commented Oct 10, 2013 at 20:00
  • Your second PHP code with dfjlsdkfsdlfkj inside it, works. Check your file permissions. Commented Oct 10, 2013 at 20:03

2 Answers 2

3

It can me a lot of things, you should be aware of the path you are trying to write and also you should tweak the configuration of PHP to show errors since all file operations produce a WARNING that does not halt your script.

<?php
ini_set('display_errors', 1); // show errors
error_reporting(-1); // of all levels
date_default_timezone_set('UTC'); // PHP will complain about on this error level

if (!isset($_POST['IGC'])) { // Test if this was posted
    echo "IGC not defined";
    exit;
}

if (!isset($_POST['filename'])) { // Test if this was posted too
    echo "filename not defined."
    exit;
}
$data = json_decode(stripslashes($_POST['IGC']), true);
$myFile = $_POST['filename'];
$fileToWrite = 'test.txt';
if (!is_writable($fileToWrite)) { // Test if the file is writable
    echo "Cannot write to {$fileToWrite}";
    exit;
}

$handle = fopen($fileToWrite, 'w');
if (!is_resource($handle)) { // Test if PHP could open the file
    echo "Could not open {$fileToWrite} for writting."
    exit;
}

fwrite($handle,$data);
fclose($handle);
echo "File successfully created";
?>

This script as your upload PHP script should give you better details on your problem. The only thing you would have to be sure is where the file you are editing is, and if PHP has permission to write to it.

If you do not use an absolute path on the filename, PHP will try to write in the directory of the script.

8
  • I gave this a shot. Like before, the file isn't created and $('#generated_textarea').val(data) just writes the entire script to #generated_textarea No errors thrown.
    – ordanj
    Commented Oct 10, 2013 at 20:26
  • I feel like at the very least, echo should be sending back proper data. Am I not accessing it properly?
    – ordanj
    Commented Oct 10, 2013 at 20:30
  • What is the content on the textarea? You are probably not accessing the PHP properly as you said, there is anything on the log at the web server (access, error...)? Commented Oct 10, 2013 at 21:52
  • Well, I actually think the problem might be that php isn't enabled. I removed the comment from #LoadModule php5_module libexec/apache2/libphp5.so but must have missed another step.
    – ordanj
    Commented Oct 14, 2013 at 13:30
  • After removing the comment you must restart Apache. Make sure PHP is installed running php -v on a shell and by creating and opening a page containing <?php phpinfo();. Commented Oct 14, 2013 at 13:34
0

Finally "solved" this problem. I had been accidentally running the html page locally, and not through the apache server, so the php couldn't run. Additionally, the txt files didn't have write access and there were some errors in my code originally. All pretty silly though.

Not the answer you're looking for? Browse other questions tagged or ask your own question.