0

How can I use return a value from a PHP function to a JavaScript variable? Example:

PHP:

// Destination folder for downloaded files

$date = date('m.d.y'); 
mkdir("uploads/" . $date, 0777, true); 
$upload_folder = 'uploads/' . $date;

// If the browser supports sendAsBinary () can use the array $ _FILES
if(count($_FILES)>0) { 
    if( move_uploaded_file( $_FILES['upload']['tmp_name'] , $upload_folder.'/'.$_FILES['upload']['name'] ) ) {
        echo 'done';
    }
    exit();
} else if(isset($_GET['up'])) {
    // If the browser does not support sendAsBinary ()
    if(isset($_GET['base64'])) {
        $content = base64_decode(file_get_contents('php://input'));
    } else {
        $content = file_get_contents('php://input');
    }

    $headers = getallheaders();
    $headers = array_change_key_case($headers, CASE_UPPER);

    if(file_put_contents($upload_folder.'/'.$headers['UP-FILENAME'], $content)) {
        echo 'done';
    }
    exit();
}

$pathinfo = realpath($upload_folder);
return $pathinfo;

Javascript

this.MakeRequest = function()
{
  var somename = "somenameTest";
  var xmlHttp = getXMLHttp();

  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
      HandleResponse(xmlHttp.responseText);
    }
  }

  xmlHttp.open("GET", "download.php", true); 
  xmlHttp.send();
}

function HandleResponse(response)
{
  document.getElementById('output').innerHTML = response;
      **var x = php return varible**

}

2 Answers 2

1
function HandleResponse(response)
{
  document.getElementById('output').innerHTML = response;
      var x = <?php echo json_encode($pathinfo);?>; 

}
Sign up to request clarification or add additional context in comments.

3 Comments

no it's not working, when i put this line to in my code thereafter my javascript not responding.
I added ; to the end of php statement
this is my file structure, index.php css.css uploader.php dragdrop.js index.php have only this JS if(window.attachEvent){ window.attachEvent("onload",init); }else{ window.addEventListener("load",init,false); } var getInstance; function init(){ getInstance = new uploader('drop', 'status', 'uploader.php', 'list'); } document.getElementById('test').onclick = function(){ getInstance.MakeRequest(); }
0

Simply echo your PHP variable:

var x='<?php echo $pathinfo; ?>';

good luck!

1 Comment

not working, it's alert like this: <?php echo $pathinfo; ?>, not the pathinfo value

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.