2

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

  • "I want to get all form data along input files and upload files. But not upload files!" Please clarify. This makes no sense. – Drazen Bjelovuk Apr 09 '15 at 23:16
  • @JoshBjelovuk The question was corrected –  Apr 09 '15 at 23:25
  • I think you are missing to stringify your object before sending it with ajax. Should be something like this: `JSON.stringify(formData)`. Are you sure that your JSON is syntactically correct? Maybe some console.log can help. – Marco Moschettini Apr 09 '15 at 23:40
  • @MarcoMoschettini console.log Image added to question. –  Apr 09 '15 at 23:50

2 Answers2

0

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.

Community
  • 1
  • 1
Drazen Bjelovuk
  • 4,376
  • 4
  • 30
  • 54
0

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);

?>
Marco Moschettini
  • 1,258
  • 2
  • 11
  • 24