user2598812
user2598812

Reputation:

AJAX upload file and text not work

I am using this ajax code for submit form and upload multiple input file. I want to send all form data via ajax. The text input successfully send but file input was not successful post via ajax! How to change this code?

$("#add_order").click(function () {

    //*****get data input
    var formData = new FormData(); 
        formData.append( 'action', 'add_order');
        formData.append( 'customer_name', $('input[name=customer_name]').val());
        formData.append( 'date', $('input[name=date]').val());
        formData.append( 'order_status', $('input:radio[name=order_stautus]').val());
        formData.append( 'total_price', $('input[name=totalprice]').val());
        formData.append( 'quits', $('input[name=quits]').val());
        formData.append( 'debt', $('input[name=debt]').val());
        formData.append( 'desc', $('#desc').val());
        formData.append( 'desc2', $('#desc2').val());

    $.each($("input[type=file]"), function(i, obj) {
        $.each(obj.files,function(j,file){
            formData.append('photo['+i+']', file);
        });
    });
    $.ajax({
        url: "includes/ajax/ajax.php",
        data: formData,
        processData: false,
        contentType: 'multipart/form-data',
        type: 'POST',
        dataType:'json',
        success: function(response){
           //load json data from server and output message     
           if(response.type == 'error'){ //load json data from server and output message     
               output = '<div class="alert alert-danger">'+response.text+'</div>';
           }else{
               output = '<div class="alert alert-danger">'+response.text+'</div>';
           }
           $("#results").append(output).slideDown();
        } 
    });        
});

PHP code for get form data:

if($_POST['action']=='add_order'){

    $customer_id = 1;
    $date = $_POST['date'];
    $status = $_POST['order_status'];
    $total_price = $_POST['total_price'];
    $quits = $_POST['quits'];
    $debt = $_POST['debt'];
    $desc = $_POST['desc'];
    $desc2 = $_POST['desc2'];

    for($i=0; $i<count($_FILES['photo']['name']); $i++) {
        //Get the temp file path
        $tmpFilePath = $_FILES['photo']['tmp_name'][$i];

        //Make sure we have a filepath
        if ($tmpFilePath != ""){
          //Setup our new file path
          $newFilePath = "../../uploads/orders/" . $_FILES['photo']['name'][$i];

          //Upload the file into the temp dir
          if(move_uploaded_file($tmpFilePath, $newFilePath)) {

            //Handle other code here

          }
        }
      }

formData console.log: enter image description here

Upvotes: 2

Views: 1530

Answers (2)

Drazen Bjelovuk
Drazen Bjelovuk

Reputation: 5472

According to this, contentType must be set to false for ajax file uploads.

And perhaps try naming all your files photo[] rather than photo[n] to let your PHP server handle the array conversion. See http://php.net/manual/en/features.file-upload.multiple.php.

Upvotes: 0

Marco Moschettini
Marco Moschettini

Reputation: 1735

You have to use JSON.stringify:

$.ajax({
    type: 'post',
    data: {form_data: JSON.stringify(formData)},
    contentType: 'application/json',
    dataType: 'json'
});

You also need to specify "application/json" instead of "multipart/form-data". You can check if your json string is correctly formatted with a tool like this: http://jsonlint.com/.

On PHP side you have to decode the incoming data like this:

json_decode($_POST[form_data]);

Note that dataType in your request specifies what are you expecting to receive from server and contentType is the content type you are sending.

In your PHP file you have to encode your response in json format accordingly to the json format:

echo json_encode($my_response);

EDIT: Here's some hint on accessing json object on the PHP side:

<?php

$my_json = json_decode($_POST["form_data"]);
$action = $my_json["action"];

/*
 DO STUFF
*/

$response = array('error' => "My error");
if(/* all is correct */)
    $response = array('response' => "My response", 'id' => 3);

echo json_encode($response);

?>

Upvotes: 0

Related Questions