I am working with Django and AJAX,
I have a template where people can select an option and then click a submit button. The button fires an Ajax function that sends the data to my view where it is processed and should return a value back to the template.
The issue is when the post goes through, it hits the view, and nothing is returned to the template, I am not sure if this is because the view isn't getting any data, but it isn't firing any of my conditional statements, so it acts like its working but doesn't return anything.
My HTML form:
<form method="POST" id="buy_form" name="buy_form" action="{% url 'manage:buy' %}">
{% csrf_token %}
<div class="buy_top_section">
<div class="width">
<div class="spacing">
<h3 class="sell_title">How much do you want to sell?</h3>
<input type="text" id="amount" class="buy_input_top" maxlength="10" name="amount" type="number" required>
<select id="selected" class="buy_selection" name="wanted">
<option value="generate_b">BTC</option>
<option value="generate_e">ETH</option>
<option value="generate_l">LTC</option>
</select>
</div>
<span class="float_clear"></span>
<button id='generate' type="submit" value="currency_details" class="custom_button"l">Generate
</button>
</div>
</div>
</form>
<!-- What needs to be returned from thew view -->
<h1>{{ address }}</h1>
My AJAX
$(document).on('submit', '#buy_form', function (e) {
e.preventDefault()
$.ajax({
type: 'POST',
url:'/manage/buy/',
data:{
currency:$('selected').val(),
amount:$('#amount').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success: function (){
}
})
});
My Django View
def buy_corsair(request):
if request.method == 'POST':
if request.POST.get('wanted') == 'generate_b':
# Get the amount entered
amount = request.POST.get('amount')
# Generate a new B address
new_b_address = client.create_address(b_account_id)['address']
# Point the address at the user
request.user.user_address.b_address = new_b_address
# Save address to current user
request.user.user_address.save()
# Pass the address to the template
context = {'address': new_b_address}
return render(request, context)
urls.py
urlpatterns = [
# Buy Page
path('buy/', views.buy_corsair, name='buy'),
]
Ajax requests run in background, django render function render a template to body, so you can not render this way. You could like this;
dont forget include
from django.http import HttpResponse
def buy_corsair(request):
if request.method == 'POST':
if request.POST.get('wanted') == 'generate_b':
# Get the amount entered
amount = request.POST.get('amount')
# Generate a new B address
new_b_address = client.create_address(b_account_id)['address']
# Point the address at the user
request.user.user_address.b_address = new_b_address
# Save address to current user
request.user.user_address.save()
# Pass the address to the template
return HttpResponse(new_b_address)
in your js;
$.ajax({
type: 'POST',
url:'/manage/buy/',
data:{
currency:$('selected').val(),
amount:$('#amount').val(),
'csrfmiddlewaretoken': "{{ csrf_token }}"
},
success: function (data){
$('h1').html(data);
}
})
});
in your Django view
import json
from django.http import HttpResponse
def buy_corsair(request):
if request.method == 'POST':
if request.POST.get('wanted') == 'generate_b':
# Get the amount entered
amount = request.POST.get('amount')
# Generate a new B address
new_b_address = client.create_address(b_account_id)['address']
# Point the address at the user
request.user.user_address.b_address = new_b_address
# Save address to current user
request.user.user_address.save()
# Pass the address to the template
context = {'address': new_b_address}
return HttpResponse(json.dumps(context))
in your js
$.ajax({
type: 'POST',
url:'/manage/buy/',
data:{
currency:$('selected').val(),
amount:$('#amount').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success: function (response){
console.log(response);
//access the value and print it in console//
var obj=JSON.parse(response)["address"];
alert(obj);
}
})
});
Related
I have a Django project with a form in an HTML file, and I'd like to update the text on the submit button of that form WITHOUT a page reload. Essentially:
I click submit on the form
Python handles the submit with the form data
The button text is updated to say "show result"
If I understand correctly, I have to use AJAX for this. The problem is that the form submit relies on an API call in Python, so the HTML essentially has to always be "listening" for new data broadcasted by the views.py file.
Here's the code I have (which doesn't work, since when I hit submit I'm greeted by a page with the JSON response data and nothing else):
views.py:
def home(request):
if request.method == "POST":
print("Got form type", request.content_type)
return JsonResponse({"text": "show result"})
return render(request, 'home.html')
home.html:
<div class="content" onload="document.genform.reset()">
<form name="genform" autocomplete="off" class="form" method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="title-sect">
<h1>AJAX Test Form</h1>
</div>
<div class="submit">
<button id="submit" type="submit">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
function queryData() {
$.ajax({
url: "/",
type: "POST",
data: {
name: "text",
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function(data) {
var text = data['text'];
var button = document.getElementById('submit');
button.innerHTML = text;
setTimeout(function(){queryData();}, 1000);
}
});
}
$document.ready(function() {
queryData();
});
</script>
I've imported jQuery with the script <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>. Any idea why this doesn't work in its current state? Thanks!
thanks in advance. I know this has been asked a few times. But after reading the previous questions, reading and understanding JSON and AJAX forms tutorials, I still can't find a way to not having the website refreshed after submitting a form. I would really appreciate it if any of you with a higher knowledge of JavaScript is able to give a hand.
This is a newsletter at the bottom part of the Home page that just asks for a name and an email and it keeps the information in the database, it works perfect and I just would like to reply with a confirmation message without refreshing, because it replies a message but the user has to go to the bottom of the page again to see it which is not practical at all.
The HTML is
<div id="contact_form">
<div class="Newsletter">
<form id="form" enctype="multipart/form-data" method="POST" action="" style="text-align: left;">
{% csrf_token %}
<div class="fields">
<div class="fields">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" minlength="3" placeholder="e.g. John Smith" id="name" required>
</div>
<div class="fields">
<label for="email" id="email_label">Email</label>
<input type="email" name="email" placeholder="e.g. john#example.com" id="email" required>
</div>
</div>
<div class="submit">
<button type='submit' id="submit" >Subscribe</button>
</div>
{% include 'messages.html' %}
</form>
</div>
</div>
The index view
def index(request):
"""View function for home page of site."""
if request.method == 'POST':
form = NewsUserForm(request.POST)
if form.is_valid():
instance = form.save(commit=False) #we do not want to save just yet
if NewsUsers.objects.filter(email=instance.email).exists():
messages.warning(request, 'Your email already exists in the newsletter database')
else:
instance.save()
messages.success(request, 'Great! Your email has been submitted to our database.')
try:
send_mail('Welcome ', 'Thank you for subscribing to the Newsletter. ', 'user123#gmail.com',[instance.email], fail_silently=False)
except BadHeaderError: #add this
return HttpResponse('Invalid header found.') #add this
form = NewsUserForm()
return render(request, 'index.html', {'form':form})
Most of the tutorials suggest to create another view + an url for that view + ajax code
I tried this one from here (https://pytutorial.com/how-to-submit-a-form-with-django-and-ajax#top) without success, also eliminating "post" in html method but still not working, even the info got from the form appears in the url. Any help will be welcome, thank you very much.
jquery unsuccessful code
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
type : "POST",
url: "{% url 'index' %}",
data: {
name : $('name').val(),
email : $('email').val(),
csrfmiddlewaretoken: '{{ csrf_token }}',
dataType: "json",
},
success: function(data){
$('#output').html(data.msg) /* response message */
},
failure: function() {
}
});
});
unsuccessful ajax view function and url
def ajax_posting(request):
if request.is_ajax():
name = request.POST.get('name', None) # getting data from first_name input
email = request.POST.get('email', None) # getting data from last_name input
if name and email: #cheking if first_name and last_name have value
response = {
'msg':'Your form has been submitted successfully' # response message
}
return JsonResponse(response) # return response as JSON
#path('ajax-posting/', views.ajax_posting, name='index'),# ajax-posting / name = that we will use in ajax url
I have comments on a product on the page. and there is a button to add a comment, which puts a new comment into the database. How can I automatically display a new comment on a page?
mytemplate.html
<div id="comments">
{% include 'comments.html' %}
</div>
comments.html
{% for comment in comments %}
<!-- some code for display comments -->
{% endfor %}
script.js
$("#addComment").on("click", function(e){
e.preventDefault()
if ($("#addCommentArea").val() != ""){
data = {
commentText: $("#addCommentArea").val(),
product_id: "{{ product.id }}"
}
$.ajax({
type: "GET",
url: "{% url 'newcomment' %}",
datatype: 'json',
data: data,
success: function(data){
$("#addCommentArea").val("")
}
})
}
})
views.py
class CommentView(View):
def get(self, request):
commentText = request.GET.get("commentText")
if (len(commentText) > 0):
newComment = Comment()
newComment.Author = request.user
product_id = request.GET.get("product_id")
product = Product.objects.get(id=product_id)
newComment.Product = product
newComment.Comment = commentText
newComment.save()
return JsonResponse({'ok': 'ok'})
Currently, you just render the template once and fetch the comments, further you are using Ajax to submit, which means your template doesn't get updated. To update the comments without a page refresh you can either make a javascript polling or use for example web sockets
I'm trying to return data with an ajax request on a form submission. My goal was too use two views, one too handle the template loading and the other to handle the POST request from the form. In the current state, the form is redirecting to the JSON that is in the callback. That makes sense as it's for the form action url is pointing, however, i want to just pass the data to the current page and not reload the page or be redirected to another page.
Here is the code:
user.html
<form action="{% url 'ajax-user-post' %}" method="post">
{% csrf_token %}
{% for user in users %}
<input type="submit" name="name" value="{{ user }}">
{% endfor %}
views.py
def ajax_user(request):
# get some data..
if request.METHOD == 'POST':
user = request.POST['user']
user_data = User.objects.get(user=user)
data = {'user_data': user_data}
return JsonResponse(data)
def user(request):
return render(request, 'user.html', context)
urls.py
url(r'^user/', user, name="user"),
url(r'^ajax/user/', ajax_user, name="ajax-user-post")
.js
$('form').on('submit', function(){
var name = // the name of the user selected
$.ajax({
type: "POST",
dataType: "json",
url: 'ajax/user/',
data: { 'csrfmiddlewaretoken': csrftoken, 'name': name, 'form': $form.serialize() },
success:function(data) {
// hide the current data
console.log(data);
displayUserData(data)
}
})
});
Thanks for the help in advance!
i want to just pass the data to the current page and not reload the page or be redirected to another page.
That means you need to stop the form submission event with the event.preventDefault() call.
Hence, change this line from:
$('form').on('submit', function(){
to to following two:
$('form').on('submit', function(e){
e.preventDefault();
I'd like to create dynamic input system, for example when I enter the folder name - the list of files inside automatically show up another input ChoiceField below, so I can choose the file. The methods are already written, the problem is - How can I make it in Django view?
Here is my view:
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
dir_date = format_date(request.POST['date'])
files = os.listdir(os.path.join(path+dir_date))
return render(request, 'inform/show_name.html', {'data': request.POST['your_name'],
'date': format_date(request.POST['date'])})
else:
form = NameForm()
return render(request, 'inform/base.html', {'form': form})
Here is the form class:
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
date = forms.DateField(widget=forms.DateInput(attrs={'class': 'datepicker'}))
flights = forms.ChoiceField(choices=?)
Finally, here is my template.
{% extends 'inform/header.html' %}
{% block content %}
<script>
$( function() {
$( ".datepicker" ).datepicker();
$( "#anim" ).on( "change", function() {
$( "#datepicker" ).datepicker( "option", "showAnim", $( this ).val() );
});
} );
</script>
<div class="container" style="color: red; size: auto;">
<form class="form-vertical" action="get_name" role="form" method="post">
{% csrf_token %}
<div class="form-group" style="display: inherit">
<center>
{{form}}
<input type="submit" value="OK">
</center>
</div>
</form>
</div>
{% endblock %}
Is there any way to dynamically read the data from the Date input and give it to the method inside the view without clicking the submit button or creating several others? If it can be solved only by ajax, jQuery or JS, could you please give me a simple sample of how it's done? I'm pretty much frustrated by the inability of creating a simple form.
Thank you in advance!
So basically you are doing it right. You already know that you need the on(change) function for the datepicker
Now as soon as the user changes a date, your on(change) function is triggered. So all you need to do now is to the get the new date value, which you already have when you do $( this ).val(). After that make an ajax call to the url corresponding to your method get_name in views.py
Something like this:
$( function() {
$( ".datepicker" ).datepicker();
$( "#anim" ).on( "change", function() {
$( "#datepicker" ).datepicker( "option", "showAnim", $( this ).val() );
send_changed_date_value(variable_with_new_date);
});
});
function send_changed_date_value(new_date) {
$.ajax({
type: // "POST" or "GET", whichever you are using
url: "/url in urls.py corresponding to get_name method in views.py/",
data: new_date,
success: function(response){
console.log("Success..!!")
}
});
}
This is how you can send the new date value to your views, everytime it is changed. If you want to submit the complete form data, i.e., your_name and flights data as well, then you may directly send serialzed data of the form in the data attribute of ajax.
Note -> You will have to return a HttpResponse from your get_name view as an ajax call requires a HttpResponse from the backend to complete the ajax call successfully. You may simply return a string in the response.