EgzEst
EgzEst

Reputation: 361

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">&times;</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>

Upvotes: 0

Views: 129

Answers (1)

Suever
Suever

Reputation: 65460

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

Upvotes: 1

Related Questions