alin dradici alin dradici - 1 month ago 18
Ajax Question

Check if FormData is empty

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?

Answer

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 retieve 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, and use a logical or statement 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!');
    }
});
Comments