Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

javascript - change button text in js/ajax after mp4 =>mp3 conversion in php

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...