Home > Enterprise >  Form Sending file but not form element via Ajax
Form Sending file but not form element via Ajax

Time:09-11

I am trying to send a file and some information to a php page to upload to the server and store in the database. The form uploads the file to a documents folder and then stores the details in the database perfectly. However the other elements of the form, are not being sent.

Below is my code.

     $(document).ready(function(){
        $("#but_upload").click(function(){
            var fdata = new FormData()
            fdata.append("lead_id", $("lead_id").val());
            var files = $('#file')[0].files;
            // Check file selected or not
            if(files.length > 0 ){
                fdata.append('file',files[0]);
                $.ajax({
                    url:'upload3.php',
                    type:'post',
                    data:fdata,
                    contentType: false,
                    processData: false,
                    success:function(response){
                        if(response != 0){
                            $("#show_message_document").fadeIn();
                        }else{
                            alert('File not uploaded');
                        }
                    }
                });
            }else{
                alert("Please select a file.");
            }
        });
    });

My form

  <form method="post" action="" enctype="multipart/form-data" id="myform">
    <input type="file" id="file" name="file" />
    <input type="hidden" id="lead_id" name="lead_id" value="<?php echo $lead_id; ?>"> 
    <input type="button"  value="Upload" id="but_upload">
  </form>

My Php

   $lead_id = ($_POST['lead_id']);

CodePudding user response:

You're trying to get "lead_id" without any selector, either use "#lead_id" or "[name=lead_id]".

Working code:

<script type="text/javascript">
    $(document).ready(function(){
        $("#but_upload").click(function(){
            var fdata = new FormData();
            fdata.append("lead_id", $("#lead_id").val());
            var files = $('#file')[0].files;
            // Check file selected or not
            if(files.length > 0 ){
                fdata.append('file',files[0]);
                $.ajax({
                    url:'upload.php',
                    type:'post',
                    data:fdata,
                    contentType: false,
                    processData: false,
                    success:function(response){
                        if(response != 0){
                            $("#show_message_document").fadeIn();
                        }else{
                            alert('File not uploaded');
                        }
                    }
                });
            }else{
                alert("Please select a file.");
            }
        });
    });
</script>

Hope this helps!!

  • Related