Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
django ajax post to unexpect url

my ajax as follow:

<script>
    $(document).ready(function () {
        $.ajaxSetup({
            data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
        });
        $("#submit").submit(function () {
            var title = $("#title").val();
            var body = $("#body").val();
            var images = $("#browsefile")[0].files[0];

            $.ajax({
                type: "POST",
                data: {title: title, body: body, images: images},
                url: "{% url 'xxxxx' %}",
                success: function (result, statues, xml) {
                    alert(result);
                },
                error: function () {
                    alert("false");
                }
            })
        })
    })
</script>

and my urls pattern as follow:

from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

from blog import views

urlpatterns = [
    url(regex=r'^add/$', view=views.add, name='bbb'),
    url(regex=r'^newBlog/$', view=views.addblog, name='xxxxx'),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I except ajax post data to the method addblog, but I get POST /add/ HTTP/1.1 instead. anyone can told me where i made a mistake, thanks!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Try adding event.preventDefault(); in the submit function to disable the default behavior of the form, which is to follow the action attribute.

$("#submit").submit(function (event) {
        event.preventDefault();
        var title = $("#title").val();
        var body = $("#body").val();
        var images = $("#browsefile")[0].files[0];
        formdata = new FormData();
        formdata.append("images", images);
        formdata.append("body", body);
        formdata.append("title", title);

        $.ajax({
            type: "POST",
            data: formdata,
            url: "{% url 'xxxxx' %}",
            success: function (result, statues, xml) {
                alert(result);
            },
            error: function () {
                alert("false");
            }
        })
        return false;
    })

EDIT: per comment.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!