0

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>
5
  • To submit using jQuery you do $("#upload").submit(); Commented Feb 4, 2018 at 5:01
  • Yes, but i don't know to output accepted and decline message Commented Feb 4, 2018 at 5:02
  • in your php code you have to return an array {success:true, message:'My accepted/declined message'} or however you want to structure the array. Commented Feb 4, 2018 at 5:05
  • Thanks for the reply @altoids, can you help me with an example? I'm new and i don't know how exactly to do that.. Commented Feb 4, 2018 at 5:10
  • 1. Post your jquery in your original post. 2. replace echo $accepted with return $accepted. Same thing with echo $declined Commented Feb 4, 2018 at 5:17

1 Answer 1

1
<!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

Sign up to request clarification or add additional context in comments.

10 Comments

I have done as you mentioned, but in the console i have nothing, i have modified the isset as you told me to do.
Do you have an error in your console? There's no request being made in the networks tab under XHR?
Thanks for the reply, no i don't, only : XHR finished loading: POST
I have changed the prop files [0] to files and now i get: b>Notice</b>: Undefined index: file
When you say XHR finished loading: POST do you mean some other request completed or your request completed?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.