Currently using the django-carton app, I have a django view that returns JSON data that I use in an ajax call. Broadly speaking, I have got it working but struggling to work out how I can pass my item quantity (using ajax).
Within the template I can call my item quantities using:
{% for item in cart.items %}
{{ item.quantity }}
The ajax call connects to the view to return the Json data:
def cart_detail_api_view(request):
# cart_obj, new_obj = Cart.objects.new_or_get(request)
cart = Cart(request.session)
products = [{"name": x.name, "price": x.price} for x in cart.products]
cart_data = {"products": products, "total": cart.total}
return JsonResponse(cart_data)
This is my Jquery/Ajax call:
$(document).ready(function() {
var productForm = $(".form-product-ajax") // #form-product-ajax
productForm.submit(function(event) {
event.preventDefault();
// console.log("Form is not sending")
var thisForm = $(this)
//var actionEndpoint = thisForm.attr("action");
var actionEndpoint = thisForm.attr("data-endpoint");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax({
url: actionEndpoint,
method: httpMethod,
data: formData,
success: function(data) {
var submitSpan = thisForm.find(".submit-span")
if (data.added) {
submitSpan.html("In cart <button type='submit' class='btn btn-link'>Remove?</button>")}
var currentPath = window.location.href
if (currentPath.indexOf("") != -1) {
refreshCart()
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
})
function refreshCart() {
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
// $(cartBody).empty()
var productRows = cartBody.find(".cart-product")
var cartTotal = cartTable.find(".cart-total-sec")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data) {
console.log("success")
console.log(data)
if (data.products.length > 1) {
$(cartBody).empty()
productRows.html("")
$.each(data.products, function(index, value) {
console.log(value)
console.log(data.count)
cartBody.append("<tr><td>" + value.name + "</td><td>" + value.price + "</td></tr>")
})
cartTotal.find(".cart-total").text(data.total)
console.log(data.total)
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
})
You have to instruct your $.ajax() call that you are expecting data in JSON format, so the data is parsed properly in your success callback:
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
dataType: 'json', // <- here
success: function(data) {
// ...
},
error: function(errorData) {
// ...
}
})
Related
I want to pass array data in views.py file for that I use AJAX and passing data through AJAX. But there I am not able to get all data in views.py file, some of the data are missing.
display.html
var SelectedID = [];
function getvalues() {
$(':checkbox:checked').each(function (i) {
SelectedID[i] = $(this).val();
console.log("Selected Data", SelectedID[i])
$.ajax({
url: "{% url 'addtoexisting' bid=adduser.id %}",
type: "POST",
dataType: "json",
data:{
SelectedID : SelectedID[i],
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
console.log("Selected Data AJAX", SelectedID)
alert("Successfully sent the Data to Django");
},
error: function (xhr, errmsg, err) {
// alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
});
}
views.py
def display(request):
is_ajax = request.headers.get('x-requested-with') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
SelectedID = request.POST.get('SelectedID')
print(SelectedID)
return render(request, 'display.html',{})
SelectedID[i] = $(this).val(); in this selectedID There are 10 records but in print of views.py there is only 6 records, other data are missing.
I've got a Django website and I'm trying to integrate Stripe using Django the Stripe API on the backend and Vue.js on the frontend. However, when I try to run the checkout link that's supposed to redirect me to the payment processing page, I get the following error:
Error: IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.
at new r (https://js.stripe.com/v3/:1:6143)
at Js (https://js.stripe.com/v3/:1:165350)
at $s (https://js.stripe.com/v3/:1:165646)
at https://js.stripe.com/v3/:1:166758
at Qs (https://js.stripe.com/v3/:1:166769)
at nc (https://js.stripe.com/v3/:1:167275)
at Ec.redirectToCheckout (https://js.stripe.com/v3/:1:188030)
at http://localhost:8000/dashboard/myaccount/teams/plans/:342:39
Here's the Vue.js method responsible for this:
<script src="https://js.stripe.com/v3/"></script>
<script>
const PlansApp = {
data() {
return {
}
},
delimiters: ['[[', ']]'],
methods: {
subscribe(plan) {
console.log('Subscribe:', plan);
const stripe = Stripe('{{ stripe_pub_key }}');
fetch('/dashboard/myaccount/teams/api/create_checkout_session/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
body: JSON.stringify({
'plan': plan
})
})
.then(function(response) {
return response.json()
})
.then(function(session) {
console.log(session)
return stripe.redirectToCheckout({ sessionId: session.sessionId })
})
.then(function(result) {
if (result.error) {
console.log('Error:', result.error.message)
}
})
.catch(function(error) {
console.log('Error:', error);
});
}
}
}
Vue.createApp(PlansApp).mount('#plans-app')
</script>
And here's the Django code that creates the session on the backend:
#login_required
def create_checkout_session(request):
stripe.api_key = settings.STRIPE_SECRET_KEY
data = json.loads(request.body)
plan = data['plan']
if plan == 'basic':
price_id = settings.STRIPE_BASIC_PRICE_ID
else:
price_id = settings.STRIPE_PRO_PRICE_ID
try:
checkout_session = stripe.checkout.Session.create(
client_reference_id = request.user.userprofile.active_team_id,
success_url = '%s%s?session_id={CHECKOUT_SESSION_ID}' % (settings.WEBSITE_URL, reverse('team:plans_thankyou')),
cancel_url = '%s%s' % (settings.WEBSITE_URL, reverse('team:plans')),
payment_method_types = ['card'],
mode = 'subscription',
line_items = [
{
'price': price_id,
'quantity': 1
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
except Exception as e:
return JsonResponse({'error': str(e)})
I'm struggling to find out why I'm getting the error that I'm getting and would be grateful for any help!
I guest the problem come from the 'success_url' and the 'cancel_url'.
Try to add http:// or https:// in your url
Cordially
how I can modify my code that be check login&password without refreshing? Ajax call function in django to check login and password then send .json with result. Next one I want display error in js if result is failed or play animation if it's true.
js code:
function CheckBeforeSend()
{
var LoginInput = document.getElementById('flogin');
if(LoginInput.value.match(/^[a-zA-Z]+['.']+[a-zA-Z]+[0-9]+$/) == null)
{
if(document.getElementById('Windows').childElementCount > 2)
{
document.getElementById('Windows').children[0].remove();
}
AddPicture("paperJsConn");
}
else
{
document.getElementById("button").type = "submit";
$.ajax({
url: 'http://127.0.0.1:8000/',
data: $('#login_form').serialize(),
type: "POST",
async:false,
success: function(response) {
var CheckingCorrect = response['result'];
//if checkingcorrect play func animation.
},
error: function(error){
alert('No Connection!');
}
});
}
}
$('#login_form').submit(function(e){
e.preventDefault();
$.post('view-url', $(this).serialize());
}); // this event dont work.
views.py:
def Logget(request):
if request.method == 'POST':
login = request.POST.get('flogin')
response_data = {}
response_data['result'] = 'Failed'
lengthBase = UsersLog.objects.count()
for i in range(lengthBase):
if login == str(UsersLog.objects.get(id=i+1)):
password = request.POST.get('lpass', False)
if str(password) == str(UsersLog.objects.get(id=i+1).password):
response_data['result'] = 'Succes'
break
return JsonResponse(response_data)
return render(request, 'index.html')
I'm trying to upload a picture to my server with some additional data. My angularJs code is that:
function create_question(question, callback){
var form = new FormData()
var settings = {
"url": "http://127.0.0.1:8000/" + "question/api/create_question/",
"method": "POST",
"headers": {
'Content-Type': undefined
},
"processData": false,
"data": form
}
$cordovaFile.readAsDataURL(cordova.file.dataDirectory, question.name)
.then(function (success) {
form.append("file", success)
form.append("title", question.title)
form.append("options", JSON.stringify(question.options))
form.append("correct_option", question.correct_option)
form.append("question_id", question.question_id)
form.append("project_id", question.project_id)
$http(settings).then(function (response) {
if (response.data.hasOwnProperty("date_str")) {
callback(true, response.data)
console.log("succesFull")
} else {
console.log(JSON.stringify(response.data))
callback(false, response.data)
}
}, function (response) {
console.log(Utf8Decode(response.data))
callback(false, response.data)
});
// success
}, function (error) {
callback(false,error)
// error
});
}
In my server, I have that view:
#parser_classes((MultiPartParser, ))
class CreateQuestion(APIView):
def post(self, request, format=None):
picture = request.data['file']
question_id = request.data['question_id']
project_id = request.data['project_id']
options = request.data['options']
title = request.data['title']
correct_option = request.data['correct_option']
username = request.user.username
project = Project.objects.get(project_id=project_id)
if project.owner_user.username == username:
ext = '.jpg'
aws = AWSClient()
picture_name = question_id + ext
picture_url = aws.put(picture, 'question_pictures', picture_name)
question = Question.objects.create(question_id=question_id, title=title,
picture_url=picture_url, options=options, owner_project=project,
correct_option=correct_option)
project.question_count += 1
project.picture_url = picture_url
project.save()
serializer = QuestionSerializer(question, context={"request": request})
return JsonResponse(serializer.data)
else:
return JsonResponse({"result": "fail"})
After I made the request, question was created and the picture file was uploaded to Amazon S3. However, I could not open the resulting file in my pc. Where am I doing mistake?
After a long search on the internet, I found the answer. First, I read file with
$cordovaFile.readAsArrayBuffer(directory,filename)
After that, I created a Blob object with the file:
var imgBlob = new Blob([success], { type: "image/jpeg" } );
My final angularJS code is:
function create_question(question, callback){
var form = new FormData()
$cordovaFile.readAsArrayBuffer(cordova.file.dataDirectory, question.name)
.then(function (success) {
var imgBlob = new Blob([success], { type: "image/jpeg" } );
form.append("file", imgBlob)
form.append("title", question.title)
form.append("options", JSON.stringify(question.options))
form.append("correct_option", question.correct_option)
form.append("question_id", question.question_id)
form.append("project_id", question.project_id)
var settings = {
"url": "http://127.0.0.1:8000/" + "question/api/create_question/",
"method": "POST",
"headers": {
'Content-Type': undefined
},
"filename": question.id,
"processData": false,
"data": form,
"file": success,
"filename": "file"
}
$http(settings).then(function (response) {
if (response.data.hasOwnProperty("date_str")) {
callback(true, response.data)
console.log("succesFull")
} else {
console.log(JSON.stringify(response.data))
callback(false, response.data)
}
}, function (response) {
console.log(JSON.stringify(response.data))
callback(false, response.data)
});
// success
}, function (error) {
callback(false,error)
// error
});
}
I have this connection with ajax, I put a print in the formulario result and in the python in the bash I get the result from the select like this:
[{"pk": 1, "model": "pagoproveedores.test", "fields": {"just_a_test": "google"}}]
the problem is that when I want show it in the template it send me Server Response: undefined. Looks like I'm not getting the response from the view, I know I have the data that I need.
view.py
def ajax(request):
print 'inside ajax'
if request.POST.has_key('client_response'):
print 'inside if'
x = request.POST['client_response']
y = test.objects.filter(just_a_test=x)
formulario = serializers.serialize('json', y)
return HttpResponse(formulario, mimetype="application/json")
else:
return render_to_response('ajaxexample.html', context_instance=RequestContext(request))
Ajax.html
$(document).ready(function () {
$("#button").click(function () {
var input_string = $("#forminput").val();
$.ajax({
url: "/ajaxexample_json",
type: "POST",
dataType: "json",
data: {
client_response: input_string,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (json) {
$('#result').append('Server Response: ' + json.server_response);
},
error: function (xhr, errmsg, err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
Instead
return HttpResponse(formulario, mimetype="application/json")
do
return HttpResponse(formulario, content_type="application/json")
I Fix it using this code and same view, ;)
$(document).ready(function () {
$("#button").click(function () {
var input_string = $("#forminput").val();
$.ajax({
url: "/ajaxexample_json",
type: "POST",
dataType: "json",
data: {
client_response: input_string,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (json) {
var jsonResponse = eval(json);
$.each(jsonResponse, function(index, element){
alert(JSON.stringify(jsonResponse));
$('#resultTables').append('<tr><td align="center">'+jsonResponse[0]["pk"]+'</td> <td align="center">'+jsonResponse[0]["fields"]["nombre_miembro_1"]+'</td> <td align="center"></td></tr>');
}); ;
},
error: function (xhr, errmsg, err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});