Alex
Alex

Reputation: 50

PHP to Jquery submit request

I'm new with this and i don't know how to implement this PHP script into jQuery to submit my form and output the accept and decline message. Can someone help me with this?

PHP SCRIPT:

<?php
if (isset($_POST['file']) && !empty($_POST['file']))
{    
$mp3file= new MP3File($_FILES['file']['name']);
$duration = $mp3file->getDuration();

 $time_limit = "02:10"; // Time limit

 $accepted = "Your music has: ".MP3File::formatTime($duration)." seconds.</br> And is accepted by our terms ";
 $declined = "Your music has: ".MP3File::formatTime($duration)." seconds and is not accepted by our terms"; 

if(MP3File::formatTime($duration) <= $time_limit) 
{
$audio=basename($_FILES['file']['name']);
$audio=str_replace(' ','',$audio);
$tmppath1="music/".$audio;
move_uploaded_file($_FILES['file']['tmp_name'],$tmppath1);

$link = mysqli_connect("localhost", "root", "", ""); 
$save=mysqli_query($link,"INSERT INTO music (location, userid) VALUES ('$tmppath1','1')");
echo $accepted;

} else {
  echo $declined;
}
 } 
?>

HTML FORM:

<form action="" method="POST" enctype="multipart/form-data" id="upload" name="upload">  
<div class="bs-example">
<label class="btn-bs-file btn btn-success">SELECT MUSIC</label>
<input id="input-1a" type="file" class="file" name="file" data-provides="file">

<button type="submit" name="submit" class="btn-bs-file btn btn-sm btn-danger" value="SUBMIT MUSIC"></button>
  </div>
</form>

Update improved:

JQUERY Script based @Jude Fernandes response:

<script type="text/javascript">
    "use strict";
    $("#upload").submit(function (e) {
        e.preventDefault();
         var form_data = new FormData();
         form_data.append('file', $('#input-1a').prop('files'));

          $.ajax({
            url: "upload-music.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            success: function (data) {
                console.log(data);

            },
            error: function () {

            }
        });

    });

</script>

Upvotes: 0

Views: 127

Answers (1)

Jude Fernandes
Jude Fernandes

Reputation: 7517

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="" method="POST" enctype="multipart/form-data" id="upload" name="upload">
    <div class="bs-example">
        <label class="btn-bs-file btn btn-success">SELECT MUSIC</label>
        <input id="input-1a" type="file" class="file" name="file" data-provides="file">

        <button name="submit" type="submit" class="btn-bs-file btn btn-sm btn-danger" value="SUBMIT MUSIC"></button>
    </div>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    "use strict";
    $("#upload").submit(function (e) {
        e.preventDefault();
         var form_data = new FormData();
         form_data.append('key_file', $('#input-1a').prop('files')[0]);

          $.ajax({
            url: "http://example.com/foo.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            success: function (data) {
                console.log(data);

            },
            error: function () {
               // Handle an error in the connection
            }
        });

    });

</script>
</body>
</html>

This is what the front end file should looks like, I have made a few modifications to the form ie, the button is of type submit so jquery catches the event when you press submit.

The line e.preventDefault(); prevents the default action of the form which is to submit the form and reload the page, instead jquery processes the request and submits it.

The var form_data = new FormData(); is a convenient helper where you can add all the parameters that you want to send to the backend in the format form_data.append('key', 'value');

A slight modification in the backend, you can replace the line if(isset($_POST['submit'])!="") with if (isset($_POST['key_file']) && !empty($_POST['key_file'])) the key_file is what you are sending from the front end so you need to check if that key is set and it exists.

$("#upload").submit(function (e) specifies that jquery needs to catch the submit event of a form with an id=upload.

P.S. Open inspect element on your browser and goto the networks tab and monitor the params being sent and the response coming back, it will help you alot

Upvotes: 1

Related Questions