user1559811
user1559811

Reputation: 449

run javascript function only if php conditions are met

I want the start_uploading function only to start if all the conditions are met and the file is uploading, right now the 'loading' message pops up for a split second when the form is submitted but it did not meet all the conditions to upload.

if(condtion){// don't start function} else

if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) {
  //now start function} else echo "error";

javascript

function start_Uploading(){
  document.getElementById('message').innerHTML = 'Loading... <br> Please Wait';
  return true;
}

and html

<form action="something.php" method="POST" enctype="multipart/form-data"
 onsubmit="start_Uploading();">    

Upvotes: 0

Views: 639

Answers (2)

Taha Paksu
Taha Paksu

Reputation: 15616

move_uploaded_file() is copying the uploaded file from apache's temp directory to user directory, so when you submit the file, so it would be already uploaded to the temp directory before the php side can start processing that file.

So, I recommend you to use a client side (javascript) form validation, or make a research about AJAX file uploads and/or form validation. PHP is a server side language, and runs before a page loads. Not inside a page. (Unless it's an AJAX call from client.)

Upvotes: 1

Dennis Hackethal
Dennis Hackethal

Reputation: 14275

Since you are checking for the condition to be true in php, I would simply only echo out the js method name if the condition is met.

Like so:

<?php
  if(true) $onsubmit = "start_Uploading();"; // Put actual condition in parantheses
  else $onsubmit = "";
?>

And then in your form:

<form action="something.php" method="POST" enctype="multipart/form-data"
onsubmit="<?php echo $onsubmit; ?>">

If the condition isn't met, no method name will be provided and js simply won't know what to look for on submit.

Upvotes: 2

Related Questions