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

前端 未结 2 1599
猫巷女王i
猫巷女王i 2020-12-12 08:22

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

=> JS/jQuery

相关标签:
2条回答
  • 2020-12-12 08:25

    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
    0 讨论(0)
  • 2020-12-12 08:45

    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.

    0 讨论(0)
提交回复
热议问题