where to get the value when sending the request? - javascript

please help to solve the problem.
html:
<div class="modal fade" id="commonModal" tabindex="-1" role="dialog" aria-labelledby="commonModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="commonModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default but_cancel" data-dismiss="modal">Отменить</button>
<button type="button" class="btn btn-primary but_ok" data-dismiss="modal">Ok</button>
</div>
</div>
</div>
</div>
I send ajax request as follows:
$('#commonModalLabel').text('Удалить профиль?');
$('#commonModal .modal-body').html('Возможность восстановить профиль будет доступна в течение двух недель. Для восстановления нужно отправить администратору ресурса письмо с почтового адреса, который был указан в профиле.');
$('#commonModal').modal('show');
$('#commonModal .but_ok').on('click', function(){
console.log('ok');
$.ajax({
url: "/accounts/delete_profile/",
type: 'POST',
dataType:"json",
data: {},
success: function(data) {
if(data.result == true){
$('#mySmallModalLabel').text('Профиль удалён');
$('#infoModal').modal('show');
}
}
});
});
views.py:
def delete_profile(request):
result = False
if request.method == "POST" and request.is_ajax():
username = request.POST.get('username', '')
try:
entry = User.objects.get(username=username)
entry.is_active = 0
entry.save()
except:
pass
else:
result = True
data = {
'result': result,
}
return HttpResponse(json.dumps(data), content_type='application/json')
the problem is that in the log, the following error message:
Forbidden (CSRF token missing or incorrect.):
/accounts/delete_profile/
in the case of a form, I'd send the token as follows:
{% csrf_token %}
but in my case there is no form (!). please tell me where to get the token and how to send

Put it in your AJAX request.
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
},
Sometimes it does not work in some browsers (in my case it is chrome), so you can add these to data you are sending to view:
data['csrfmiddlewaretoken'] = $.csrf_token;
$.csrf_token is a global object for me, I put token printing it to template directly:
<script type="text/javascript">
$.csrf_token = '{{ csrf_token }}';
</script>

Your problem is explained in the django docs.
Be aware, that if no form is rendered django might not send a csrf token, you'll have to use the ensure_csrf decorator

Related

why my modal is not closing on clicking add area button

on click add area button my modal should be closed but it is not working. everything looks fine but i can not find error. id="category-popup" should close modal by $("#category-popup").modal('hide'); but it is not working can someone help me?
<div class="modal fade" id="category-popup" tabindex="-1" role="dialog" aria-labelledby="category-
popup" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Area</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="{{ route("save.area.ajax") }}" class="category-form">
{{ csrf_field() }}
<div class="form-group">
<label>Area Name</label>
<input type="text" name="name" class="form-control old-category" required="">
</div>
<div class="form-group">
<button type="button" class="btn btn-primary btn-block add-area-submit-btn">Add
Area</button>
</div>
</form>
</div>
</div>
</div>
</div>
java script
$('.add-category').click(function(event){
event.preventDefault();
$('.old-category').val('')
$('.category-form').attr('action' , '{{ route("save.area.ajax") }}');
$('#category-popup .modal-title').html('Add Area');
$('#category-popup .modal-footer button').text('Add Area');
});
$(document).on('click', '.add-area-submit-btn', function(e){
e.preventDefault();
var btn = $(this);
if($('.category-form .old-category').val() != ""){
$.ajax({
type: 'post',
data: $('.category-form').serialize(),
url: $('.category-form').attr('action'),
success: function(res){
$("#area-select").html(res);
$("#category-popup").modal('hide');
}
});
}
});
The syntax for hiding modal is correct but please make sure that your $.ajax request is succeeding. Try doing console.log() in $.ajax success. Or add error in your ajax so you could know the error
$.ajax({
type: 'post',
data: $('.category-form').serialize(),
url: $('.category-form').attr('action'),
success: function(res) {
console.log("ajax request success");
$("#area-select").html(res);
$("#category-popup").modal('hide');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("ajax request failed: " + errorThrown);
}
});
check errors in the cnsole it submit area in option field but not closed
Hm, weird, are you sure you include jQuery correctly? Could you show your included scripts?
jQuery should be like: <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
In JavaScript one error results in broking whole script. And without jQuery your "modal" action will not work. I think it's the reason why your script not working.

failed to load resource the server responded with a status of 403

I am trying to make two ajax calls to get amazon servers link and after that I am trying to play it in a modal but getting this I don't know how to solve or is there any other way in first ajax call I am taking the url from my own server and by that url's page I am trying to get amazon server's link after that I am trying to play a video i.e. on that link but it's not working
<script>
$(document).ready(function(){
$('.activityinstance').click(function(){
var url = $(this).find("#mod_id").attr('data-link');
$.ajax({
type : 'post' ,
url : url ,
data : {flag:'ajax'},
success: function(result){
$.ajax({
type : 'get' ,
url : result ,
success: function(data){
data=data.substring(0, data.indexOf("4"));
console.log(data);
$("#Mdlheader").html(data);
var playerInstance = jwplayer("myElement");
playerInstance.setup({
file: data,
});
}
});
}
});
});
});
</script>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 id="Mdlheader" class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div id="myElement"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Bootstrap Modal in Django application with Ajax

I have little problem in my Django application. I am tring to use modal from bootstrap 4 and ajax to create new object. Here below you see code that I used. When user click the button I dont see modal window but background became grey. What I did wrong? Why I dont see modal? Is my ajax correct?
detail.html:
<!-- BUTTON TO TRIGGER THE ACTION -->
<button class="add-group-task" data-toggle="modal" data-target="#add-group-task-modal" data-url="{% url 'project:group_task_add' project_code=project.code %}">{% trans 'Create' %}</button>
<table class="table table-bordered" id="group-tasks-table">
<!-- TABLE CONTENT-->
</table>
<!--MODAL-->
<div class="modal fade" id="add-group-task-modal" tabindex="-1" role="dialog" aria-labelledby="add-group-task-modal-title" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
</div>
</div>
</div>
urls.py:
url(r'^(?P<project_code>[0-9a-f-]+)/add_new_group_task/$', group_task_add, name='group_task_add'),
view.py:
def group_task_add(request, project_code):
data = dict()
project = get_object_or_404(Project, pk=project_code)
if request.method == 'POST':
form = GroupTaskAddForm(request.POST)
if form.is_valid():
group_task = form.save(commit=False)
group_task.project = project
group_task.save()
data['form_is_valid'] = True
group_tasks = GroupTask.objects.filter(project=project_code)
data['html_group_tasks'] = render_to_string('project/project_detail.html', {'group_tasks': group_tasks})
else:
data['form_is_valid'] = False
else:
form = GroupTaskAddForm()
context = {'form': form}
data['html_group_task_add_form'] = render_to_string('project/group_task_add.html', context, request=request)
return JsonResponse(data)
javascript:
$(function () {
/* Functions */
var loadForm = function () {
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#add-group-task-modal").modal("show");
},
success: function (data) {
$("#add-group-task-modal .modal-content").html(data.html_form);
}
});
};
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#group-tasks-table tbody").html(data.html_group_tasks);
$("#add-group-task-modal").modal("hide");
}
else {
$("#add-group-task-modal .modal-content").html(data.html_group_task_add_form);
}
}
});
return false;
};
// Create book
$(".add-group-task").click(loadForm);
$("#add-group-task-modal").on("submit", ".js-group-task-add-form", saveForm);
});
group_task_add.html:
<form method="post" action="{% url 'project:group_task_add' project_code=project.code %}" class="js-group-task-add-form">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title" id="addGroupTaskModalLabel">{% trans 'Create a new group task' %}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="formGroupTaskInput">{% trans 'Name' %}</label>
{{ form.name }}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">{% trans 'Close' %}</button>
<button type="submit" class="btn btn-primary">{% trans 'Create' %}</button>
</div>
</form>
ERROR:
try with following html and js code combination:
<!-- BUTTON TO TRIGGER THE ACTION -->
<button ... onclick="modalHandler()">{% trans 'Create' %}</button>
// js code
function modalHandler(){
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#add-group-task-modal").modal("show");
},
success: function (data) {
$("#add-group-task-modal .modal-content").html(data.html_form);
}
});
};

Get form values and pass it to Bootstrap modal on Submit

I'm trying to get my form data and pass it as JSON to my modal dialog, which also should open on Submit button!
Here is what I've done so far:
HTML
<form class="form-horizontal" id="configuration-form">
--unimportant--
<button type="submit" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#myModal">Submit</button>
</form>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Please copy this code to your HTML</h4>
</div>
<div class="modal-body">
<code id="configurationObject"></code><br/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS
(function(formId) {
$("#" + formId).submit(function(event){
event.preventDefault();
var errMsg = "Something went wrong with form submit, please try again";
var json = convertFormToJSON(this); //here I got my json object with all my form data
$.ajax({
type : 'POST',
data: {conf: JSON.stringify(json)},
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(data){
$("#configurationObject").html(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
return false;
});
})("configuration-form");
After Submit button is clicked I do get my JSON object with form data (I can log it after
var json = convertFormToJSON(this)
and my modal dialog window is opened, but I do miss my data aka.
element with id="configurationObject" is empty.
Thanks in advance
Have you tried to append() the data to #configurationObject rather than using html()?
According to documentation $.html() accepts A string of HTML to set as the content of each matched element. .
Here you are passing json data instead of string. So first, you have to convert json response to string. $("#configurationObject").html(JSON.stringify(data));
or you can use
$("#configurationObject").append(data);

Method Not Allowed when using url for in jquery

How to pass parameters inside an URL for in javascript?
I have a case like this:
$('.btn-delete').click(function () {
var user_id = $(this).attr('userid');
console.log(user_id);
$('#modal-form').attr('action', "{{ url_for('admin.delete_user' , id="' + user_id +'" ) }}");
});
user_id variable has a value 56f52ea551d72027711157d6
If I do like this I get Method Not Allowed because the URL looks like this:
/admin/users/delete/%27%20+%20user_id%20+%27
How should I pass arguments in this part?
$('#modal-form').attr('action', "{{ url_for('admin.delete_user' , id="' + user_id +'" ) }}");
please somebody help me?
Edit:
The method that I use in route admin.delete_user in python is:
mod_admin.add_url_rule( '/users/delete/<string:id>', methods=['GET'])
def delete_user(self, id):
mongo.db.users.remove({'_id': ObjectId(id)})
return redirect(url_for('admin.users'))
And the modal popup:
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span></h4>
</div>
<form id="modal-form" action=" " method="POST">
<div class="modal-body">
<p>Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-sm btn-style" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default btn-sm btn-filter-apply btn-style" >Yes</button>
</div>
</form>
</div>
</div>
Because the template {{ }} is evaluated by jinja and converted to a string before the browser ever sees it, you don't need to concatenate all of the strings like you have shown. The id parameter should be passed as a standard keyword arguments.
$('#modal-form').attr('action', "{{ url_for('admin.delete_user' , id=user_id|string) }}");
You will also need to allow POST requests to the specified URL by updating this
mod_admin.add_url_rule( '/users/delete/<string:id>', methods=['GET', 'POST'])
UPDATE
Because user_id is actually defined in javascript, this is an issue because user_id is not accessible to jinja. To get around this, you will need to create your URL in this way:
$('#modal-form').attr('action', "{{ url_for('admin.delete_user') }}" + user_id);

Categories

Resources