Home » Php » jquery – How do you save a file to a directory given by an input type="text" with php?

jquery – How do you save a file to a directory given by an input type="text" with php?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a html page with jQuery and I used ajax to send data to the a php file to save the data.
I have seen other questions like this but none of them seemed to match my purpose.

The data is an iframe’s srcdoc.

My html looks like this:

<iframe srcdoc="<h1>hello</h1>" id="iframe"></iframe>
<br />
<input type="text" placeholder="Filename to save as..." id="fn">
<input type="button" value="Save" onclick="saveDoc(document.querySelector('#fn').value)">

My jQuery and JS looks like this:

function saveDoc(e) {
  let iframe = document.querySelector("#iframe");
  let data = {"srcdoc": iframe.srcdoc, "lnk": e};

  $.ajax({
    type: "POST",
    url: "saver.php",
    dataType : "text",
    contentType: "application/json",
    data: data,
    cache: false,
    timeout: 3000,
    success: function (data) {
        alert("SUCCESS");
        console.log(data);
    },
    error: function (e) {
        alert(e);
    }
  });
}

And my php code looks like this:

<!doctype html>
<html>
<body>
<?php
  if (isset($_POST["lnk"]) && isset($_POST["srcdoc"])) {
    $myfile = fopen($_POST["link"], "w");
    fwrite($myfile, $_POST["srcdoc"]);
    fclose($myfile);
    echo $_POST["lnk"];
    echo "\n <br/>";
    echo $_POST["srcdoc"];
  } else {
    echo "Error";
  }
?>
</body>
</html>

When I run it, I get an alert message saying “SUCCESS”. And the console.log gives me:

<!doctype html>
<html>
<body>
Error</body>
</html>

What is happening here, and what am I doing wrong?

How to&Answers:
contentType: "application/json"

You are explicitly sending this to the server as JSON – so you can not access it via $_POST. (PHP only populates $_POST for Content-Types application/x-www-form-urlencoded or multipart/form-data.)

Either remove contentType, so that it can fall back to the normal way of sending form data, or go read up on how to actually read POSTed JSON data in PHP. (That would involve reading the data from php://input first, see Receive JSON POST with PHP)

Answer:

I executed your code at my local you need to do two changes

in your HTML add id="filename"

<input type="text" id="filename" placeholder="Filename to save as...">

in your JS code change this line

let data = {"srcdoc": iframe.srcdoc, "lnk": document.getElementById("filename").value};

the reason it was printing Error was this lnk param was not passing to saver.php