0

I am trying to upload images in a folder named "patents". It works, but I am trying to post its name using AJax in order to get json_encode messages from "checkout.php" in case filename exists or its invalid. Here is my code:

$('#checkout_form').on('submit', function(e) {
        e.preventDefault();
        var filename = $('#checkout_form input[name=file]').val();
        $.ajax({
            url: "checkout.php",
            type: "POST",
            enctype: 'multipart/form-data',
            data: {
                file: filename,
            },
            dataType: 'json',
            success: function(response) {
                    alert('pau');
                }
        });
    });

checkout.php

 $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 80000) && in_array($extension, $allowedExts)) {
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        } else {
            if (file_exists("patents/" . $_FILES["file"]["name"])) {
                echo json_encode($_FILES["file"]["name"] . " already exists. ");
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "patents/" . $_FILES["file"]["name"]);
            }
        }
    } else {
     echo json_encode('invalid file');
    }

When click submit button nothing happens, it's not shown no error message and the form is not submitted.

Ana Vani
  • 51
  • 1
  • 6
  • is the form not submitting? or is your PHP page coming back with an `error 500`? – 13ruce1337 Mar 22 '14 at 15:16
  • form is not submitting and is not shown any error, nor in console – Ana Vani Mar 22 '14 at 15:19
  • You can't do it the way you want. Upload fields need special care, I suggest you use an upload library such as Plupload or Uploadify. Take a look at the answer here: http://stackoverflow.com/questions/6211145/upload-file-with-ajax-xmlhttprequest – va5ja Mar 22 '14 at 15:20
  • 1
    You have two issues 1. You have logic to upload a file in your php script when you're just sending the name of the file. 2. Your php script only has output on failure but your ajax call expects a json response every time and has no error handling – Musa Mar 22 '14 at 15:29
  • @Musa what do you suggest me? – Ana Vani Mar 22 '14 at 15:41

0 Answers0