0

I am following this tutorial on how to upload an image with file using ajax and php.. https://www.codexworld.com/ajax-file-upload-with-form-data-jquery-php-mysql/

Everything works fine but for some reasons I get the custom error message "Some problem occurred, please try again."

Even when the file gets uploaded and also the data.

html

<p class="statusMsg"></p>
<form enctype="multipart/form-data" id="fupForm" >
<div class="form-group">
    <label for="name">NAME</label>
    <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />
</div>
<div class="form-group">
  <label for="email">EMAIL</label>
    <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required />
</div>
<div class="form-group">
    <label for="file">File</label>
    <input type="file" class="form-control" id="file" name="file" required />
</div>
<input type="submit" name="submit" class="btn btn-danger submitBtn" value="SAVE"/>

Ajax

<script>
$(document).ready(function(e){
    $("#fupForm").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'submit.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $('.submitBtn').attr("disabled","disabled");
                $('#fupForm').css("opacity",".5");
            },
            success: function(msg){
                $('.statusMsg').html('');
                if(msg == 'ok'){
                    $('#fupForm')[0].reset();
                    $('.statusMsg').html('<span style="font-size:18px;color:#34A853">Form data submitted successfully.</span>');
                }else{
                    $('.statusMsg').html('<span style="font-size:18px;color:#EA4335">Some problem occurred, please try again.</span>');
                }
                $('#fupForm').css("opacity","");
                $(".submitBtn").removeAttr("disabled");
            }
        });
    });

    //file type validation
    $("#file").change(function() {
        var file = this.files[0];
        var imagefile = file.type;
        var match= ["image/jpeg","image/png","image/jpg"];
        if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
            alert('Please select a valid image file (JPEG/JPG/PNG).');
            $("#file").val('');
            return false;
        }
    });
});
</script>

submit.php

<?php
if(!empty($_POST['name']) || !empty($_POST['email']) || !empty($_FILES['file']['name'])){
    $uploadedFile = '';
    if(!empty($_FILES["file"]["type"])){
        $fileName = time().'_'.$_FILES['file']['name'];
        $valid_extensions = array("jpeg", "jpg", "png");
        $temporary = explode(".", $_FILES["file"]["name"]);
        $file_extension = end($temporary);
        if((($_FILES["hard_file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
            $sourcePath = $_FILES['file']['tmp_name'];
            $targetPath = "uploads/".$fileName;
            if(move_uploaded_file($sourcePath,$targetPath)){
                $uploadedFile = $fileName;
            }
        }
    }

    $name = $_POST['name'];
    $email = $_POST['email'];

    //include database configuration file
    include_once 'dbConfig.php';

    //insert form data in the database
    $insert = $db->query("INSERT form_data (name,email,file_name) VALUES 
    ('".$name."','".$email."','".$uploadedFile."')");

    echo $insert?'ok':'err';
}
4
  • 1
    Warning: You are wide open to SQL Injections and should really use parameterized Prepared Statements instead of manually building your queries like that. Specially since you're not escaping the user inputs at all! Commented Nov 28, 2018 at 12:00
  • 2
    Do a console.log(msg) and check what it actually contains. Commented Nov 28, 2018 at 12:00
  • You can check the server response from your browser network section. Commented Nov 28, 2018 at 12:18
  • could you please show me table structure of form_data. because as per my assumption this must due to database error. Commented Nov 28, 2018 at 12:25

1 Answer 1

1

The Error was in you PHP where you trying to check your file type you given $_FILES['hard_file']['type'] where it should be $_FILES['file']['type']

  if(!empty($_POST['name']) || !empty($_POST['email']) || !empty($_FILES['file']['name'])){
$uploadedFile = '';
if(!empty($_FILES["file"]["type"])){
    $fileName = time().'_'.$_FILES['file']['name'];
    $valid_extensions = array("jpeg", "jpg", "png");
    $temporary = explode(".", $_FILES["file"]["name"]);
    $file_extension = end($temporary);
    if((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
        $sourcePath = $_FILES['file']['tmp_name'];
        $targetPath = "./".$fileName;
        if(move_uploaded_file($sourcePath,$targetPath)){
            $uploadedFile = $fileName;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.