Check for FormData
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'm trying to check if the fileds files are empty so that the user does not send 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 send without selecting a file, and ajax no longer reloads the page. Any suggestions what can I do?
Short answer, you cannot reliably verify that FormData contains information (how was your original question asked).
In Chrome and Firefox, you can use FormData.entries() to retrieve information, but they are not supported in older browsers and, of course, not in IE.
An alternative is to check the form elements directly - as you do - except that you skipped the file input. Also note that you must remove async: false as your incredibly bad practice in order to use it.
To fix your code, check the val() of file input in if :
$('#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!'); } });