Send $_POST and $_FILES together using AJAX data field so that PHP can grab the value?

Anu

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);
    }
?>
Karlo Kokkak

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Using POST via AJAX and PHP to send data

can not Send data to php file using ajax

Can't get value from Summernote textarea using Javascript AJAX send post data

How to send button value to PHP backend (POST) using ajax

How to send input file data value using ajax to a php page

How can I send "special" data in a POST request using PHP

Send data with ajax but empty $_POST in php

Unable to send POST value using AJAX

Send $_POST data between php files

Send PHP POST using Javascript AJAX

Creating a VSTS Extension, using WIQL query to grab work item data, can I grab Activity field data?

Send text field value using href to php

how can i send post data from a textbox value through ajax jquery

php can not get the data send by ajax

Spring send formdata with files and value of input ajax post

Can a php script called using Ajax post send back SSE events while the script executes

send post data from js to php using ajax without type cast

Jquery ajax post doesn't send data to server end(Using PHP)

Send html form data to php using post request with ajax to a https://foo.com

How can I get files by javascript and post send for ajax

using ajax to send javascript data to php

Send data to a php function using .ajax

Send image using XMLHttpRequest and grab with php

How to send data to php file api using http post with same key but multiple value?

Retrieve array data on POST using PHP Ajax

PHP form passing post data using AJAX

PHP POST data to another page using AJAX

How to POST data to php file using AJAX

how to pass data to php by using ajax .post()