George
George

Reputation: 1114

Submit form containing text input and file input

I am submitting a form which contains a text input and file input to a php page using Jquery and Ajax, but before the submission, I would want to validate on the text input before I submit.

Below is the form page

            <form id="registrationForm"  method="POST"  name="registrationForm" enctype="multipart/form-data">

                <input type="text"  name="firstName" id="firstName" />

                <input type="file" name="file" id="file" />

                <button type="submit"> UPLOAD</button>

            </form>

and the Javascript page

 $('#registrationForm').validate({
        rules: {
            firstName:{
                required: true
            }
        },
        message:{
            firstName: {
                required: "Please Enter Name"
            }
        },


    submitHandler : function(){

      //grab all form data  
      var formData = new FormData(this);

      $.ajax({
        url: 'submitPage.php',
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
          success: function(data) {  
            $('#message').html(data);  
            $('#message').html(data).hide().fadeIn(1500,function(){$('#message')});
            } 
        });

    }
    });

And PHP Page which is the receiving page

        <?php
            $firstName=$_POST['firstName'];
            $file=$_FILES['file']['name'];

            echo $firstName;
            echo $file;

         ?>

This returns null on the php receiving page. I really wish if somebody could help me out. Thanks.

Upvotes: 1

Views: 89

Answers (1)

user1361491
user1361491

Reputation:

$('#registrationForm').validate({
        rules: {
            firstName:{
                required: true
            }
        },
        message:{
            firstName: {
                required: "Please Enter Name"
            }
        },


    submitHandler : function(){

      //grab all form data  
      var formData = new FormData(document.querySelector("form"));

      $.ajax({
        url: 'submitPage.php',
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
          success: function(data) {  
            $('#message').html(data);  
            $('#message').html(data).hide().fadeIn(1500,function(){$('#message')});
            } 
        });

    }
    });

Upvotes: 1

Related Questions