简体   繁体   中英

Url not being called through ajax

I'm trying to send some data to my django view through ajax. For some reason, the url is not being called. It always alerts "Not found!".

Here is my ajax code:

$.ajax({
url: "/AddToDb/",
type: "POST",
data: {"id":6,"quantity":3},
csrfmiddlewaretoken:'{{ csrf_token }}',
success: function(){
     alert("Found!");
  // code to update DOM here
},
error: function(xhr, ajaxOptions, thrownError){
   alert("Not found!");
}

});

This is my url:

url(r'^AddToDb/$', 'Phase_2.views.AddToDb'),

And this is my view:

def AddToDb(request):
jdfsjfhs
if request.method == 'POST' and request.is_ajax():
    JSONdata = request.POST['data']
    dict = json.JSONDecoder().decode('JSONdata')
    obj = ShoppingCart.objects.get(id=4)
    obj.quantity =  dict['quantity']
    obj.save()
return render(request,"HTML.html")

It's just a dummy call to check whether i'm able to send data to my view or not. I'm a newbie so i'm sure i'm making a stupid mistake somewhere. Please help!

PS The "jdfsjfhs" in my view is just to check whether the view is being called or not. It's not being called.

When making an ajax request. You need to send full url for instance localhost/AddToDb or www.example.com/AddToDb . You can check the final generated request from console section of either firefox or chrome. Hopefully that shall help.

use firebug to debug your javascript function. it will tell you whether the function is sending the correct response or not.

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