JojoL
JojoL

Reputation: 141

Url Post request jquery Django

This might be a silly question, but I try to do a post request with jquery and I don't know how to set my "url" in my post request.

I have a variable "id":

var url = window.location.pathname.split('/');
var id = url[3]; 

And I would like my post to go to /mysite/xxx/"id"/

here is my post request:

   $.post("/mysite/xxx/'id'", { 
   name: "test"
   });

I don't know how to do include the variable "id" at the end of my url. Thank you for your help.

P.S: this post request goes to the exact same url where I try to implement it. I don't know if there is a simpler way to do it than specify the whole url again.

Upvotes: 0

Views: 129

Answers (3)

noirbizarre
noirbizarre

Reputation: 3429

If your posting on the current page you can do either:

$.post(window.location.pathname, {
    name: "test"
});

$.post('.', {
    name: "test"
});

If your posting on another page, you could use tokens in your url and pass it as a variable to your module:

<script>
    var url = '{% url my-url "{token}" %}';

    $.post(url.replace('{token}', 'param'), {
        name: "test"
    });
</script>

Notice that token should match the regex type to resolve successfully (You can't use {token} if parameter is defined with \d+).

I'm a little bit unsatisfied with this solution and I ended by writing my own application to handle javascript with django: django.js. With this application, I can do:

{% load js %}
{% django_js %}
<script>
    Django.onReady(function() {
        $.post(Django.url('my-url', 'param'), {
            name: "test"
        });
    });
</script>

The Django.onReady() wrapping is only necessary if posting early and needed to wait for Django.js to be ready. I a real case, you just have to do

$.post(Django.url('my-url', 'param'), {
    name: "test"
});

Upvotes: 0

koniiiik
koniiiik

Reputation: 4382

Why not just do this?

$.post(window.location.pathname, {
    name: "test"
});

Upvotes: 1

adriendenat
adriendenat

Reputation: 3475

$.post("/mysite/xxx/"+id, { 
   name: "test"
});

Your problem is "how to concatenate string and variable".

If you had to do something like "/mysite/xxx/ID/yyy/" you could do "/mysite/xxx/"+id+"/yyy/"

Upvotes: 1

Related Questions