I am working on passing data from ajax to a Django view. However, ajax somehow is making 2 GET requests: one with the query string and the other without it. In the view when I try to get the query string its empty.
Ajax code:
<script>
$( document ).ready(function() {
var query = "{{ item.ipv4_address }}";
$("#clickid").click(function() {
$.ajax({
url: "/reserve/run/?ip=",
type: "GET",
data: {ip:query},
success:function(data){
console.log(data);
}
});
});
});
</script>
Django view:
def run_script(request):
if request.GET:
ip = request.GET['ip']
print ip
return render_to_response('test.html',{'item':ip})
Two urls:
[16/Dec/2017 07:43:56] "GET /reserve/run/?ip=198.18.101.123 HTTP/1.1" 200 570
[16/Dec/2017 07:03:58] "GET /reserve/run/ HTTP/1.1" 200 1
urls.py file
url(r'^run/$',views.run_script,name='run_script'),
Please let me know where I am going wrong. Also, let me know if you need any more info. Any pointers is appreciated.
If you are passing query parameter in your data attribute you need not to send it in url parameter.Update your url parameter as:
$.ajax({
url: "/reserve/run/",
type: "GET",
data: {ip:query},
success:function(data){
console.log(data);
}
});
I found the error. In my tag, I had mentioned the URL too. {% url 'run_script' %}. This was sending that extra GET request. Once I removed it, the issue resolved.
Related
jQuery("#myform").submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
jQuery.ajax({
type:'POST',
url:'{% url 'editJobDesc' %}',
data: formData,
cache:false,
contentType: false,
processData: false,
success: function (data) {
alert("Done");
}
});
});
The code works perfectly fine in localhost but shows 404 url not found when hosted on server.
In django views.py:
profile = request.POST.get('profile')
jd = request.FILES.get('jd')
Django urls.py:
path('editJobDesc', views.editJobDesc, name="editJobDesc"),
I found out that error is due to the file I am trying to upload using ajax. If I try to upload other inputs it works fine.
I even tried appending file with formData but still I get the same error.
I have a JQuery event that, when a link is clicked, an AJAX POST request is sent to a Django function. There I print the recieved url and do other stuff with it. However, when it is printed (by Django) some characters in the url are changed.
The specific url this happened with was :
https://www.catholicleague.org/05press_releases/quarter%204/051110_put_on_notice.htm
Which was printed as :
https://www.catholicleague.org/05press_releases/quarter+4/051110_put_on_notice.htm
Where %20 was changed to +
Here is the AJAX and Django code:
$("a").on("click", function(e){
e.preventDefault();
if(e.target.href){
let clicked_source = e.target.href;
let csrf_tok = parent.document.getElementById("csrf_tok").value;
$.ajax({
url: "/change_origin/",
data: JSON.stringify({"clicked_source":clicked_source}),
type: "POST",
beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrf_tok );},
success: function(response) {
console.log(response.msg)
},
error:function(error) { console.log(error); }
});
}
});
def change_origin(request):
if request.method == 'POST':
received = ast.literal_eval(request.body.decode())
print(received)
clicked_source_url = received['clicked_source']
return JsonResponse({'msg': "ok"})
Where decode is used as the JSON object is received in Python as a byte-like object. And ast is used to turn the string representation of the object to an actual object (or dict) for access.
I need either:
1) A way to just send a string from Ajax to Django
2) A better way to deal with the received object as I believe using .decode() might be the one causing this issue.
EDIT: The link is the second link in the "origin" part of this article
https://www.snopes.com/fact-check/an-unmerried-woman/
I have middleware, that stores all http requests into DB.
Also I have view, that fetches data from DB and put this data into the context.
views.py
def requests(request):
http_requests = WebRequest.objects.all()
context = {
"http_requests": http_requests
}
return render(request, "requests.html", context)
How can I asynchronously update data on this page as new requests come in (so, new requests should appear on this page asynchronously)? Can I use only Django features to achieve such behavior or I need to use some javascript libraries?
It depends on how much time you want to spend on the project. As Lorenzo stated, it might make sense to create an API and have javascript-frameworks (e.g. emberjs or angularjs) handle the asynchronity. I dont think you can handle this with pure django...
If you don't have time and are in for some 'hack' you could just replace the content of your page by polling the url and replacing the whole document with the response:
$.ajax({
type: "GET",
url: "<url_to_your_requests_view>",
success: function(response){
$('body').html(response);
}
});
This is NOT clean, but should work as a quick an dirty trick...
EDIT: If you only want to exchange certain parts of your site, you can break it down to just add elements to the page:
$.ajax({
type: "GET",
url: "<url_to_your_requests_view>",
success: function(response){
var newlyAddedRows = // find your newly added rows through some jquery
newlyAddedRows.forEach(function(row){
$('#request-holder').append(row);
});
}
});
OR WITH JSON
$.ajax({
type: "GET",
url: "<url_to_your_requests_api_endpoint>",
success: function(response){
var requestRows = response.requestItems
var $requestsHolder = $('#request-holder');
$requestHolder.empty();
requestRows.forEach(function(row){
requestsHolder.append('<div class="request-row">' + <visualize your data somehow> + '</div>'); //e.g. row.timestamp if you have that in your json
});
}
});
I am trying to do a JSON post to my Bottle server.
from bottle import request, route, run
#route('/feedback', method='POST')
def feedback():
data = request.json
print data
run(host='localhost',port=8080)
In the client side, I have
$('#user_feedback').submit(function() {
var feedback = {"id": 1}
$.ajax({
type: "POST",
url: "http://localhost:8080/feedback",
data: feedback
});
return false;
});
I am returning false here because I don't want the page to be redirected.
However, the data I received in my Bottle server is always None when printed out.
Please help. Thank you.
request.json expects the content type of the request to be application/json .
So to make it work, you should set the contentType property of your request to application/json and stringify your data :
$.ajax({
type:"POST",
contentType: "application/json",
url:"/feedback",
data: JSON.stringify(feedback)
});
I want to send an email from python using the below codes i wrote/reffered
<script>
$(document).ready(function() {
$("#form1").submit(function(){
$("#form1").validationEngine();
if($('div input[type=text]').val() != "")
{
var textfield2=document.getElementById("textfield2").value;
var textarea=document.getElementById("textarea").value;
var dataS=$("#form1").serialize();
$.ajax({
type: "POST",
crossDomain: 'true',
url: "mail.py",
success: function( ){
alert("completed");
},
error: function(){
alert(dataS);
}
});
}
return false;
});
});
</script>
For the mail part , i reffered the below google code
from google.appengine.api import mail
mail.send_mail(sender="Example.com Support <support#example.com>",
to="Albert Johnson <Albert.Johnson#example.com>",
subject="Your account has been approved",
body="""
Dear Albert:
Your example.com account has been approved. You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.
Please let us know if you have any questions.
The example.com Team
""")
Now the question is , on ajax call .. How can i recieve the HTML parameters in the mail.py script? pls help i'm new to python
Within a cgi script, if you instantiate a cgi.FieldStorage(), it is automatically filled with the GET or POST parameters. If you want to post content, then just add a data property to your ajax request object:
$.ajax({
...
data: {param1: 'value1', param1: 'value2', ...}
...
})
In your python script it should the be enough to do:
import cgi
store = cgi.FieldStorage()
par1 = store.getfirst('param1')
...
One more thing -
Ask yourself: do you really want to submit the form when the page is loaded? (Your're using the 'ready' event). Wouldn't it be better to wait until somebody has entered somehting in the form?