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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…