skip to Main Content

I’m trying to upload product to my PHP upload system, that includes multiple variables, images among them.

I’m using ajax function to transfer string variables and newForm() (that related to images fetched from input[type="file"]). The main goal is to upload the image and strings in upload.php file using the data I’m fetching from ajax.

But there are troubles transfering the image value, once I send all the data together (including images) the system fails to transfer the data, because I’m forced to use processData: false, otherwise it fail to run the ajax function.

This attribute blocks the entire data transfer to my PHP file.

How can I over come processData: false influence, and transfer multiple strings and newForm() using AJAX to upload.php file?

AJAX:

      var proname = $('#proname').val();
      var prodescription = $('#prodescription').val();
      var content = $('#content').val();
      var price = $('#price').val();

      //Main image upload
      var file_main = $('#file').prop('files')[0];
      var main = new FormData();
      main.append('file', file_main);


      //Serval images upload
      var file_images = $('#files').prop('files')[0];
      var images = new FormData();
      images.append('files', file_images);




      //Checkboxes
      var tag = new Array();
      $("#tag input:checked").each(function() {
         tag.push($(this).val());
      });
      var color = new Array();
      $("#color input:checked").each(function() {
         color.push($(this).val());
      });


      //Ajax data transfer to upload.php
      $.ajax({
          type: 'POST',
          dataType: 'json',
          processData: false,
          url: 'upload.php',
          data: { proname: proname,
                  prodescription: prodescription,
                  content: content,
                  price: price,
                  tag: tag,
                  color: color,
                  file: main,
                  files: images
                }, // All the data as $_GET in php
          cache: false,
          success: function (result) {
            $('#success').html(result);
            console.log(result);
          }
        });

Upload.php

//Defines
$code = getRandomWord();
$productName = $_POST["proname"];  // Product name
$productDescription = $_POST["prodescription"]; // Product description
$productContent = $_POST["content"]; // Product content
$price = $_POST["price"]; // Product price
$date = date("d-m-Y"); // Product upload date
$date = date("Y-m-d",strtotime($date));



//Statements
if(empty($productName)){
    echo "שם מוצר חסר<br/>";
}
else if(empty($productDescription)){
    echo "תיאור מוצר חסר<br/>";
}
else if(empty($productContent)){
    echo "תוכן מוצר חסר<br/>";
}
else if(empty($price)){
    echo "לא הזנת מחיר מוצר<br/>";
}
else if(empty($_POST['tag'])){
    echo "חסר קטגוריות מוצר<br/>";
}
else if(empty($_POST['color'])){
    echo "צבע המוצר חסר<br/>";
}
else if($_FILES['file']['size'] == 0 && $_FILES['file']['error'] == 0){
    echo "התמונה הראשית חסרה<br/>";
}
else if($_FILES['files']['size'] == 0 && $_FILES['files']['error'] == 0){
    echo "לא הוספת תמונות<br/>";
}
else{
    //Image main upload
    $filename = $_FILES["file"]["name"];
    $file_basename = substr($filename, 0, strripos($filename, '.')); // get file name
    $file_ext = substr($filename, strripos($filename, '.')); // get file extention
    $filesize = $_FILES["file"]["size"];
    $allowed_file_types = array('.png', '.jpg', '.jpeg', '.jfif');
    // Rename file
    $newfilename = getRandomWord() . $file_ext;
    if (in_array($file_ext, $allowed_file_types) && ($filesize < 200000)) {
        if (file_exists("upload/" . $newfilename)) {
            // file already exists error
            echo "You have already uploaded this file.";
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename);
            echo "File uploaded: " . $newfilename . "<br/>";
        }
    } elseif (empty($file_basename)) {
        // file selection error
        echo "Please select a file to upload.<br/>";
    } else {
        // file type error
        echo "Only these file typs are allowed for upload: " . implode(', ', $allowed_file_types);
        unlink($_FILES["file"]["tmp_name"]);
    }
    //Multiple image upload
    $countfiles = count($_FILES['files']['name']);
    $multipleDir = array();
    //Allowing to choose only 6 images
    if($countfiles > 7){
        echo "You can choose only 7 images to one product! <br/>";
    }
    else if($countfiles <= 0){
        echo "You didn't upload any photo! <br/>";
    }
    else{
        // Looping all files
        for($i=0;$i<$countfiles;$i++){
            $filesname = $_FILES['files']['name'][$i];
            $files_basename = substr($filesname, 0, strripos($filesname, '.'));
            $files_ext = substr($filesname, strripos($filesname, '.'));
            $allowed_files_types = array('.png','.jpg','.jpeg','.jfif');


            // Rename file
            $newfilesname = getRandomWord() . $files_ext;

            if (in_array($files_ext,$allowed_files_types))
            {
                if (file_exists("upload/" . $newfilesname))
                {
                    // file already exists error
                    echo "You have already uploaded: ".$newfilesname."<br/>";
                }
                else
                {
                    // Upload file
                    move_uploaded_file($_FILES['files']['tmp_name'][$i],'upload/'.$newfilesname);
                    echo "File uploaded: ". $newfilesname ."<br/>";
                    array_push($multipleDir, $newfilesname);
                }
            }
            else
            {
                // file type error
                echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_files_types);
                unlink($_FILES["files"]["tmp_name"]);
            }
        }
    }

At the momment this is the output:

Notice: Undefined index: proname in
D:XAMPPhtdocsugreencpanelupload.php on line 22

Notice: Undefined index: prodescription in
D:XAMPPhtdocsugreencpanelupload.php on line 23

Notice: Undefined index: content in
D:XAMPPhtdocsugreencpanelupload.php on line 24

Notice: Undefined index: price in
D:XAMPPhtdocsugreencpanelupload.php

  <form id="form" method ="POST" enctype="multipart/form-data" class="validate" novalidate>
    <div id="mc_embed_signup_scroll">
      <div class="mc-field-group">
        <input type="text" name="proname" id="proname" placeholder="שם המוצר" class="required">
      </div>
      <div class="mc-field-group">
        <input type="text" placeholder="תיאור המוצר" id="prodescription" name="prodescription" class="required">
      </div>
      <div class="mc-field-group">
        <textarea class="required" id="content" name="content" placeholder="תיאור נרחב על המוצר" style="height: 200px;"></textarea>
      </div>
      <div class="mc-field-group">
        <input type="text" id="price" name="price" placeholder="מחיר המוצר" class="required">
      </div>
      <div class="mc-field-group">
        תמונה ראשית:
        <br/>
        <input id="file" name="file" type="file"/>
      </div>
      <br/>
      <br/>
      <div class="mc-field-group">
        העלאת תמונות - עד 7 תמונות
        <br/>
        <input type="file" name="files[]" id="files" multiple>
      </div>
      <br/>
      <br/>
      <div class="mc-field-group" id="tag">
        שייך מוצר:<br/><br/>
            <input type="checkbox" name="tag[]" value="usb">USB
            <input type="checkbox" name="tag[]" value="charge">מטען
            <input type="checkbox" name="tag[]" value="adapter">מתאם
            <input type="checkbox" name="tag[]" value="pc">למחשב <br/>
            <input type="checkbox" name="tag[]" value="car">לרכב
            <input type="checkbox" name="tag[]" value="cables">כבלים
            <input type="checkbox" name="tag[]" value="apple">אפל
            <input type="checkbox" name="tag[]" value="other">אחר
      </div>
      <br/>
      <br/>
      <div class="mc-field-group"id="color">
        צבעים זמינים:
        <br/><br/>
        <input type="checkbox" name="color[]" value="שחור" /> שחור
        <input type="checkbox" name="color[]" value="לבן" /> לבן
        <input type="checkbox" name="color[]" value="אדום" />  אדום
        <input type="checkbox" name="color[]" value="ורוד" /> ורוד  <br/>
        <input type="checkbox" name="color[]" value="צהוב" /> צהוב
        <input type="checkbox" name="color[]" value="ירוק" /> ירוק
        <input type="checkbox" name="color[]" value="סגול" /> סגול
        <input type="checkbox" name="color[]" value="כחול" /> כחול  <br/>
        <input type="checkbox" name="color[]" value="זהב" /> זהב
        <input type="checkbox" name="color[]" value="אפור" /> אפור
        <input type="checkbox" name="color[]" value="כתום" /> כתום
        <br/>
      </div>
      <p class="error-message">מלא את תיבות הטקסט באדום</p>
      <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_d6c6ce7da87357b90e9859e81_2091bdd722" tabindex="-1" value=""></div>
      <div class="clear"><input type="submit" name="addproduct" value="הוסף מוצר" id="mc-embedded-subscribe" class="cta-btn"></div>
    </div>
  </form>

Note: If I remove Ajax data request and run the PHP code in the same page the code works.

2

Answers


  1. Here, I would use only one instance of the FormData class.

    var data = new FormData();
    data.append('proname', proname);
    data.append('prodescription', prodescription);
    data.append('content', content);
    data.append('price', price);
    data.append('tag', tag);
    data.append('color', color);
    data.append('file', $("#file")[0].files[0]);
    
    $.each($("#files")[0].files, function(i, file) {
        data.append('files[]', file);
    });
    

    Change/add in the ajax() call:

    data: data, // change
    contentType: false, // add
    
    Login or Signup to reply.
  2. I use this following code to upload my form data including images/files. Hope it helps.

    let yourForm = $('#yourForm');
    let actoin = // your action page;
    $.ajax({
            url: action,
            data:new FormData(yourForm[0]),
            async:false,
            type:'post',
            processData: false,
            contentType: false,
            success: function (data) {
               // your code here
            },
            error: function (data) {
                // your code here
            }
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search