簡體   English   中英

在 PHP 發布請求中調用 js function

[英]calling js function in PHP Post Request

I'm trying to call a javascript function after making a POST request using Jquery $.post() post request sends base64 image data and writes it down in the server the problem is that the post request is done and the file is uploaded but there沒有 javascript function 調用getCounterNumber(); 不工作,function 應該這樣做

function getCounterNumber(Path){
  Tesseract.recognize(
  Path,
  'eng',
  { logger: m => console.log(m) }
).then(({ data: { text } }) => {
   window.location.href = "getcounterreading.php?counterNumber="+text+"";
})
}

jQuery crop button單擊

            var base64data = reader.result;
            $.post('http://127.0.0.1/counter/uploadcounter.php', {image:base64data}, 
            function(response){ 
                  bs_modal.modal('hide');
                  alert("success upload image");
                      window.location.href = "uploadcounter.php";
                      console.log(response);

              });

上傳計數器.php

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$folderPath = '../../uploads/counters/';

$image_parts = explode(";base64,", $_POST['image']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . uniqid() . '.png';
file_put_contents($file, $image_base64);
echo ("image uploaded successfully.");
console.log($file);
echo '<script>getCounterNumber("'.$file.'")</script>'; 
}

不要返回標簽。 改為返回 JSON。

你的 Javascript

(我使用 $.ajax() 而不是 $.post() 沒有特別的原因。也許是因為它更具描述性):

let base64data = reader.result;
let postData = { image:base64data };

$.ajax({
    type: "POST",
    url: 'http://127.0.0.1/counter/uploadcounter.php',
    data: postData,
    success: (result) => {
        bs_modal.modal('hide');
        getCounterNumber(result.data.file);
        alert("success upload image");
        console.log(response);
    },
    error: (error) => {
        alert("There was an error. Check JS Console.");
        console.log(error);
    },
    dataType: 'json'
});

你的 PHP

if ('POST' === $_SERVER['REQUEST_METHOD']) {
    $folderPath = '../../uploads/counters/';
    
    $image_parts = explode(";base64,", $_POST['image']);
    $image_type_aux = explode("image/", $image_parts[0]);
    $image_type = $image_type_aux[1];
    $image_base64 = base64_decode($image_parts[1]);
    $file = $folderPath . uniqid() . '.png';
    file_put_contents($file, $image_base64);
    
    header("Content-Type: application/json");
    echo json_encode(["file" => $file]);
    exit();
}

請注意,我沒有運行也沒有測試過代碼。 這只是一個示例,您可以將其作為靈感。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM