1

as the title says I want to call a javascript function with a PHP variable so i used ajax request the send the variable called [ filename ] to execute the javascript function like

upload.php


<script>
    function prepareforconvert(filenamse){
            $.post('prepare.php', {filename: filenamse}, function(response){ 
            alert('done');
        });
    }
</script>

      if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file))
      {
          $target_file   = $target_dir . basename($_FILES["uploadedFile"]["name"]);
          echo "File ". basename( $_FILES["uploadedFile"]["name"]). " uploaded success.";
          echo $target_file;
          echo '<script>prepareforconvert("'.$target_file.'")</script>';

      }

the code should call first the function prepareforconvert and then send a post request to prepare.php with the parameter $target_file

prepare.php

<script src='scripts\prepare.js'></script>
<?php
$UploadedImage = $_POST['filename'];
if (!empty($_POST["mail"])){
          echo '<script>readFile("'.$UploadedImage.'")</script>';
}
?>

prepare.js contains readFile js function

async function readFile(fileName) {
  console.log({ fileName });

  return await Tesseract.recognize(fileName, 'ara', {
  
    logger: m => console.log(m)
  });

}
async function parseDataFromTextAndPropertyNames(text, propertyNames) {
  console.log({ text, propertyNames });

  return propertyNames
    .reduce((table, key) =>
      Object.assign(table, {

        [ key ]: RegExp(`${ key }\\W+(\\w+)`)
          .exec(text)?.[1] ?? ''

      }), {});
}
async function writeParsedTextDataAsJSON(fileName, table) {
  console.log({ table });
   JSON.stringify({ table });

  // fake it ...
  return (await new Promise(resolve =>
    setTimeout(() => {

      console.log({ fileName, json: JSON.stringify({ table }) });
      resolve({ success: true });

    }, 1500)
  ));
}

console.log('... running ...');

(async () => {
  const { data: { text } } = await readFile('gfhgf.png');

  const data = await
    parseDataFromTextAndPropertyNames(text, ['نقطة الخدمة', 'رقم العداد']);
 document.getElementById("dvjson").innerHTML = JSON.stringify(data, undefined, 4);
 const final = [JSON.stringify(data)];
 console.log(data);
 console.log(text);
 const ff = [JSON.parse(final)];
 console.log(final)
 console.log(ff);
 constructTable('#table',ff);
   $("#table").excelexportjs({
  containerid: "table", 
  datatype: 'table', 
  dataset: data, 
  columns: getColumns(data)     
  });
  const result = await writeParsedTextDataAsJSON('myjsonfile.json', data);

  console.log({ result });
})();

as you can see all of the functions are async but I want to organize this code to work only when calling the function readFile from the prepare.php after the post request. how can i accomplish that and thanks

3
  • Instead of echo '<script>prepareforconvert("'.$target_file.'")</script>'; and then a separate AJAX request, it would make a lot more sense to just write require "prepare.php"; in that location instead. Commented Jun 17, 2022 at 0:13
  • How is upload.php called? Is it through an HTML form: <form action="upload.php"... ? Commented Jun 17, 2022 at 0:30
  • 1
    What is sent back to the client through the AJAX request, from prepare.php, <script src='scripts\prepare.js'></script>, and possibly <script>readFile("'.$UploadedImage.'")</script>, comes through as text in the response variable provided by the JQuery post() function: $.post('prepare.php', {filename: filenamse}, function(response){. Now you would have to use Javascript to do something with that text. Better yet, as @ADyson suggests, skip the extra AJAX call, which I expect is not working the way you think it will, and require "prepare.php";. Commented Jun 17, 2022 at 0:35

1 Answer 1

1

Instead of

echo '<script>prepareforconvert("'.$target_file.'")</script>';

and then a separate AJAX request, it would make a lot more sense to just write

require "prepare.php";

in that location instead.

The AJAX request seems to be redundant - you don't need an extra round-trip to the server, because all the information that prepare.php needs is already present within upload.php...nothing new is being added by the client-side code which then runs your AJAX request.

Also just modify prepare.php slightly so it doesn't expect a POST variable:

<script src='scripts\prepare.js'></script>
<?php
if (empty($target_file)){
    echo '<script>readFile("'.$target_file.'")</script>';
}
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.