I have stored some data on localStorage( Itemnames and ItemIds), As shown on this image:LocalStorage console.log
now I want to send itemid’s to django views from ajax. Filter the products having those id, and return back to template.
I am trying to pass data to views on this way:
$(document).ready(function() {
var compare = localStorage.getItem("comparisionItems");
var compareObj = JSON.parse(compare);
console.log(compare)
console.log(compareObj)
$.ajax({
url: './compare',
type: "POST",
data: {'compare_id': compareObj },
headers: { "X-CSRFToken": $.cookie("csrftoken") },
dataType: "json",
success: function (data) {
console.log(data)
},
error: function () {
alert("Some problem on passing data");
}
});
});
Ok, so in your test case, what specifically is the value of request.body, and therefore data at the line prior to that?
(What does your post request look like?)
Assuming that there’s nothing being misrepresented by the print function, it looks like the value part of the object you’re passing is being processed as a string rather than as a nested object.
That gives me a couple ideas you could try - and in no particular order -
Instead of setting data to {'compare_id': compareObj }, just set it to compareObj. That also means that your references in your view will change from data['compare_id']['itemIds'] to data['itemIds'].
Call json.loads on data[‘compare_id’].
Superficially, I think any one of these would be enough - the choice comes down to what you’re comfortable with. However, it’s possible that you may need to do both of the first two together to get it to work.
Side note: One of the quickest / easiest ways to see what’s being passed is to look at the network tab within your browser’s developer tools. It’ll show you exactly what’s being sent. Also, if you’re going to be working with AJAX calls on a regular basis, you’re going to find it extremely useful to get comfortable with running your code in the context of a debugger.
I got the id passed to my product variable doing following method:
I passed data to ajax without json.parse, in my context I passed : data: compare,
and updated views as following:
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
data = json.loads(request.body)
compare_ids = data['itemIds']
products = Products.objects.filter(id__in=compare_ids)
context={'products':products}
return render(request,'./ecommerce/compare.html', context)
else:
return render(request,'./ecommerce/compare.html')
Now,
When I print data on html template by doing {{product.name}} it shows blank. I think I should do something with if/else, could you please help me with this?
When you’re posting code here, you need to surround the code with lines of three backtick - ` characters. That means you’ll have a line of ```, then your code, then another line of ```. That forces the forum software to maintain the formatting of your code, which is critical with Python.
I don’t see anything wrong with your view. (I’ll assume the first return statement is indented properly.)
Next steps I would take would be to verify that compare_ids is a list of the right datatypes matching your id field of Products and that your products queryset is returning the expected results.
If both of those are correct, then we’d need to see the compare.html template to see how you’re trying to render the data.
Compare.html has simple logic, when the page loads it will send the post data from ajax as shown above and then I am trying to print the product on template via:
{% for products in products %}
{{product.name}}
{% endfor %}
I think first when page loads before sending data will be GET, and then when it sends data it will get records from POST and it should print that data, I am assuming this.
Should I do something on my views to achieve return on this way?
sorry I am doing correctly {{products.name}} or {{product.name}} if variable is product. I am aware of this, but data is not showing while on console.log network shows 200 status code. So I think I should do something with views, is there anything that I need to do there?