Saturday, June 12, 2021

Re: Allow field validation in ajax.

You are not submitting your form which Inturn is not validating. For validations to run you need to submit a form.

Give the submit button attribute type="submit", then add an event listener for form submit in your javascript.
$("#ReportForm").on('submit', function(event) {
       // here event is submit type event object
       event.preventDefault() // this is added to prevent default execution of form submit event which will stop the page reload. 
       // here event.target is your form so you can use that to get data as let data = new FormData(event.target) 
})

On Saturday, 12 June 2021 at 22:09:26 UTC+5:30 eugenet...@gmail.com wrote:
Friends,

The ajax codes below successfully save the records in the database without page loading. But what I want is to validate the fields first before saving. The codes do not validate the empty field. How can I include that validation ? please help

<script>
$(".submit_btn").click(function(){
var form=new FormData($("#ReportForm")[0]);
//AJAX CODE
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.status==200){
console.log(xhr.responseText);
}
}
xhr.open("POST","{% url 'report_create' %}",true);
$("#progressbar").show();

//UPDATING PROGRESS BAR
xhr.upload.addEventListener("progress",function(ev){
if(ev.lengthComputable){
var percentage=(ev.loaded/ev.total*100|0);
$("#progressbar").css({"width":""+percentage+"%"}).text("Uploading .."+percentage+"%");
console.log(percentage);
if(percentage>=100){
location.reload()

}
}
});

xhr.send(form);
})
</script>

Regards,
Eugene


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d4c70f2f-2b3f-4d64-a94a-ee31b9ecdd03n%40googlegroups.com.

No comments:

Post a Comment