I'm sort of new with Django and I ran through an issue. I'm sending a post request to django view and return the function back with HttpResponse in order to change my template's div contents to the passed value from my view. The issue is: once ajax responds and changes it's div's value; the page instantly reloads. Do you guys have any idea why?
Views.py
def index(request):
if request.is_ajax():
print("request is ajax")
details = request.POST.get('id')
return HttpResponse(details)
else:
return HttpResponse("Failed)
base.html
<button id="checkres">Check result</button>
<form name="testform" id="testform" method="post">
{% csrf_token %}
<input type="text" id="rowfield">
<input type="submit">
</form>
$("#testform").submit(function (event){
$row_num = $('#rowfield').val()
$("#responseresult").text('checking');
$.ajax({
type: "POST",
url: "/bot",
data: {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id: $row_num},
success: function(data){
$("#responseresult").text(data);
alert(data);
}
});
});
Your javascript submit event not calling event.preventDefault(), that's the reason that after ajax response, the is refreshing. Change your javascript function to:
$("#testform").submit(function (event){
$row_num = $('#rowfield').val()
$("#responseresult").text('checking');
$.ajax({
type: "POST",
url: "/bot",
data: {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id: $row_num},
success: function(data){
$("#responseresult").text(data);
alert(data);
}
});
event.preventDefault(); // prevents the page from refreshing.
});
Further read about preventDefault()
Try this for your view
def index(request):
if request.is_ajax():
print("request is ajax")
details = request.POST.get('id')
return JsonResponse(details, safe=False)
else:
return JsonResponse("Failed" safe=False)
You need to prevent submit as well.
$("#testform").submit(function (event){
$row_num = $('#rowfield').val()
$("#responseresult").text('checking');
$.ajax({
type: "POST",
url: "/bot",
data: {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id: $row_num},
success: function(data){
$("#responseresult").text(data);
alert(data);
}
});
event.preventDefault(); // prevents the page from refreshing.
});
Related
I try to send images from <input type="file" id="file" name="file" accept="image/*" multiple> without sending al the form. I found many post which explain this so I do this
urls.py
url(r'^images/', 'app.views.images', name='images'),
view.py
def images(request):
if request.method == 'POST':
print('hello')
jquery
$("#file").change(function (){
try{
var formdata = new FormData();
var files = $('#file')[0].files;
formdata.append('file',files);
jQuery.ajax({
url: "images/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
// if all is well
// play the audio file
}
});
}
catch(err){
alert(err.message);
}
});
But this gives me "POST /images/ HTTP/1.1" 403 error
I did diferent test and I think the error is the data: formdata part
You need to either send the csrf_token in the ajax request.
formdata["csrfmiddlewaretoken"] = '{{ csrf_token }}'; //add csrf token to the reauest data
jQuery.ajax({
url: "images/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
// if all is well
// play the audio file
}
});
Or use #csrf_exempt on the your view.
#views.py
#csrf_exempt
def images(request):
if request.method == 'POST':
print('hello')
I'm sending form data via an ajax call after user hits submit button and then handling this request in my views, but the form is empty. How can I populate the form?
This is my code:
My JS file:
var csrftoken = getCookie('csrftoken'); //getCookie is a csrf_token generator
var form = $(this).closest('form')
$.ajax({
url: form.attr("action"),
data: { // if I change this line to data: form.serialize(), it works fine!
csrfmiddlewaretoken : csrftoken,
form: form.serialize(),
},
type: form.attr("method"),
dataType: 'json',
success: function (data)
{
//Do a bunch of stuff here
}
})
My views:
def task_edit(request, pk):
task = get_object_or_404(Task, pk=pk)
if request.method == 'POST':
task_form = NewTaskForm(request.POST) # This is empty!
else:
task_form = NewTaskForm(instance=task) # This for populating the edit modal, works fine!
I'm not doing the data: form.serialize() because I need to send additional data with the ajax request. How do I get this working?
You can write as below:-
$form_data = $("#idofform").serialize();
And then in ajax
data : $form_data+'&key=value',
You can use services like https://www.formkeep.com to capture form data using AJAX.
This may be a good idea if you are already using a JavaScript framework, you want to add validation logic, or you don't want to redirect the user after they submit the form.
You can submit to FormKeep using a standard AJAX request. To ensure the request does not cause a redirect, be sure to set the Accept header to application/javascript.
Given the following form:
<form id="newsletter-signup" action="http://formkeep.com/f/exampletoken" method="POST" accept-charset="UTF-8">
<input type="hidden" name="utf8" value="✓">
<input name="email" type="email">
<input value="Submit" type="submit">
</form>
Here's an example of how to submit a form with jQuery:
$(function() {
$('#newsletter-signup').submit(function(event) {
event.preventDefault();
var formEl = $(this);
var submitButton = $('input[type=submit]', formEl);
$.ajax({
type: 'POST',
url: formEl.prop('action'),
accept: {
javascript: 'application/javascript'
},
data: formEl.serialize(),
beforeSend: function() {
submitButton.prop('disabled', 'disabled');
}
}).done(function(data) {
submitButton.prop('disabled', false);
});
});
});
That's it. Once your data is securely captured in FormKeep you can easily store it, manage it or connect it with 1000s of other systems like Google Docs and Hubspot and Mailchimp.
I want to make a post request by using ajax. I want to use the input value as function parameter and append the function return into a html table. I don't know but a think that my code is wrong and the ajax is not working.
Note: For testing, I'm taking input value and returning to html page.
network.html
<script type="text/javascript">
$(function(){
$('#button').click(function(){
var dados = $('#search-input').val();
$.ajax({
url: '/network',
data: $('form').serialize(),
type: 'POST',
success: function(data){
$('#result').append(data)
console.log(data);
},
error: function(error){
console.log(error);
}
});
});
});
</script>
<form name='form' method="POST">
<input type="text" name="search-input" id="search-input" class="form-control" placeholder="Users and ID" >
<button type="submit" class="btn btn-primary" id="button">Search</button>
</form>
<span id=result>{% print dado %}</span>
app.py
#app.route('/network',methods=['POST','GET'])
def network():
if request.method == 'POST':
input = request.form['search-input']
return render_template('network.html',dado=input)
else:
return render_template('network.html',dado='')
Edit: After this update what's returning is a JSON format
{
"dado": "INPUT VALUE"
}
app.py
#app.route('/network',methods=['POST','GET'])
def network():
if request.method == 'POST':
input = request.form['search-input']
return jsonify(dado=input)
else:
return render_template('network.html',dado='')
network.html
<script type="text/javascript">
$(function(){
$('#botao').click(function(){
var dados = $('#search-input').val();
$.ajax({
url: "{{ url_for('network') }}",
data: JSON.stringify(dados),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(data){
$('#result').append(data["dado"])
console.log(data);
},
error: function(error){
console.log(error);
}
});
});
});
</script>
You got to return JSON!
Instead of return render_template(...), use:
return jsonify(dado = input)
Then in your ajax success call:
success: function(data){
$('#result').append(data["dado"])
console.log(data);
}
...
}); // end AJAX
e.preventDefault();
Don't forget to import jsonify
from flask import jsonify
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'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.
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');