1

I have the following form which has

  • a text field
  • date field
  • a file browser.

I am using AJAX to send the $_POST data values to another PHP file to insert into a MySQL database. But I want to move the $_FILES too.

In the $.ajax field, there is data: whereby I can assign those data to be transferred to another PHP file.

I am able to do it with the text field and date fields. How to do it for the $_FILES? My codes are as below

AJAX

<script>
    $("#submit").click(function() {
        var prjId = $('#prjId').val();
        var updatedDate = $('#updatedDate').val();
        $.ajax({
            type: 'POST',
            url: "process.php",
            data: {prjId: prjId,updatedDate: updatedDate},
            success: function(response) {('#resulting').html(response);}
        });
    });
</script>

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="icon" type="image/png" href="images/version-control.png">
        <meta charset="utf-8">
        <link href='https://fonts.googleapis.com/css?family=Raleway:400,300,700,900' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <!-- jQuery library -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <!-- Latest compiled JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <body>
    <body>
        <div class="container" id="contactform">
            <form method="post" enctype="multipart/form-data">
                <div class="form-group row">
                    <label class="col-sm-3 col-form-label">Project ID</label>
                    <div class="col-sm-7"><?php if(isset($_POST['prjId'])){echo '
                        <input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId" value="'.$_POST['prjId'].'">';}else{echo'
                        <input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId">';}?>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-sm-3 col-form-label">Updated Date</label>
                    <div class="col-sm-7"><?php if(isset($_POST['udatedDate'])){echo '
                        <input type="date" class="form-control" name = "updatedDate" id="updatedDate" value="'.$_POST['udatedDate'].'">';}else{echo '
                        <input type="date" class="form-control" name = "updatedDate" id="updatedDate">';}?>
                    </div>
                </div>
                <fieldset class="form-group ">
                    <label class="btn btn-default tempPerm" id="techLabelText">
                        <input class="tempPerm" style="" type="file" name="file" id="techInputBoxValue" />
                    </label>
                </fieldset>
            </form>
            <div class="cover">
                <div id="result"></div>
                <input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
            </div>
        </div>
    </body>
</html>

PHP

<?php include ("../db.php");?>
<?php
    $prjId = $_POST['prjId'];
    $updatedDate = $_POST['updatedDate'];
    if(isset($prjId)){
        $sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
        mysqli_query($conn, $sql);
    }
?>
Anu
  • 1,123
  • 2
  • 13
  • 42
  • formdata is what you need – Wils Apr 17 '18 at 03:24
  • but how to give the formdata? i mean in the AJAX field for normal text field i can give as data: {var: text1, var, text2}. But how to insert formdata here? – Anu Apr 17 '18 at 03:27
  • var fd = new FormData(); fd.append( 'file', input.files[0] ); – Wils Apr 17 '18 at 03:29
  • @Wils If I use this way, how can I access the file name temp_name etc in php? I need to upload the file as well as to get the file name in my database using move_uploaded_file. So how should I type in php in order to get the variables such as file name, tmp_name etc? – Anu Apr 17 '18 at 03:49
  • it is actually the same. It receive as $_POST['file'] – Wils Apr 17 '18 at 03:56
  • Thank you @Wils. I used new FormData($('form')[0]); method to collect all data at once so that I don't need to assign key: value pair in the data: of AJAX. Your method also helped me to think deeper and understand AJAX. Thanks a lot – Anu Apr 17 '18 at 05:52
  • you are welcome. – Wils Apr 17 '18 at 05:53

3 Answers3

2

The code below automatically includes all fields from the form without manually adding them using the append function.

Also added $(document).ready(function() for fail safe. So the javascript code only takes effect when the whole document is ready.

You can try tinker with these working template.

<script>
$(document).ready(function() {
  $("#submit").click(function() {
    var FD = new FormData($('form')[0]);
    $.ajax({
      type: 'POST',
      url: "process.php",
      processData: false,
      contentType: false,
      data: FD,
      success: function(response) {
        $('#resulting').html(response);
      }

    });
  });
 });
</script>

process.php

<?php include ("../db.php");?>
<?php
    $prjId = $_POST['prjId'];
    $updatedDate = $_POST['updatedDate'];

    if(isset($_POST['prjId'])){
        $target_dir = "uploads/";
        $target_file = $target_dir.basename($_FILES["file"]["name"]);
        $save_file = basename($target_file); // this holds the filename to save.
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        $is_uploaded = move_uploaded_file($_FILES["file"]["tmp_name"], $target_file));

        // Modify this query string to add the file uploaded as well.  
        // Change the query string to use prepared statements for failure safe and for security reasons.
        $sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
        mysqli_query($conn, $sql);
    }
?>

^ Added a simple file upload handler.

Karlo Kokkak
  • 3,674
  • 4
  • 18
  • 33
  • This works very well!! But now I have another question. What if I have more than one file uploader? How to differentiate from one to another? – Anu Apr 17 '18 at 05:26
  • 1
    You can can assign a new html file field a unique name. And in your PHP handler, you can access the new file using that name you assigned like `$_FILES['newuploader']`. – Karlo Kokkak Apr 17 '18 at 05:32
  • 1
    Alternatively, rather than creating a new field with a unique name, you can just create an array of file inputs using `[]`. Like - ` `. – Karlo Kokkak Apr 17 '18 at 05:41
  • 1
    Thanks a lot! This works like charm. I am giving tick to your answer! – Anu Apr 17 '18 at 05:45
0

You can use formdata to send your files along with your request like this:

<script >
  $("#submit").click(function() {
    var formData = new FormData();
    var prjid = $('#prjId').val();
    var updatedDate = $('#updatedDate').val();
    formData.append( 'file', input.files[0]);
    formData.append('prjId', prjid);
    formData.append('updatedDate', updatedDate);

    $.ajax({
      type: 'POST',
      url: "process.php",
      data: formData,
      contentType: false,       
      cache: false,             
      processData:false, 
      success: function(response) {
        $('#resulting').html(response);
      }

    });
  });

</script>
Haider Ali
  • 1,081
  • 8
  • 23
0

If you submit form using ajax it will not pass $_FILES

you have to create object for that using FormData

note : please add enctype="multipart/form-data in form tag

 <form id="upload" enctype="multipart/form-data">

please refer : jQuery AJAX file upload PHP

Thanks

Affan
  • 1,132
  • 7
  • 16