0

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.

Sunil
  • 237
  • 2
  • 4
  • 13

2 Answers2

1

Please refer this url's, these may help you

https://stackoverflow.com/a/8758614/1072492

http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/

Community
  • 1
  • 1
Mani7TAM
  • 469
  • 3
  • 10
0

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;
        });
Punit Gajjar
  • 4,937
  • 7
  • 35
  • 70