Sunil
Sunil

Reputation: 237

File Upload not Working when form send data to another php file through jquery

Below code works well when I am executing PHP in same page but it does not work when I execute script_add_business.php using jquery. Particularly HTML html file upload does not send any value but when I tried getting other fields values like textbox, I am successfully getting them.

MY HTML:

<form method="post" enctype="multipart/form-data" id="addBusinessForm" class="form-horizontal addBusinessForm" action="">
<input type="file" name="logo" class="form-control">
<button type="submit" id="addBusiness" class="btn btn-custom">Upload Logo</button>
</form>

JQUERY within HTML page:

<script type="text/javascript">
    //Add Invoice Form
    $('#addBusiness').click(function() {
      $.post("script_add_business.php", $(".addBusinessForm").serialize(), function(response) {
        $('#success').html(response);
        $('#success').show();
        if (response == 'OK') {
            $('#addBusinessForm')[0].reset();
            $('#success').text('Your Business has been successfully submitted. People can see it live once we approve it.');
        }
      });
      return false;
    });
    </script>

script_add_business.php CODE:

if(!empty($_FILES['logo']['name']))
        {
            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["logo"]["name"]);
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            $imgname = basename($_FILES["logo"]["name"]);
            $target_file = $target_dir .$imgname;
            echo "File path is:". $target_file; exit;
}

I really appreciate help.

Upvotes: 0

Views: 56

Answers (2)

Punit Gajjar
Punit Gajjar

Reputation: 4987

You can't upload file with jQuery $.post method.

Try like this .

<form method="post" enctype="multipart/form-data" id="addBusinessForm" class="form-horizontal addBusinessForm" action="">
        <input type="file" name="logo" class="form-control">
        <button type="submit" id="addBusiness" class="btn btn-custom">Upload Logo</button>
    </form>


$('#addBusiness').click(function() {

            var formData=new FormData();

            formData.append("image",$('[name="logo"]')[0].files[0]);

            $.ajax({
                url: 'script_add_business.php',
                data:formData,
                type: 'POST',
                dataType:"JSON",
                cache: false,
                contentType: false,
                processData: false,
                success:function(response){ 
                    // Do stuffffff
                }
            });
            return false;
        });

Upvotes: 0

Related Questions