Home > Net >  Ajax Post request to call javascript function
Ajax Post request to call javascript function

Time:06-18

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

CodePudding user response:

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>';
}
?>
  • Related