在 php 中的 mp4 =>mp3 转换后更改 js/ajax 中的按钮文本

2022-01-09 00:00:00 progress-bar upload php javascript ajax

我正在处理 html 表格行(目前是两个),如下所示,其中单击按钮:

=> JS/jQuery 代码被调用(其中 Go 文本更改为 Converting)
=> 然后通过 AJAX 编写 convert.php 脚本,在该脚本中将 mp4 转换为 mp3.

<块引用>

html/php代码:

 <?php foreach ($programs as $key => $program) { ?><tr data-index="<?php echo $key; ?>"><td><input type="submit" id="go-btn" name="go-button" value="Go" data-id="<?php echo $key; ?>"></input></td></tr><?php }?>

<块引用>

转换.php:

 $f = $mp4_files[$_POST['id']];$parts = 路径信息($f);开关($parts['extension']){案例mp4":$filePath = $src_dir .DS .$f;system('C:ffmpeginffmpeg.exe -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $结果);print_r("你好世界");休息;}

<块引用>

JS/jQuery 代码:

$("input[name='go-button']").click( function() {//更改按钮的文本,并禁用$(this).val("Converting").attr("disabled", "true");});

只要单击上面 html/php 代码中的按钮,UI 中的文本就会从 Go 更改为 Converting因为我在我的代码库中添加了 JS/jQuery 代码,但是我添加的这个 JS/jQuery 代码只更改了文本.它实际上并不知道转换是在后台发生的.

问题陈述:

我想知道我需要在上面的 JS/jQuery 代码中做哪些修改,以便 UI 真正知道转换是在后台发生的.

可能,我们需要在 JS/jQuery 和上面的 php 代码之间添加 make 建立一些连接,但我不确定我们该怎么做.

解决方案

首先,让我们修复html.您的按钮不需要 nameid 属性,它们不会是唯一的,因为您是在循环中编写它们.只需将它们替换为 class="converter".<input> 标签不需要结束 </input>.

submit 类型的按钮具有默认行为(您不想与 ajax 请求结合使用).您可以使用 e.preventDefault(); 像 this 或将标签更改为不会触发表单提交.

未经测试的代码:

js

$(document).ready(function () {$("input.converter").click(函数 (e) {e.preventDefault();让 btn = $(this);btn.val("正在转换").attr("已禁用", "true");$.ajax({缓存:假,类型:发布",数据类型:json",数据:{id:btn.data('id')},网址:转换.php",成功:功能(响应){btn.val(response.message).attr("disabled", response.message == "Converted" ? "false" : "true");},错误:函数(jqXHR,状态,错误){console.log("请求失败:" + status);},完成:功能(jqXHR,状态){console.log("完成.无论结果如何");}});返回假;});});

php

if (empty($mp4_files[$_POST['id']])) {exit(json_encode(['message' => '失败']);}$f = $mp4_files[$_POST['id']];$parts = 路径信息($f);开关($parts['extension']){案例mp4":$filePath = $src_dir .DS .$f;system('C:ffmpeginffmpeg.exe -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $结果);exit(json_encode(['message' => 'Converted']);}exit(json_encode(['message' => '无效的文件类型']);

<小时>

这是一个快速演示(在本地测试可以工作):

main.php

<!DOCTYPE html><html><头><script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><脚本>$(文档).ready(函数 () {$("按钮").click(函数 (e) {e.preventDefault();让 btn = $(this);btn.html("正在转换...").attr("已禁用", "true");$.ajax({缓存:假,类型:发布",数据类型:json",数据:{id:btn.data('id')},网址:转换.php",成功:功能(响应){btn.html(response.message).attr("已禁用", response.message != "Bad");//如果不好则重新启用}});});});</脚本></头><身体>

转换.php

表现如何:

------------------------------------------- 启用 -> 禁用...... -> 禁用

  • 按钮 #1 文本进度:转换 -> 正在转换... -> 好
  • 按钮 #2 文本进度:转换 -> 正在转换... -> 错误(已启用)
  • 按钮 #3 文本进度:转换 -> 正在转换... -> 错误

I am working on html table rows (which is two at this moment) as shown below in which on button click:

=> JS/jQuery code is called (where Go text changes to Converting)
=> and then convert.php script through AJAX where conversion of mp4 into mp3 happens.

html/php code:

  <?php  foreach ($programs as $key => $program) {  ?> 
       <tr data-index="<?php echo $key; ?>">
          <td><input type="submit"  id="go-btn" name="go-button" value="Go" data-id="<?php echo $key; ?>" ></input></td>
       </tr>
    <?php }?>

convert.php:

 $f = $mp4_files[$_POST['id']];
 $parts = pathinfo($f); 
 switch ($parts['extension'])
 {  
     case 'mp4' :
         $filePath = $src_dir . DS . $f;
         system('C:ffmpeginffmpeg.exe -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $result);    
         print_r("Hello World");
         break;                  
 } 

JS/jQuery code:

$("input[name='go-button']").click( function() {

  // Change the text of the button, and disable
  $(this).val("Converting").attr("disabled", "true");

});

As soon as the button is clicked from the html/php Code above, the text gets changed from Go to Converting in the UI because I have added JS/jQuery code in my codebase but this JS/jQuery code which I have added just change the text only. It doesn't actually know that the Conversion is happening in the background.

Problem Statement:

I am wondering what modification I need to do in the JS/jQuery code above so that UI actually knows that conversion is happening in the background.

Probably, we need to add make establish some connection between JS/jQuery and php code above but I am not sure how we can do that.

解决方案

First, let's fix the html. You don't need name or id attributes on your button and they won't be unique because you are writing them in a loop. Just replace them with class="converter". The <input> tag doesn't need a closing </input>.

A submit type button has a default behavior (which you don't want to combine with an ajax request). You can either use e.preventDefault(); like this or change the tag to something that does not fire a form submission.

Untested Codes:

js

$(document).ready(function () {
    $("input.converter").click(function (e) {        
        e.preventDefault();
        let btn = $(this);
        btn.val("Converting").attr("disabled", "true");
        $.ajax({
            cache:    false,
            type:     "POST",
            dataType: "json",
            data:     {id: btn.data('id')},
            url:      "convert.php",
            success:  function(response) {
                btn.val(response.message).attr("disabled", response.message == "Converted" ? "false" : "true");
            },
            error: function (jqXHR, status, err) {
                console.log("Request failed: " + status);
            },
            complete: function (jqXHR, status) {
                console.log("Done. No matter the outcome");
            }
        });
        return false;
    });
});

php

if (empty($mp4_files[$_POST['id']])) {
    exit(json_encode(['message' => 'Failed']);
} 
$f = $mp4_files[$_POST['id']];
$parts = pathinfo($f); 
switch ($parts['extension'])
{  
    case 'mp4' :
        $filePath = $src_dir . DS . $f;
        system('C:ffmpeginffmpeg.exe -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $result);    
        exit(json_encode(['message' => 'Converted']);
} 
exit(json_encode(['message' => 'Invalid File Type']);


Here's a quick demo (tested locally to work):

main.php

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $("button").click(function (e) {        
        e.preventDefault();
        let btn = $(this);
        btn.html("Converting...").attr("disabled", "true");
        $.ajax({
            cache:    false,
            type:     "POST",
            dataType: "json",
            data:     {id: btn.data('id')},
            url:      "convert.php",
            success:  function(response) {
                btn.html(response.message)
                   .attr("disabled", response.message != "Bad"); // re-enables if Bad
            }
        });
    });
});
</script>
</head>
<body>
<?php
for ($i = 0; $i < 3; ++$i) {
    echo "<div>{$i}: <button data-id="{$i}">Convert</button></div>";
}
?>
</body>
</html>

convert.php

<?php
$lookup = [
    'Good',
    'Bad'
];
sleep(1);
echo json_encode(['message' => $lookup[$_POST['id']] ?? 'Error']);

How it performs:

------------------------------------------- enabled -> disabled...... -> disabled

  • Button #1 Text Progression: Convert -> Converting... -> Good
  • Button #2 Text Progression: Convert -> Converting... -> Bad (enabled)
  • Button #3 Text Progression: Convert -> Converting... -> Error

相关文章