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

257
Views
Ajax POST to an url then redirect to it

I'm building a web app where user can create markers on a leaflet map. Marker's details are saved in a backend with Django. My goal is to redirect the user to a detail page to fill marker's detail after clicking on the map. Here the js code to redirect to url create with an Ajax post.It's run when user click on the leaflet map.

map.on("click", function (e) { 
 window.location.href = {% url 'create' %};
     $.ajax({
          url: {% url 'create' %},
          data: { markers: markers_dict},
          type: "POST"
        }).done(function (response) {
          console.log(response);
        });
}

but I'm struggling in the views.py because this redirect and AJAX post create two request one GET and another POST:

def create_marker(request):
    if request.method == "POST":
        r = request.POST.get("markers")
        print(r)
        return JsonResponse({"response":"succeed"})
    else:
        return JsonResponse({"response":"failed"})

and the urls.py :

url_patterns = [
    path("create/",views.create_marker,name="create"),
]

It always returns the failed response even if it prints r in the console. How can I send these frontend data to the create url while redirect to this url and create a django from with these data ?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You are exiting the current page before making the ajax call. Move the redirection into ajax call’s done block. Something like this:

map.on("click", function (e) { 
     $.ajax({
          url: {% url 'create' %},
          data: { markers: markers_dict},
          type: "POST"
        }).done(function (response) {
         window.location.href = “{% url 'create' %}/” + response.id;
        });
}

You will need one more url in your urls.py for editing the marker object in backend. Try the CBV DetailView.

So first you post to this view with your map data. Once successful, redirect the user to the edit view of the created data.

  1. User clicks on map You create the minimal object in backend
  2. You get the ID of the created object on success
  3. Redirect the user to the form/edit view of that object
  4. User fills out the remaining items
  5. User clicks on save
about 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!