0

Hey I am trying to submit a form to mysql db. The form is inside a modal though. The data is then sent to an ajax handler via ajax and a php function is ran. Everytime the word 'file' is written in the handler, i get an error. Here is my form, ajax and handler.

Form input:

<div class="form-group">
    <label>Image</label>
    <input type="file" class="addInput" name="image" id="newImage" placeholder="">
</div>

Javascript/Ajax

var name = $('#newName').val();
              var description = $('#newDescription').val();
              var notes = $('#newNotes').val();
              var status = ($('#newStatus').is(":checked") ? 'active' : '');
              var slug = $('#newSlug').val();
              var start_date = $('#newStartDate').val();
              var end_date = $('#newEndDate').val();
              var image = $('#newImage').val();

              let data = {
                action: 'NewEventExhibition',
                name: name,
                description: description,
                notes: notes,
                status: status,
                slug: slug,
                start_date: start_date,
                end_date: end_date,
                image: image,
                event_code: '<?=$code?>'
              };

              console.log(data);

              $.ajax({
                url: '/modules/ajax/ajax_handler.php',
                type: 'POST',
                data: data,
                success: function(response) {
                  console.log(response);
                },
                fail: function(response) {
                  console.log(response);
                }
              })

Handler

$added = $image = $filename = $imagefile = $imagefilesuccess1 = $imagefilewarning1 = NULL;


        if(!empty($_POST['image'])){
        $filename=($_SERVER['DOCUMENT_ROOT']."/assets/images/" . $_FILES["file"]["name"]);
        $imagefile=($_FILES["file"]["name"]);
            $path="/assets/images/".$imagefile."";
        $allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "PNG");
        $tmp = explode(".", $imagefile);
            $extension = end($tmp);
        if ((($_FILES["file"]["type"] == "image/gif")
        || ($_FILES["file"]["type"] == "image/jpeg")
        || ($_FILES["file"]["type"] == "image/jpg")
        || ($_FILES["file"]["type"] == "image/JPG")
        || ($_FILES["file"]["type"] == "image/pjpeg")
        || ($_FILES["file"]["type"] == "image/x-png")
        || ($_FILES["file"]["type"] == "image/png"))
        && ($_FILES["file"]["size"] < 7000000)
        && in_array($extension, $allowedExts))
        {
          if ($_FILES["file"]["error"] > 0){
          $imagefilewarning1 = "Return Code: " . $_FILES["file"]["error"] . "<br>";
          }
          else {
            $imagefilesuccess1 = "an image file was uploaded: <strong>" . $_FILES["file"]["name"] . "</strong>";
            if (file_exists("uploads/" . $_FILES["file"]["name"])){
                $imagefilewarning2 = $_FILES["file"]["name"] . " already exists. ";
            }
            else {
                move_uploaded_file($_FILES["file"]["tmp_name"],$filename);
                $imagefilesuccess4 = " and is stored in: <strong>" . $path . "</strong>";
            }
          }
        }
        else {
          $imagefilewarning3 = "no image file was uploaded";
        }

        $image = ($imagefile == '') ? $_POST['file'] : $imagefile;
      }

I included just the image code in the ajax handler. The $image variable at the bottom is the one i use to upload.

TiernO
  • 427
  • 6
  • 20

1 Answers1

0

to upload file via ajax you can use FormData. but first you need to see if your browser is supporting XHR2 , not every browser will support having file sending via ajax.

so if you wanna have your script work in every browser is better to the a work around, ( try to do a base64 in a hidden input, or work with ifram so the ifram will refresh alone )

browsers who support XHR2

so to add formData your can do a little change in your js script :

  var formData = new FormData($('#yourform')[0]);

or if you don't wanna create any form in yout html :

var formData = new FormData();
formData.append('name',$('#name').val());
formData.append('image',$('#image').get(0).files[0]);

. EDIT

you can also try this :

<input type="file" onchange="PrepareFile(this)" >

and init a global formData

async function PrepareFile(file) 
{         
    formData.append("file", file.files[0]);
}

.

... // inside   $.ajax({
    data: formData,
    dataType: 'json',
    mimeType: 'multipart/form-data', // this too
    contentType: false,
    cache: false,
    processData: false,
....

or you can use XMLHttpRequest , in this case you will drop ajax to work only with javascript , but is not working for IE<10.

MoxGeek
  • 458
  • 6
  • 17
  • Is it possible to send `formData` inside the `data` object with the rest of my data – TiernO Aug 18 '20 at 13:33
  • if you did the reverse will be more good i think, as i show in the second code, you can put your data inside the form data using append :) – MoxGeek Aug 18 '20 at 13:37
  • Yes I have tried that but if I `console.log` it after appending everything it logs an empty formData object :( – TiernO Aug 18 '20 at 13:39
  • send only the file at first, to see if the code work , it can be something else who is blocking what you try to do. if it work, you can do a work around, like sending your above ajax request after uploading the file with my proposition . but generally it will work without doing this – MoxGeek Aug 18 '20 at 13:41
  • I am just console logging `formData` before it even gets to the Ajax. I have `formData.append('image',$('#newImage').get(0).files[0]);` – TiernO Aug 18 '20 at 13:43
  • see the edit please – MoxGeek Aug 18 '20 at 13:51