Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if FormData is empty

Tags:

jquery

ajax

So I have a form like this:

<form id="uploadimage" action="" method="post" enctype="multipart/form-data">                   
    <div class="text-inside">
        Selectati Categoria<br><select id="sc" name="selectCat"></select><br><br>
        Nume Produs<br><input id="numprod" type="text" name="input-text" /><br>
        Pret Produs<br><input id="pretprod" type="number" name="input-pret" /><br><br>
        <input type="file" name="file"><br><br>
        <input type="submit" name="sumit" value="Send" id="imgButton" class="button"  /><br><br>
    </div>              
</form>

And I am trying to check is the filelds are empty in order to prevent the user from submiting empty fields so I used this:

$('#uploadimage').on('submit',(function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    var name= $('#numprod').val();
    var pret = $('#pretprod').val();

    if(name && pret){
        $.ajax({
            url: 'connect.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function(){
                alert('uploaded successuflly!');
            }
        });
    }else{alert('input fields cannot be left empty you num num!');}
}));

But I can still submit with no file selected and ajax is not reloading the page anymore. Any suggestions what can I do?

like image 770
alin dradici Avatar asked Nov 01 '16 16:11

alin dradici


People also ask

How do I check if a FormData is empty?

val(); if(name && pret){ $. ajax({ url: 'connect. php', type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function(){ alert('uploaded successuflly! '); } }); }else{alert('input fields cannot be left empty you num num!

How do I view data in FormData?

I think it's also useful to note that you can grab an existing form's data using: var formData = new FormData(formElement) . If you are using JQuery, you can therefore do this: var formData = new FormData($('#formElementID')[0]) . Then append data as needed. Still, this has to be one of the worst browser APIs.

Why FormData is empty in JQuery?

The best way to begin is to make sure that file uploads is allowed and then testing with very small files to be sure everything in your code is OK. instead of var formData = new FormData($('#generate_params')[0]); you can write var formData = new FormData(this); instead.

What is FormData ()?

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the fetch() or XMLHttpRequest. send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data" .


3 Answers

Short answer, you can't reliably check that FormData contains information (as your original question asked).

In Chrome and Firefox you can use FormData.entries() to retrieve information, but these are not supported in older browsers and certainly not in IE.

The alternative is to validate the form elements directly - as you are doing - except that you missed out the file input. Also note that you should remove async: false as its incredibly bad practice to use it.

To fix your code, check the val() of the file input in the if condition:

$('#uploadimage').on('submit', function(e) {
    e.preventDefault();
    var name = $('#numprod').val().trim();
    var pret = $('#pretprod').val().trim();
    var file = $('input[type="file"]').val().trim(); // consider giving this an id too

    if (name && pret && file) {
        $.ajax({
            url: 'connect.php',
            type: 'POST',
            data: new FormData(this),
            cache: false,
            contentType: false,
            processData: false,
            success: function(){
                alert('uploaded successuflly!');
            }
        });
    } else {
        alert('input fields cannot be left empty you num num!');
    }
});
like image 180
Rory McCrossan Avatar answered Oct 12 '22 15:10

Rory McCrossan


As this is the top Google result, for anyone searching for a quick solution to checking whether a FormData object is empty, FormData.entries() will return an iterator. If you use the .next() method on that iterator, you will get an object with the properties done and value. Thus you can check for that done property to determine if the iterator has no entries. This worked for my needs:

formDataObject.entries().next().done

And a sandbox proof of concept: https://codesandbox.io/s/16v99w3o4 (check the console)

like image 33
Kyle Crossman Avatar answered Oct 12 '22 15:10

Kyle Crossman


Add an Id to the input of type file and check if it has files with the below snippet:

if(document.getElementById("file").files.length == 0 ){
    console.log("no files selected");
}
like image 21
Ricky Stam Avatar answered Oct 12 '22 14:10

Ricky Stam