Method Not Allowed when using url for in jquery - javascript

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);

Related

Update asp-route-id with jQuery

I'm building a razor pages application, and I want to use a modal as a partial view.
Foreach loop from where I'm opening the modal:
#foreach (var item in Model.SourceFiles)
{
<tr>
<td>#item.Id</td>
<td>#item.FileName</td>
<td>#item.Created</td>
<td>
#(item.IsConverted == true ? "Exported" : "Imported")
</td>
<td>
<button type="submit" class="btn btn-primary" asp-page-handler="FileContent" asp-route-fileId="#item.Id">View</button>
</td>
<td>
#if ((await authorizationService.AuthorizeAsync(User, "DeletePolicy")).Succeeded)
{
Delete
}
</td>
</tr>
}
I'm trying to set a new value of an asp-route-id tag using javaScript (jQuery), but I cant get it to work.
function triggerDeleteModal(itemId) {
$('#' + 'deleteModal').modal('toggle');
$("#confirmDeleteButton").attr('asp-route-deleteid', itemId)
}
Modal (partial view):
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalTitle">Caution!</h5>
</div>
<div class="modal-body">
<p style="white-space: pre-wrap;">#Model.DeleteModalText</p>
<p></p>
</div>
<div class="modal-footer">
<button type="submit" id="confirmDeleteButton" class="btn btn-secondary" data-bs-dismiss="modal">Yes</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
When pressing the yes-button (#confirmDeleteButton) in the modal to submit the form, the id is not getting passed in the asp-route-deleteid tag helper, and the id is always 0 in the OnPost-method.
Code behind where deleteid always is 0:
public async Task<IActionResult> OnPostAsync(int deleteid)
{
//code for deleting stuff
}
When trying to console.log the value of any attribute besides asp-route tags, the value is shown. When trying to log the value of an asp-route tag, the value is undefined.
Any ideas of how I can get the asp-route-deleteid to be passed to the code behind?
BR
The asp-route-* attribute works on tag helpers, which are server-side components. It is not rendered to the browser and is inaccessible to JavaScript. It is designed to work with elements that have an href, action or formaction attribute, and it either adds the attribute value to the query string of the generated href, or as a URL segment depending on the route template for the target page.
Generally, you shouldn't pass POST data within the URL, so instead, you can wire up a click event handler to the confirmDeleteButton that initiates an AJAX post that passes the deleteid:
$('#confirmDeleteButton').on('click, function(){
$.post('/yourpage',{deleteid: itemId}, function(){
// process the call back
})
})

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);

Django Angularjs How to call Http request with specific Id

i am very new in angularjs.I am trying to pull data in one of my django template using angularjs.This is the view by which i actually trying to pull data.
def download_history(request,download_id):
from django.core import serializers
download_history = DownloadHistory.objects.filter(user = request.user,pk=download_id)
ctx_detail_history = serializers.serialize('json', download_history)
return HttpResponse(ctx_detail_history)
this is the urls
url(r'^history_detail/(?P<download_id>\d+)/$',views.download_history,name = 'download_history'),
and this is my template where i am trying to pull data and trying to show in a jquery pop up modal.
{% extends 'base.html' %}
{% block title%}User Subscription {%endblock%}
{%block content%}
<div style="margin-top:100px;background-color:#85ADFF;" ng-app='history'>
<table class="table table-striped" >
{%for download_history_name in download_history%}
<tr>
<td><button type='button' data-toggle="modal" data-target="#myModal"><a href={%url 'download_history' download_history_name.id %} >{{download_history_name.name}} and the id {{download_history_name.id}}</a></button></td>
</tr>
{%endfor%}
</table>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Objact Name</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-striped" ng-controller='HistoryCtrl'>
<tbody>
<tr>
{[{detail_history.fields.name}]}
{[{detail_history.fields.download_rate}]}
{[{detail_history.fields.photo.url}]}
{[{detail_history.fields.downloaded_time}]}
{[{detail_history.fields.DuePayment}]}
</tr>
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
{%block extrajs%}
<script>
var app = angular.module('history',[]);
app.config(function($httpProvider){
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});
app.config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
});
app.controller('HistoryCtrl',['$scope','$http' , function($scope,$http){
$http.get('/history/history_detail/(? P<download_id>\d+)/').success(function(data){
//$scope.doToggle=false;
$scope.detail_history=data;
}).error(function(data,status){
$scope.data = data || 'Request Fails';
$scope.status = status;
console.log(data)
});
}]);
</script>
{%endblock%}
{%endblock%}
now the problem is ,though i am trying to pull data with a specific id,but its not working,, in fact if i inspect the page ,it shows the return URL something that
http://localhost:8000/history/history_detail/(?Pd+)/
now whats the problem,definitely i make a mistake here,but i am very new in angularjs and can not figure it out.Is it possible to solve the problem using ng-click function?
From a cursory examination of your JavaScript it appears that you're trying to make a GET request to a URL including a regular expression. This makes sense for your Django configuration because you're telling the application to expect a number in the url that you assign to a variable named download_id. It appears you have copied this URL directly into your JavaScript where in fact you should be providing a specific download id in your GET request (e.g. '/history/history_detail/12345/').

Pass php variable using jquery ajax to a modal

I am having a problem with my jquery ajax script. I can not get it to pass the variable to the modal. I have been messing with this all weekend and can not figure out way it does not pass the variable.
This is the link to call the modal and the id I am trying to pass
echo '<img src="./images/see.png" class="open-editexpenses" data-target="#editexpenses" data-id="' . $value['expid'] . '" >';
This is the jquery ajax script
$(document).on('click', '.open-editexpenses', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "expenses.php",
data: {id: id},
success: function() {
$('#editexpenses').modal('show');
}
});
});
This is the modal I am opening
<div class="modal fade" id="editexpenses" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<?php
echo $id;
var_dump($_POST);
//var_dump($_GET);
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
$(x).data('id') is not the same as $(x).attr('data-id'), which is probably what you're after to read the data-id attribute of your img element.
See jQuery Data vs Attr? for more info.
I'm going to assume the 'modal' is expenses.php and also that you're using a jQuery plugin for $('#editexpenses').modal('show'); to mean anything.
From what I can see you haven't actually added the response from expenses.php into the DOM. You can do this by altering the success function in your AJAX call:
success: function(html) {
$('body').append(html);
$('#editexpenses').modal('show');
}
Here I've just added the HTML returned to the end of the page, but jQuery has plenty of other ways you can insert into the DOM: https://api.jquery.com/category/manipulation/
As an aside, be careful about assuming that the $id variable in expenses.php exists. This works when PHP's register_globals setting is on, but this is considered extremely bad practice and was deprecated in PHP 5.3.0 and actually removed in 5.4.0. Just use $_POST['id'] instead.

Pass an ID To Twitter Bootstrap Model

I am trying to pass an id to a twitter bootstrap model for a delete confirmation (basic CRUD page) and for the life of me I can't get this working. Looked at several examples still unable to get to work. I need to get the data-id to pass to the model and append the href link so that for example they confirm it takes them to the appropiate page (eg: delete.php?id=5) Any ideas would be greatly appreciated. Heres my code:
The link:
<a href="#msgDelete" data-toggle="modal" class="open-dialog btn btn-mini btn-danger" data-id="'.$row["id"].'">
The Model:
<div id="msgDelete" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Are You Sure?</h3>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this product? This action can not be reversed. <br /><br /><em>Remember if you want to just hide the product from your store you can mark it as inactive.</em></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<a href="delete.php?id=" class="btn btn-danger" id="clink" >Delete Product</a>
</div>
The JavaScript:
<script type="text/javascript">
$(document).on("click", ".open-dialog", function () {
var productId = $(this).data('id');
console.log(productId);
//$(".modal-body #clink").href( 'delete.php?id=' + productId );
$("#clink").attr("href", "delete.php?idd=" + productId);
// As pointed out in comments,
// it is superfluous to have to manually call the modal.
// $('#addBookDialog').modal('show');
});
</script>
Look like your code has misprint.
$("#clink").attr("href", "delete.php?idd=" + productId);
-----^
Should be
$("#clink").attr("href", "delete.php?id=" + productId);
At least http://jsfiddle.net/egX3W/ shows that you href changes as you want.
in your code
<a href="#msgDelete" data-toggle="modal" class="open-dialog btn btn-mini btn-danger" data-id="'.$row["id"].'">
change it to
<a data-href="delete.php?id=<?php=productId?>" data-toggle="modal" class="open-dialog btn btn-mini btn-danger" data-id="'.$row["id"].'">
so, it will be automatically pass to your javascript... and you won't need to pass it in script...
change your script to this
$(document).on("click", ".open-dialog", function () {
var productId = $(this).data('id');
console.log(productId);
});

Categories

Resources