I am very new to ajax. Here I have a django form and inside the form there is a form group of checkbox.
What I want here is, from the checkbox if the user check some user object I want to get it in the django view immediately before the form submit. And if the the user uncheck this It should be removed from django view also. How can I do this ?
After form submit it works fine but I want to get the checked user before the form submits.So I think in this case ajax will be required. But I am very beginner in ajax so I got stuck here.
template
<div class="form-group">
<div class="checkbox">
<input class="checkbox1" name="users" type="checkbox" value="{{user.pk}}"
id="user{{user.pk}}"/>
<label for="user{{user.pk}}"></label>
</div>
</div>
jquery
<script>
$(function(){
var checked_lists = [];
$(".checkbox1:checked").each(function() {
checked_list.push(this.value);
});
$.ajax({
url: "{% url 'my_url' %}",
data:{
checked_Lists: checked_list,
}
}
});
});
</script>
views
print(self.request.POST.getlist('checked_lists'))
In you case you need to pass checked_list[] javascript list to view so need ajax
for that
and handle ajax request base on checkbox change event
<script>
$('.checkbox1').change(function(){ // checkbox1 change event
var checked_lists = [];
$(".checkbox1:checked").each(function() {
checked_list.push(this.value);
});
var formdata = new FormData();
$.ajax({
formdata.append('checked_list',checked_list)
formdata.append('csrfmiddlewaretoken',$('input[type=hidden]').val());
$.ajax({
url:"/profile_upload", //replace with you url
method:'POST',
data:formdata,
enctype: 'application/x-www-form-urlencoded',
processData:false,
contentType:false,
success:function(data){
alert("Display return data"+data)
},
error:function(error){
alert(error.error)
}
});
});
});
</script>
views.py :You define view base on your logic
def <view-name>(request):
if request.method=='POST':
user_list = request.getlist('checked_list')
return JsonResponse(status=200,data={'data':'success'})
else:
return JsonResponse(status=203,data={'error':'unauthorize request.!!'})
If you use post request to define csrf_token so pass them if your script
code in single page formdata.append('csrfmiddlewaretoken',{% csrf_token %});through those link and do
Ajax Request For Sumbit Data
if you get error on it, let me know
Related
I have a problem with django. I have researched so much on other questions but their answers don´t work for me. I need to send a base64 string of an image to my view so that i can store the string instead of the image in my database. So, I want to send data via ajax to my django view. Due to whatever reason, the form gets already submitted by django automatically and i tried to stop it, but then ajax isn´t firing too. I would really appreciate help because it already has cost me so much time.
add.html
<form method="post" enctype="multipart/form-data" onsubmit="submitdata()">
{% csrf_token %}
<input type="text" name="dish" required id="id_dish" placeholder="Rezeptname">
<img ><input type="file" name="image" required id="id_image" accept="image/*">
<div class="image-upload"><img id="img_id" src="#">
</div><button type="submit">Upload</button>
</form>
<script>
function submitdata() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "/add",
data: JSON.stringify({
csrfmiddlewaretoken: document.getElementsByName("csrftoken")[0].value,
"dish": "test",
"image": dataurl,
"recipe": document.getElementsByName("recipe")[0].value,
"caption": document.getElementsByName("caption")[0].value
}),
dataType: "json",
});
}
</script>
views.py
#login_required(login_url="login")
def add(response):
if response.method == "POST":
form = AddForm(response.POST, response.FILES)
if form.is_valid():
print(response.POST)
# The print statement prints the data from the automatical form
submit, not from the ajax submit
current_user = Client.objects.get(id=response.user.id)
current_user.post_set.create(poster=response.user.username,
dish=form.cleaned_data.get("dish"),
image=response.POST.get("image"),
caption=form.cleaned_data.get("caption"),
recipe=form.cleaned_data.get("recipe"))
messages.success(response, "You successfully added a post.")
return redirect("home")
else:
form = AddForm()
return render(response, "main/add.html", {"form":form})
urls.py
urlpatterns = [
path("add", views.add, name="add")
]
forms.py
class AddForm(forms.ModelForm):
dish = forms.CharField()
image = forms.FileField()
caption = forms.TextInput()
recipe = forms.TextInput()
class Meta:
model = Post
fields = ["dish", "image", "recipe", "caption"]
When you use the onsubmit property and want to prevent the form from sending data, make sure the handler returns false.
If the onsubmit handler returns false, the elements of the form are not submitted. If the handler returns any other value or returns nothing, the form is submitted normally.
<script>
function submitdata() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "/add",
data: JSON.stringify({
"dish": "test",
"image": dataurl,
"recipe": document.getElementsByName("recipe")[0].value,
"caption": document.getElementsByName("caption")[0].value
}),
dataType: "json",
//return false if ajax is successful
// you can also do something with response data if needed
success: function(data) {return false;},
//return false if ajax request returns error
error: function(data) {return false;},
});
}
</script>
i wrote a program using django to retrieve all checked checkbox without submit button by using AJAX , it is not throwing any error , but it displays "NO Value " . Can anyone check and tell me what is the mistake i did .
AJAX :
<script>
$('.form-check-input').change(function(){ // checkbox1 change event
var checked_lists = [];
$(".form-check-input:checked").each(function() {
checked_list.push(this.value);
});
var formdata = new FormData();
$.ajax({
formdata.append('checked_list',checked_list)
formdata.append('csrfmiddlewaretoken',$('input[type=hidden]').val());
$.ajax({
url:"secondtableonDashboard", //replace with you url
method:'POST',
data:formdata,
enctype: 'application/x-www-form-urlencoded',
processData:false,
contentType:false,
success:function(data){
alert("Display return data"+data)
},
error:function(error){
alert(error.error)
}
});
});
});
</script>
Views.py
def secondtableonDashboard(request):
conn = pyodbc.connect('Driver={SQL Server};'
'Server=ABC\SQLEXPRESS;'
'Database=WebstartUI;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute("select * from CustomerServer")
result = cursor.fetchall()
if request.method=='POST':
user_list = request.getlist('checked_list')
print(user_list)
else:
print("No Values")
html :
<td>
<div class="form-check form-switch">
<input class="form-check-input" name="Servers[]" value="{{datas.ServerName}}" type="checkbox" id="flexSwitchCheckDefault">
<label class="form-check-label" for="flexSwitchCheckDefault">
</div>
</td>
So here i use my views.py, same function to keep data in checkbox and to get POST values.
UI:
I am trying to fetch data from postgres table by clicking a button in the django template page and the fetched data from db should be populated into another div.
For the same, I am using Ajax get call to fetch the data from DB, but I am facing problem that the value is shown as undefined.
With the Ajax call if I populate the target div with the below, it is working.
$('#childContainer').html(10 + Math.floor(Math.random()*91));
But when I try to fetch the data from table, I am getting undefined.
Here is the code which I have written:-
views.py:-
def index(request):
distinctenvapp = Env_app.objects.values('environment_name').distinct()
return render(request, 'envconfigmgmt/index.html', {'distinctenvapp' : distinctenvapp});
def get(self,request, *args, **kwargs):
if self.request.is_ajax():
return self.ajax(request)
def ajax(self, request):
response_dict= {
'success': True,
}
action = request.GET.get('action','')
if action == 'get_appnames':
env_id = request.GET.get('id','')
if hasattr(self, action):
response_dict = getattr(self, action)(request)
envappname = Env_app.objects.get(environment_name='env_id')
response_dict = {
'application_name':envappname.application_name
}
return HttpResponse(simplejson.dumps(response_dict),
mimetype='application/json')
index.html:-
<div><center><table id="t1"><tr>
{% for obj in distinctenvapp %}
<td>
<button id="{{ obj.environment_name }}">
{{ obj.environment_name }}
</button>
</td>
{% endfor %}
</tr></table></center></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$env_id = $(this).attr('id')
$.ajax({
type: "GET",
data: { action: "get_appnames", id: $env_id },
success: function(data){
$("#childContainer").html("<strong>"+data.application_name+"</strong>");
console.log(data);
}
});
//$('#childContainer').html(10 + Math.floor(Math.random()*91));
});
});
</script>
<div id="childContainer"></div>
I expect the data to be fetched in the target child div.
It should show application names like App1, App2 etc, but it is showing undefined.
IF your ajax request returning JSON content then you have to define datatype in Ajax parameter
$.ajax({
type: "GET",
data: { action: "get_appnames", id: $env_id },
dataType: 'json',
success: function(data){
$("#childContainer").html("<strong>"+data.application_name+"</strong>");
console.log(data);
}
});
For more refere this https://api.jquery.com/jquery.ajax/
I think your ajax request doesnt have url so ajax called current page again
current page is a string and doesnt have application_name
be aware that the mimetype argument was removed in Django 1.7. Use content_type instead.
I am using django 1.5, python 2.7 and jquery 1.9. I have a form which has precisely 2 fields i.e. title and document. When I press submit I want the users chosen document to be present in the request.FILES as shown in the view.
When I submit the regular form (without ajax), this works fine, but with ajax I do not get the file field in my request. Any suggestions on how to upload a file using ajax.
HTML:
<form enctype="multipart/form-data" action="{% url 'upload_document' %}" method="post" id="uploadForm">
{% csrf_token %}
<ul>
<li>
<div>Title</div>
<input id="title" type="text" maxlength="200"/>
<div class="error"></div>
</li>
<li>
<div>Upload File</div>
<input id="document" type="file" size="15" />
<div class="error"></div>
</li>
</ul>
<input type="submit" value="submit"/></p>
</form>
FORMS.PY:
class UploadForm( forms.Form ):
document = forms.FileField()
title = forms.CharField(max_length = 200)
def clean(self):
cleaned_data = super(UploadForm, self).clean()
return cleaned_data
def save(self, *args, **kwargs):
title = self.cleaned_data['title']
doc = self.cleaned_data['document']
document = Document(title = title, document = doc)
document.save()
return document
SCRIPT:
<script type="text/javascript">
$("#uploadForm").submit(function(event){
event.preventDefault();
$.ajax({
url : "{% url 'upload_document' %}",
type: "POST",
data : {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
title: document.getElementById('title').value,
//document: document: document.getElementById('document'),
},
dataType : "json",
success: function( response ){
if(response == "True"){
// success
}
else {
//append errors
}
}
});
});
</script>
VIEWs.PY
def upload_document(request):
print request.POST
print request.FILES
if request.is_ajax():
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES, user = request.user)
if form.is_valid():
form.save()
return HttpResponse(simplejson.dumps('True'), mimetype = 'application/json' )
else:
errors = form.errors
return HttpResponse(simplejson.dumps(errors), mimetype = 'application/json' )
The answer to that question is not that simple. First of all if you intend to support old browsers then indeed it gets nasty. You have to deal with hidden iframes and some JavaScript tricks. I do advice using some well-known scripts for that like jQuery-File-Upload.
But the world is evolving and new technologies arise including HTML5. There's a new File API which is available in most modern browsers ( IE10+, FireFox3.6+, Chrome13+, see: http://caniuse.com/fileapi ) which can be used for that. First you need some HTML:
<input type="file" id="file-select" />
Then you can bind to (for example) change event:
$('#file-select').change( handleFileSelect );
and finally the handler itself:
var data = {};
function createReaderHandler(name) {
return function(ev) {
data[name] = ev.target.result;
};
}
function handleFileSelect(ev) {
var files = ev.target.files; // FileList object
// Loop through the FileList
for (var i = 0; i < files.length; i++) {
var file = files[i],
name = file.name || file.fileName,
reader = new FileReader();
reader.onload = createReaderHandler(name);
reader.readAsText(file);
}
}
Once the data is loaded into JavaScript memory (note that the operation is asynchronous) you can send it via AJAX like any other data. There are more options: depending on your file you can read it as a binary data using .readAsBinaryString and so on. Google is your friend. :)
Also I think there already are good scripts for uploading files with a fallback to old methods. This one can be interesting (haven't tried it):
http://www.plupload.com/
I think the issue is in the submit button, change it into normal button
ie, <button type='button' id='submit'>submit</button>(by default all buttons in form are submit)
and the ajax as
$('#submit').on('click',function(){
frm = $(this).parents('form')
$.ajax({
type: frm.attr('method'),
dataType:'json',
url: frm.attr('action'),
data: frm.serialize(),
async: false,
success: function (data) {
console.log('success')
},
error: function(data) {
console.log("Something went wrong!");
}
})
All others will be same
Just try it will work
my use case is:
a) Present a form loaded via ajax in a bootstrap modal, the fancy overlay effect stuff.. . I followed these instructions.
This works fine. (see code below)
b) Submit this form back to my Django app, try to validate it, and if it does not validate, re-show the form with the errors in the fancy bootstrap modal.
I can reload the form via ajax, but I m not able to represent it again in the modal.
Note: I did not include the view since it does nothing special. Only instantiating and validating the form.
Quite a lot to read below, so just continue if you think the use case sounds interesting...
My taskList.html looks like this:
<table id="listItemTable" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Task 1</td>
<td><a class="editItem" href="/update/item/1/">edit</a></td>
</tr>
</tbody>
</table>
<div class="modal hide" id="itemFormModal"></div>
<div id="modalExtraJsPlaceholder"></div>
.js for loading the form + showing the bootstrap modal + binding form to a .jquery submit call:
$(document).ready(function() {
modalConnect();
});
<script type="text/javascript">
//connects the modal load for each <a> with class editItem
//Functionality 1
//loads an item edit form from the server and replaces the itemFormModal with the form
//presents the modal with $("#itemFormModal").modal('show');
//Functionality 2
//loads some extra js "modalExtraJsHtml"
//calls the function "submitItemModalFormBind" which has been loaded via "modalExtraJsHtml"
function modalConnect(){
$(".editItem").click(function(ev) { // for each edit item <a>
ev.preventDefault(); // prevent navigation
url = ($(this)[0].href); //get the href from <a>
$.get(url, function(results){
var itemForm = $("#ajax_form_modal_result", results);
var modalExtraJs = $("#modalExtraJs", results);
//get the html content
var modalExtraJsHtml = modalExtraJs.html();
//update the dom with the received results
$('#itemFormModal').html(itemForm);
$('#modalExtraJsPlaceholder').html(modalExtraJsHtml);
$("#itemFormModal").modal('show');
submitItemModalFormBind(); //bind loaded form to ajax call
}, "html");
return false; // prevent the click propagation
})
}
</script>
The itemForm returned from the view looks like this:
<form id="#ajax_form_modal_result" class="well" method="post" action="/update/item/{{ item.id }}">
<div id="ajax_form_modal_result_div">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Edit Item</h3>
</div>
<div class="modal-body">
{% csrf_token %}
{{form.as_p}}
</div>
<div class="modal-footer">
<input class="btn btn-primary" type="submit" value="Save" />
<input name="cancel" class="btn" type="submit" value="Cancel"/>
</div>
</div>
</form>
Loading and showing the modal works fine.
But now comes the second part which does not work as expected. The issue is the following. If the form does not validates, the view returns the form. The returned form should be shown again in the bootstrap modal. But the result is that ONLY the form is presented in the browser, everything else is lost. No css, no table, only the form. Quite ugly.. Thus I did not achieve to update the ajax_form_modal_result_div. Can anyone help me out here what I m doing wrong..!?
The view returns also the js function 'submitItemModalFormBind' which prevents the form default behavior and sends the form via ajax.
<div id="modalExtraJs">
//ajax bind for update item form visualized via modal
function submitItemModalFormBind(){
var url = "{% url updateItem item.pk %}";
$('#ajax_form_modal_result').submit(function(){
$.ajax({
type: "POST",
url: "{% url updateTask item.pk %}",
data: $(this).serialize(),
success:function(response){
var div = $("ajax_form_modal_result_div", response);
$('#ajax_form_modal_result_div').html(div);
},
error: function (request, status, error) {
console.log("failure");
console.log(request.responseText);
}
});
});
return false;
}
</div>
Found a working approach (based upon this solution - and enhanced it with handling of invalid forms) and will post it for anybody who also want to use the stunning beautiful bootstrap modals with django. Major issue with the code above was that I did not correctly disabled the default behavior of the submit button and the approach for loading additional js was not a good idea. So I changed my strategy.
On documentReady or ajaxStop event bind the click event of the hyperlinks to the modalConnect function. Note that you only need the ajaxStop function if you have some kind of ajax which updates the content of your table (which I have):
<script type="text/javascript">
$(document).ready(function() {
modalConnect();
});
</script>
<script type="text/javascript">
$( document ).ajaxStop( function() {
modalConnect();
});
</script>
The modalConnect function which loads the form which we want to present in the modal and a formUpdateURLDiv:
<script type="text/javascript">
function modalConnect()
{
//unbind the click event. If not done we will end up with multiple click event bindings, since binding is done after each ajax call.
$(".editItem").unbind('click');
//bind the click event
$(".editItem").click(function(ev) { // for each edit item <a>
ev.preventDefault(); // prevent navigation
var url = this.href; //get the href from the <a> element
$.get(url, function(results){
//get the form
var itemForm = $("#ajax_form_modal_result", results);
//get the update URL
var formUpdateURLDiv = $("#formUpdateURL", results);
//get the inner html of the div
var formUpdateURL = formUpdateURLDiv.html();
//update the dom with the received form
$('#itemFormModal').html(itemForm);
//show the bootstrap modal
$("#itemFormModal").modal('show');
$(document).ready(function () {
//bind the form to an ajax call. ajax call will be set to the received update url
submitItemModalFormBind(formUpdateURL);
});
}, "html");
return false; // prevent the click propagation
})
}
</script>
the formUpdateURL includes a server generated (see included view below) url to which the loaded form has to make its form submission call. We use this url to "init" the submitItemModalFormBind function:
<script type="text/javascript">
function submitItemModalFormBind(url){
//bind the form. prevent default behavior and submit form via ajax instead
$('#ajax_form_modal_result').submit(function(ev){
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success:function(response, textStatus, jqXHR){
var form = $("#ajax_form_modal_result_div", response);
//form is returned if it is not valid. update modal with returned form
//change this "if" to check for a specific return code which should be set in the view
if (form.html()) {
console.log('Form was invalid and was returned');
//update modal div
$('#ajax_form_modal_result_div').html(form);
$("#itemFormModal").modal('show');
}
//form is not returned if form submission succeeded
else{
//update the entire document with the response received since we received a entire success page and we want to reload the entire page
document.open();
document.write(response);
document.close();
//sort by modified date descending
//var notificationDiv = $("#notification", response);
//$('#notification').html(notificationDiv.html());
console.log('Form was valid and was not returned');
$("#itemFormModal").modal('hide');
}
},
error: function (request, status, error) {
var div = $("ajax_form_modal_result_div", request.responseText);
$('#ajax_form_modal_result_div').html(div);
//implement proper error handling
console.log("failure");
console.log(request.responseText);
}
});
return false;
});
}
</script>
..and to see what is going on at the server see below the view which handles the logic:
class UpdateTaskModalView(LoginRequiredMixin, View):
template = 'list_management/crud/item/update_via_modal.html'
def get_logic(self, request, task_id, **kwargs):
task = get_object_or_404(Task.objects, pk=task_id)
task_form = TaskForm(instance=task)
context = {
'model_form': task_form,
'item': task,
}
return context
def post_logic(self, request, task_id, **kwargs):
task = get_object_or_404(Task.objects, pk=task_id)
task_form = TaskForm(request.POST, instance=task)
if task_form.is_valid():
task = task_form.save(commit=False)
task.modified_by = request.user
task.save()
messages.add_message(request, messages.INFO, 'Item "%s" successfully updated' % (task.name))
return ('redirect', HttpResponseRedirect(reverse('show_list_after_item_update', kwargs={'list_id':task.list.pk, 'item_id':task.pk})))
context = {
'model_form' : task_form,
'list': task.list,
'item': task,
}
return ('context', context)
def get(self, request, task_id, **kwargs):
context = self.get_logic(request, task_id, **kwargs)
return render_to_response(
self.template,
context,
context_instance = RequestContext(request),
)
def post(self, request, task_id, **kwargs):
post_logic_return = self.post_logic(request, task_id, **kwargs)
if post_logic_return[0] == 'redirect':
return post_logic_return[1]
if post_logic_return[0] == 'context':
context = post_logic_return[1]
return render_to_response(
self.template,
context,
context_instance = RequestContext(request),
)
..the form template is already included in my question: ajax_form_modal_result_div, you only have to provide also the formUpdateURL. I did it via the template, which seems quite odd now that I write this post. could be easily provided via the view context.
Voila - Django Forms with Bootstrap Modals! Spice up your UI!
I hope this helps somebody to solve a similar problem.
I wrote this simple AJAX that did the trick for me, hope it helps:
$(document).on('submit', 'div.modal-body form', function(e) {
var form_el = $(this);
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (xhr, ajaxOptions, thrownError) {
if ( $(xhr).find('.errorlist').length > 0 ) {
form_el.parents('.modal-body').html(xhr);
} else {
form_el.parents('.modal-body').html('<h4>Formulario enviado correctamente</h4>');
}
},
error: function (xhr, ajaxOptions, thrownError) {
form_el.parents('.modal-body').html(xhr);
}
});
});
Oh btw, you will also need something like this in order to load your form into the modal:
$('.modal-class').on('click',function(){
let dataURL = $(this).attr('data-href');
$('.modal-body').load(dataURL,function(){
$('#modal_crear').modal({show:true});
});
});