-1

I know that this question has been asked a lot of times but everything I tried does not work.

HERE HERE HERE HERE I've read many other posts and articles, nothing works.

So, what I'm trying to do is passing a variable to either the JS file or the HTML file.

This variable is "fileNewName", basically when an image is uploaded, it's name is replaced by a uniqid so that if two images have the same name one of them won't be overwritten.

I then need to get this "fileNewName" back to the HTML in order to display it with the img object. I want to avoid changing the index.HTML file to index.PHP, but I understand that from what I've read, I will have to do that at some point and probably use Ajax.

What I wanted to do originally is : pass the variable from PHP to set a var in JS with it's value (like that : var name = "somehow get the the variable from the PHP file";) and then use img.src = "uploads/" + name;.

I hope that I've explained my problem clearly. Any help or hints will be much appreciated, thanks !

Here are the different codes :

index.html

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/index.css" >
    <link rel = "icon" href="logo.png" type="image/x-icon">
</head>

<body>
  <div class="topnav">
    <img src="logo.png" style="width:40px;height:40px;"></img>
    <a class="active" href="index.html">HOME</a>
    <a href="help.html">HELP</a>
    <a href="about.html">ABOUT</a>
    <a href="examples.html">EXAMPLES</a>
  </div>

<div class="dropzone" id="dropzone">
  <img src="" id="img" class="img">
  <form class="form" id="myForm">
    <input type="file" id="inpFile" accept="image/png, image/jpg, image/jpeg" hidden="hidden">
    <button type="button" id="custom">CHOOSE AN IMAGE</button>
    <button type="submit" class="btn" id="btn">START SORTING</button>
</div>
<script src="drop.js" type="text/javascript"></script>
</body>
</html>

drop.js :

const realBtn = document.getElementById("inpFile");
const customBtn = document.getElementById("custom");
const inpFile = document.getElementById("inpFile");
const myForm = document.getElementById("myForm");
var btn = document.getElementById("btn");
btn.disabled = true;

realBtn.onchange = function(e) {
  btn.disabled = false;
}

customBtn.addEventListener("click", function(click) {
  inpFile.click();
});

myForm.addEventListener("submit", e => {
  e.preventDefault();

  const endpoint = "upload.php";
  const formData = new FormData();

  formData.append("inpFile", inpFile.files[0]);

  console.log();

  fetch(endpoint, {
    method: "post",
    body: formData
  }).catch(console.error);

  document.getElementById("btn").style.display = "none";
  document.getElementById("custom").style.display = "none";
  document.getElementById("img").style.display = "block";

  var img = document.getElementById("img");

  var fileName = ???;

  img.src = "uploads/";

}); 

upload.php :

<?php

$uploadOk = 1;
$fileName = $_FILES["inpFile"]["name"];
$fileTmpName = $_FILES["inpFile"]["tmp_name"];
$fileExtsion = explode('.', $fileName);
$fileActualExtension = strtolower(end($fileExtsion));
$fileNewName = uniqid('').'.'.$fileActualExtsion;
$targetPath = "uploads/" . basename($fileNewName);


if ($_FILES["inpFile"]["size"] > 500000000) {
    $uploadOk = 0;
}

if ($uploadOk == 1) {
    move_uploaded_file($fileTmpName, $targetPath);
}

?>
Polymood
  • 397
  • 3
  • 14
  • And what's the problem with all this code? What have you tried so far, where are you stuck? – Nico Haase Feb 27 '20 at 11:42
  • If there's a good reason to not use AJAX, then you can add a script tag to the actual HTML. Use ex. `type="javascript/template"` (or what ever __invalid__ JavaScript [mime-type](https://stackoverflow.com/questions/876561/when-serving-javascript-files-is-it-better-to-use-the-application-javascript-or)), and store the data in that tag. Then read `text` property of the script element, there you've a way to add data to a HTML page as much as needed. A real success is to store the data in JSON format ... – Teemu Feb 27 '20 at 11:51

1 Answers1

2

Within upload.php, you could return the $fileNewName value to send it as the response :

<?php

$uploadOk = 1;
$fileName = $_FILES["inpFile"]["name"];
$fileTmpName = $_FILES["inpFile"]["tmp_name"];
$fileExtsion = explode('.', $fileName);
$fileActualExtension = strtolower(end($fileExtsion));
$fileNewName = uniqid('').'.'.$fileActualExtsion;
$targetPath = "uploads/" . basename($fileNewName);


if ($_FILES["inpFile"]["size"] > 500000000) {
    $uploadOk = 0;
}

if ($uploadOk == 1) {
    move_uploaded_file($fileTmpName, $targetPath);
}

echo json_encode($fileNewName);

?>

Then get it on the fetch() response :

myForm.addEventListener("submit", e => {
  e.preventDefault();

  const endpoint = "upload.php";
  const formData = new FormData();

  formData.append("inpFile", inpFile.files[0]);

  console.log();

  var fileName;
  fetch(endpoint, {
    method: "post",
    body: formData,
    headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
  })
  .then(function (response) {
      return response.json()
  })
  .then(function (data) {
      fileName = data;
  })
  .catch(console.error);

  document.getElementById("btn").style.display = "none";
  document.getElementById("custom").style.display = "none";
  document.getElementById("img").style.display = "block";

  var img = document.getElementById("img");


  img.src = "uploads/";

});
Hasta Dhana
  • 4,699
  • 7
  • 17
  • 26
  • I see how this could work but whenI try it it gives the following error : Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise.catch (async) (anonymous) @ drop.js:38 – Polymood Feb 27 '20 at 13:46
  • I've modified the `fetch()` parameter, hope it helps – Hasta Dhana Feb 28 '20 at 08:17
  • Ok I tried your code, it still doesn't work and I still get the same error. In fact, what's is happening is that the fetch is trying to get the entire PHP code back ence the "Unexpected token error < ..." I will try to find a solution, thanks again for your help ! – Polymood Feb 28 '20 at 09:20