Phil O
Phil O

Reputation: 1668

Django Ajax Post - works sometimes

I have a Django application where I am using AJAX to do a post when submitting a form. My issue is what do I set the URL to in my JavaScript?

JavaScript snippet:

   $.ajax({
        url: "search/do_post/", // the endpoint
        type: "POST", // http method
        data : {
            relevancy: relevancy,
            report_id: report_id,
            query: query_text,
            //csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
        },

urls.py snippet:

path("search/do_post/", do_post_view, name="do_post"),

My issue is that sometimes the above works and sometimes it does not. When it doesn't I get:

POST http://localhost:1227/search/search/do_post/ 404 (Not Found)

When I see that I then remove the search part from the url in my JavaScript. Sometimes that works and sometimes not.

Any suggestions?

Upvotes: 1

Views: 53

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

You should start with a leading slash to define an absolute path, otherwise the request is send to a path relative to the current one, so /search instead of search:

$.ajax({
    url: "/search/do_post/",
    // …
},

you can also work with a {% url … %} template tag [Django-doc] which is more convenient:

$.ajax({
    url: "{% url 'do_post' %}",
    // …
},

Upvotes: 1

Related Questions