I'm try to send data to a django view through ajax with POST method as I saw in one tutorial.
The code I've made is the following (myURL is the URL where I call testview):
$(document).on('submit','#form',function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/myURL/',
data:{
HELLO: "I'm inside ajax data"
},
contentType: "application/json",
datatype: 'json',
sucess:function(){
alert("Ajax pass data correctly");
}
})
});
</script>
And in django I'd call HELLO as following. test.html is where I have the html form
if request.method == 'POST':
takeHELLOfromajaxpost = request.POST['HELLO']
return render(request,'test.html',{'dataTakenfromAjax':takeHELLOfromajaxpost})
return render(request,'test.html',{})
Then I would template tagging in the same HTML {{ dataTakenfromAjax }} to verify if I'm taking that data , but nothing happens! I even get no error.
First of all, you are not sending csrfmiddlewaretoken with your request.
Second, you have typo in success argument.
Third, you probably expecting it to completely change html? Than you should add $("body").html() at successful response. That way your variable appear on page.
test.html:
{{ dataTakenfromAjax }}
<form action="" id="form">
{% csrf_token %}
<button type="submit">Submit</button>
</form>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script>
$(document).on('submit', '#form', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/myURL/',
data: {
csrfmiddlewaretoken: $("[name=csrfmiddlewaretoken]").val(),
HELLO: "I'm inside ajax data"
},
success: function (data) {
$("body").html(data);
}
})
});
</script>
Related
I am trying to send data from a form to Python Flask using ajax. I do not want the page to reload. When I try to send the form I get the error
POST http://127.0.0.1:5000/addTran 400 (BAD REQUEST)
I just want to input a Russian word with an English translation and then to write it to a file from flask.
Here is my html and JavaScript
<form id="translationForm">
<label for="russianWord">Russian Word:</label><br>
<input type="text" id="russianWord" serialize-as="russianWord" name="russianWord"><br>
<label for="englishWord">English word:</label><br>
<input type="text" id="englishWord" serialize-as="englishWord" name="englishWord">
<input type="submit" value="Submit">
</form>
<script>
$(function () {
$('#translationForm').on('submit',function (e) {
$.ajax({
type: 'POST',
url: "{{url_for('addTran')}}",
data: $('#translationForm').serialize(),
contentType: "application/j-son;charset=UTF-8",
dataType: "json",
success: function () {
alert("It worked!");
}
});
e.preventDefault();
});
});
Here is my Python route
#app.route('/addTran',methods=["POST"])
def addTran():
if request.method == "POST":
tran = request.get_json(force=True)
with open('/home/matt/Desktop/info.txt','w') as w:
w.write(str(tran))
Adding JSON.stringify() worked!
data: JSON.stringify($('#translationForm').serialize())
Maybe it's the typo in the request content type?
contentType: "application/j-son;charset=UTF-8",
To
contentType: "application/json",
Suppose, I have a simple HTML checkbox.
When the HTML page is loaded through flask initially, this checkbox displays boolean values from a postgres database. It cannot be included in an HTML form, nor I can use submit button.
Now, if I tick/untick this checkbox, I want to send the value associated with this checkbox to flask and ultimately to db.
Can I do it with ninja or do I need ajax call for it?? I tried with ajax, but :(
I am a newbie to ajax,json,flask.
I tried searching other questions, but most of them I found were with HTML form or with php.
Sorry for my lack of knowledge, if I miss something.
<input type="checkbox" id="statustick" name="statustick" value="{{ testvariable }}" {% if testvariable==True %}checked{% endif %}>
<script>
$("#statustick").change( function(){
if( $(this).is(':checked') ) {
$.ajax({
type: "POST",
url: "{{ url_for('logging') }}",
contentType: "application/json",
data: JSON.stringify("#check".val()),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});
}else{
alert("unchecked");
}
});
In a chat-like app, I'm using ajax calls to POST a new message and update the messages displayed on the page without reloading the entire page. My ajax call for posting works - a new message instance is created in the database. However, afterwards when I make an ajax call to GET all messages, the new message is missing from the resulting query set. If I refresh the page fully, I can see all the messages, but that's not what I'm after.
HTML messages template:
{% for message in messages %}
<p>
{{ message.content }}
</p>
{% endfor %}
HTML chat template:
<div id="chat">
{% include "messages.html" %}
</div>
<form id="post-message-form", method="post" enctype="multipart/form-data">
[my form goes here]
</form>
JavaScript:
$('#post-message-form').on('submit', function(event){
event.preventDefault();
$form = $(this);
var data = new FormData($form.get(0));
$.ajax({
url: '/post/a/new/message/',
type: 'POST',
data: data,
success: refresh_chat,
cache: false,
contentType: false,
processData: false
})
return false;
}
function refresh_chat(){
$.ajax({
url: '/get/all/messages/,
type: 'GET',
success: function(json) {
$('#chat').html(json['data']);
}
})
return false;
}
Views:
import json
from django.template import loader
from .forms import MessageForm
# /post/a/new/message/
def post_message(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
message = form.save()
return HttpResponse(
json.dumps({'status': 1,
'message': 'Message posted!'}),
content_type='application/json'
)
# /get/all/messages/
def get_messages(request):
if request.method == 'GET':
messages = loader.render_to_string('messages.html', context={'messages': Message.objects.all(), 'form': MessageForm()})
return HttpResponse(
json.dumps({'data': messages}),
content_type='application/json'
)
Any ideas why I do not get the latest database data when I call an ajax GET after POST? Thanks!
Turns out if I do my chat refresh on the ajax "done" call instead of on "success" it works:
$('#post-message-form').on('submit', function(event){
event.preventDefault();
$form = $(this);
var data = new FormData($form.get(0));
$.ajax({
url: '/post/a/new/message/',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false
}).done(function() {
refresh_chat();
});
return false;
}
Thanks for commenting!
I have given {% csrf_token %} inside the form.
Do I have to give another {% csrf_token %} inside the AJAX $.ajax({ .......... )} ?
<form method="post" data-validate-username-url="{% url 'validate_username' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign up</button>
</form>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$("#id_username").change(function () {
console.log($(this).val());
var form = $(this).closest("form");
$.ajax({
url: form.attr("data-validate-username-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert(data.error_message);
}
}
});
});
</script>
See below for how I changed your code. The csrf_token is assigned to a variable with Django templating. You can produce this variable in any of your Javascript code.
The token is then included in the header
<script>
var token = '{{csrf_token}}';
$("#id_username").change(function () {
console.log($(this).val());
var form = $(this).closest("form");
$.ajax({
headers: { "X-CSRFToken": token },
url: form.attr("data-validate-username-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert(data.error_message);
}
}
});
});
</script>
The documentation very well explained how to use AJAX
https://docs.djangoproject.com/en/2.1/ref/csrf/
Get this library https://github.com/js-cookie/js-cookie/
Add this var csrftoken = Cookies.get('csrftoken');
The last step is configure ajax setup
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Update to the steps above - as the Django documentation indicates you can use the Javascript Cookie library to do a Cookies.get('csrftoken'). Also, I had to add {% csrf_token %} before the function call. Might be obvious, but I didn't know so providing it here to help others
I have a form which is loaded via jQuery from the external template file:
$('#imguploadform').html(' ').load('{% url upload_form %}');
In template it looks like this:
<img src="{{ MEDIA_URL }}img/misc/upload.png" alt="Illustration" title="myimage" />
<form id="uploadForm" enctype="multipart/form-data" method="post" action="upload_picture/">
{{ form.as_ul }}
<input type="submit" value="Upload" id="uploadImage" />
</form>
I'm trying to upload an image with ajax using jquery form plugin:
var submit_options = {
target: '#picworks',
dataType: 'json',
success: function() {
alert('It Works!');
}
};
$('#uploadForm').submit(function(){
$(this).ajaxSubmit(submit_options);
return false;
});
But then I want to return a json object from server and dynamically load into page an image using it's returned address. I've tried like this:
def upload_picture(request):
dest = save_original(request.FILES['image'])
form = UploadImageForm(request.POST, request.FILES)
res = json.dumps({
"path": dest,
})
return HttpResponse(res, mimetype='application/json')
The problem is that I can't catch a json response in javascript, so my browser shows me just an empty page with json dictionary content. What I'm doing wrong?
Have your success callback take a parameter. That will be the response.
var submit_options = {
target: '#picworks',
dataType: 'json',
success: function(response) {
alert('It Works!');
window.location.href = response.path;
}
};
I solved the problem! The thing is that function which replace form submitting action with an ajax request is called earlier than the form loads from external file. So it should be like this:
$('#imguploadform').html(' ').load('{% url upload_form %}',
function(){
var submit_options = {
dataType: 'json',
success: update_dom
};
function update_dom(data) {
$('#picworks').html('<img src="' + data.path + '" alt="Illustration" />');
}
$('#uploadForm').submit(function(){
$(this).ajaxSubmit(submit_options);
return false;
});
});