简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM