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

时光总嘲笑我的痴心妄想 提交于 2019-11-30 06:06:59

问题


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:\ffmpeg\bin\ffmpeg.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.


回答1:


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:\ffmpeg\bin\ffmpeg.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



回答2:


Try changing this:

$.ajax({
            url: 'convert.php',
            type: 'POST',
            data: {id: target}, //change to what you want
            success: function(res)
            {   
            },
            error: function(res)
            {
            }
        })

To this:

$.ajax({
        url: 'convert.php',
        type: 'POST',
        data: {id: target}, //change to what you want
        success: function(res)
        {   
//You can add $(".go-btn").html('completed'); to here, but I prefer the other way.
        },
        error: function(res)
        {
// This is unnecessary if you are not gonna make it do anything if error occurs.
        }
    }) 
.done(function(data) {
$('.go-btn').html('Completed!');
//This fires when AJAX call suceeds the process. As a side note, "data" is what your .php code outputs, so you can do whatever you want to do with it.
});

And also see my comments. I hope this helps.



来源:https://stackoverflow.com/questions/56533375/change-button-text-in-js-ajax-after-mp4-mp3-conversion-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!