This question is not new, however I've spent really plenty of time, but coudn't fixed it.
<form id="test_data_form" action={% url 'insert_test_data' %} method="post">{% csrf_token %}
<input type="submit" value="Insert test data">
<div id="message"></div>
</form>
<script type="text/javascript">
var form = $("test_data_form");
$(document).ready(function() {
form.submit(function() {
$.ajax({
data: form.serialize(),
url: form.attr('action'),
cache: false,
type: form.attr('method'),
dataType:'json',
success: function(response) {
alert("1");
},
error: function() {
alert('Error!');
}
}
);
return false;
}
);
}
);
</script>
views.py
#csrf_exempt
def insert_test_data(request):
print request.is_ajax()
data = {'success': True, 'html': "text"}
return HttpResponse(json.dumps(data), mimetype="application/json")
urls.py
url(r'^hello/insert_test_data/$', insert_test_data, name="insert_test_data"),
Firstly, I've found that success isn't caught, so then while debugging I found that django doesn't think it is an ajax request and redirects me to the different page: /insert_test_data. And I want to stay on the home page.
I've found a lot of advices about that problem (e.g. cache: false) but none of them helped. I agree, that I miss something obvious, but couldn't figure out what exactly.
I'll be realy glad for any help.
The JavaScript to handle the form submit looks ok at first inspection, but there's one mistake:
var form = $("test_data_form");
If you use Firebug or Chrome developer tools and query for this element in the console, you won't get anything back because you're missing a selector (tag, id, class, etc). From your form tag, I think you meant to select by id:
var form = $("#test_data_form");
Related
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");
}
});
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>
I've been going through the django documentation, but so far everything I've tried hasn't worked for me. I'm trying to make it so if the user enters the url to a certain page and they are not already logged in then they are redirected to the login page that gives them a popup error message that says they don't have access to the page until they have logged in.
Here is a small snippet of code from the views.py
def home(request):
if request.session.test_cookie_worked():
return render(request, 'page/home.html')
else:
return render(request, 'page/login.html')
Everything works except for the error message not popping up if they are redirected to the login page. I've looked at other stack overflow questions that people have asked that are similar to this, but those don't seem to work for me either. Any advice?
Here's how I'm doing it.
First, if the view code determines that the popup should be displayed, call render() with a named flag in the context:
return render(request, 'page/home.html', {'some_flag': True})
Then, in your page template, if the flag is set, display a <div> element:
{% if some_flag %}
<div id="some_flag" title="Some Flag">
<p>Some Text Here</p>
</div>
{% endif %}
Also in the page template, in the <head> section, create a JavaScript function to display the <div> as a popup dialog:
<head>
<script type="text/javascript">
$(document).ready(function() {
$(function() {
$( "#some_flag" ).dialog({
modal: true,
closeOnEscape: false,
dialogClass: "no-close",
resizable: false,
draggable: false,
width: 600,
buttons: [
{
text: "OK",
click: function() {
$( this ).dialog( "close" );
}
}
]
});
});
});
</script>
</head>
This solution also requires that you use the jQuery library.
I'm sure there are drawbacks to doing it this way, but it works for me.
We can pass a variable in context object like a flag.
return render(request, 'index.html', {'alert_flag': True})
and then in templates simply do a check for the alert_flag.
{% if alert_flag %}
<script>alert("Some Message.")</script>
{% endif %}
Here no jQuery code is required and I am using native alert.
I have a Ajax and template like this:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
url = '/home'
ajaxRequest.open("GET", url, false);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
{% csrf_token %}
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' id='time' value="" />
</form>
</body>
</html>
And I have simple views like this:
from django.shortcuts import render_to_response, HttpResponse
import simplejson
from django.template.context import RequestContext
import datetime
def home(request):
if request.GET:
a = datetime
return HttpResponse(simplejson.dumps(a), mimetype='application/json')
#return render_to_response('home.html', {'a':a}, context_instance=RequestContext(request))
else:
return render_to_response('home.html', context_instance=RequestContext(request))
Ajax is loading when I press enter but instead of the particular variable all the template is loading in the input box. What's wrong?
This line:
if request.GET:
checks to see if there are any GET parameters. There aren't, because you're not sending any. The URL is just /home. You could use if request.method == 'GET', but I think you're checking for the wrong thing here: a normal request (not Ajax) will also be GET.
What you should do is send the HTTP_X_REQUESTED_WITH header as "XmlHttpRequest", then check request.is_ajax() in the view. Or, as recommended, use a library like jQuery - which sets that for you automatically.
The proper way to detect request type is if request.method == 'GET', instead of if request.GET.
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;
});
});