Skip to content

Instantly share code, notes, and snippets.

@siumhossain
Last active June 9, 2021 16:04
Show Gist options
  • Select an option

  • Save siumhossain/022caaba91d7e2367d9a6f99199f4c06 to your computer and use it in GitHub Desktop.

Select an option

Save siumhossain/022caaba91d7e2367d9a6f99199f4c06 to your computer and use it in GitHub Desktop.
ajax_from_submission
{% load static %}
<html>
<body>
<b> <a href="{% url 'lead:lead' %}">previous page</a> </b>
<hr>
<b>
Create a lead
</b>
<form method="post" id="p-form">
{% csrf_token %}
{{form.as_p }}
<button id='submit' type="submit">Submit</button>
</form>
</body>
<script src="{% static 'form.js' %}" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</html>
console.log('from form')
document.getElementById('submit').onclick = function() {
console.log('submit submit');
}
const form = document.getElementById('p-form');
const resultBox = document.getElementById('resultBox');
const first_name = document.getElementById('id_first_name');
const last_name = document.getElementById('id_last_name');
const age = document.getElementById('id_age');
const agent = document.getElementById('id_agent');
const csrf = document.getElementsByName('csrfmiddlewaretoken');
const url = "";
//console.log(csrf)
//console.log(form)
form.addEventListener('submit',e=>{
e.preventDefault() //this will prevent from page load
const fb = new FormData();
fb.append('csrfmiddlewaretoken',csrf[0].value)
fb.append('first_name',first_name.value)
fb.append('last_name',last_name.value)
fb.append('age',age.value)
fb.append('agent',agent.value)
$.ajax({
type:'POST',
url:url,
enctype: 'multipart/form-data',
data:fb,
success: function(response){
resultBox.innerHTML = `
<b>Success</b>
`
setTimeout(()=>{
first_name.value = ''
last_name.value = ''
age.value = ''
agent.value = ''
},200)
},
error: function(error){
console.log(error)
},
cache:false,
contentType:false,
processData:false,
})
})
def lead_create(request):
form = LeadForm()
data =[]
if request.is_ajax():
form = LeadForm(request.POST)
if form.is_valid():
form.save()
context = {
'form':form
}
return render(request,'lead_create.html',context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment