Reputation: 5402
I've gotten my view to successfully add my item to my cart. However, I just want it to ajax refresh (of sorts) the '#cart' div, while still on the original page. In other words, the item is added to into the cart, but only shown if I manually refresh. I just want it to look smooth and ajax-y.
Views.py:
@login_required
def add(request, profile):
if request.method != 'POST':
return HttpResponseNotAllowed('POST')
try:
item = Item.objects.get(slug=slugify(request.POST['itemname']))
except ObjectDoesNotExist:
item = Item(name=request.POST['itemname'])
item.save()
profile = Profile.objects.get(user=request.user)
profile.items.add(item)
response = simplejson.dumps(
{"status": "Successfully added."}
)
return HttpResponse (response, mimetype='application/json')
Template:
<form id="addItemForm" class="form-style" method="POST" action="/item/add/{{ profile }}/">
{% csrf_token %}
<input id="item-input" class="input-text inline required" name="itemname" type="text" />
<button class="blue" type="submit" id="additem">
Add Item
</button>
</form>
Script:
$('#addItemForm').submit(function(e){
e.preventDefault();
var form = $("#additem").attr("action");
var post_data = $.post($(this).attr('action'), $(this).serialize(), function(data, textStatus, jqXHR){
$('.item-selection').html(data);
result = $.ajax({
url: form,
data: post_data,
type: "POST",
success: function(data) {
//alert("Successfully added");
console.log()
$("#item-selection").replaceWith($('#item-selection', $(html)));
//{[( THIS IS WHERE I'D LIKE IT TO REFRESH)]}
},
error: function(data) {
// return the user to the add item form
$('#addItemForm').html(data);
}
});
});
Console error:
Uncaught TypeError: Cannot call method 'toLowerCase' of undefined
( I apologize for the formatting ) I'm an ajax beginner. It's clearly something wrong with my script. I just don't know where to go from here.
Thanks for your help in advance.
Upvotes: 2
Views: 376
Reputation: 5000
i cant see in your code what you mean. but this should reload the #cart element.. alhtough there is probably a better way to do it without downloading the entire page again just for the content on one element
$('#cart').load('ajax/test.html #cart');
Upvotes: 1