AJAX Post request not sending values to Django View - javascript

I am trying to pass some data from the frontend to the backend of my site using AJAX. This is the post request view in my django views:
def post(self, request):
id_ = request.GET.get('teacherID', None)
print(id_)
args = {}
return JsonResponse(args)
This is the function I have in javascript. I know the correct value is being passed because the console.log(teacher_id) prints the right value.
function send(teacher_id){
console.log(teacher_id)
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'teacherID': teacher_id,
},
dataType: 'json',
success: function (data) {
//location.href = data.url;//<--Redirect on success
}
});
}
When the code is run, and the print statement in my view is run, regardless of what the teacher_id is, None is printed.
what is wrong with the code?

In your Django view the data is being retrieved using GET.get() while the AJAX request is sending it using method: "POST".
POST data can't be retrieved in the same way as GET data so you should either change the way the data is being send (by changing the method in the AJAX call to GET) or read it using the related POST methods.
You can visit this Stack Overflow question if you are doubting which method to use.

Related

Submitting a JS array via AJAX to Django view returns TypeError

I have an array of objects that needs to be submitted to Django view.
I stringify it and checked result in console log. Up to this point it works. However, when I try to retrieve it in my view I get some errors.
I tried to edit my code similarly to what I've found on the topic, unfortunately nothing helped.
I tried ast.literal_eval instead of json.loads, passing 'items[]' and collecting data via request.POST.getlist as well as solution with request.body and request.is_ajax(). Yet, neither allowed me to retrieve the data.
var items = [];
var formInput = $('#inputbox').val();
items.push({'item': formInput , 'metrics': metrics.toString()});
$('#id_search').click(function( event ) {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '{% url "list_of_items" %}',
data: {'items': JSON.stringify(items),},
success: function (response) {
console.log(data);
}
});
event.preventDefault();
});
and in views.py:
def list_of_items(request):
data = request.POST.get('items')
data_received = json.loads(data)
#another approach:
response_json = request.body
struct = {}
try:
response_json = response_json.decode('utf-8').replace('\0', '')
struct = json.loads(response_json)
except:
print('bad json: ', response_json)
#(...)
I looks like an empty object is passed.
TypeError at /list_of_items
the JSON object must be str, not 'NoneType'
This view receives another POST request from the JS form within same template (list_of_items.html) and I wonder if it's interfering with my ajax POST.
You are not sending the data correctly. From the docs:
A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data.
You need to send the data as key:value pair or you need to decode the request.body as
data = request.body.decode('utf-8')
data_received = json.loads(data)
This is the correct way to send ajax request.
$.ajax({
type: 'POST',
url: '{% url "list_of_items" %}',
data: {'items': JSON.stringify(items),},
success: function (response) {
console.log(data);
}
});
I also think that you have bound the submit event and click event incorrectly. Also you are sending ajax request on submit event without preventDefault

Passing a variable to URL parameters using JQuery POST

I have a function which currently passes an account code (derived from a combo box) to the server. Currently it does this by sending the request in the body - I need it to send as a URL parameter. So for example the URL should be:
localhost:1234/myProject/WebApp/Data?accountCode=Full
Assuming full is selected.
My code below works as a request body but my attempts to amend it to submit as a URL request have failed.
accountSelected: function () {
var saccountCode = $("select#accountcombo").val();
var stringAccountCode = saccountCode.toString()
console.log("Account is: " + stringAccountCode);
var myURL = "WebApp/Data";
$.ajax({
url: myURL,
type: "POST",
data: {
"accountCode": stringAccountCode
},
dataType: "text",
})
I have been looking at using $.param but couldn't get anything to work and also read on other questions about using $.get but when I change my code above to a "GET" i get an error
"Request method 'GET' not supported" - the server is expecting a POST request. Any way i could achieve this?
Thanks
Try,
URL: "localhost:1234/myProject/WebApp/Data?accountCode="+stringAccountCode
Appending number of parameters you want example
?accountCode="+stringAccountCode+"&aa="+someAccount

How to use javascript to send a request to call web.py behind code?

I have a button in my form.When user click it.It should send a request to the server to get a validate code.I am not sure how to realise it without refresh the page.Wait for your help,guys.Many thanks.
If you don't want to refresh the page, you should use Ajax as a request. Example using JQuery:
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
Taken from this answer https://stackoverflow.com/a/13175665/2854344
Adding on to Joao's answer, after making the AJAX request using jQuery, you can access it like using the POST function:
class FrontPage:
def GET:
### Add some GET code here
def POST:
k = web.input()
user_input = k['param']
### Do something with user_input and sends back using AJAX

AJAX Post to store JSON with Python and javascript

I have been having problems with getting AJAX to post JSON correctly. The application is intended to be hosted on Google App Engine. But what I have does not post data.
Python
mainPage = """
<html>
html is included in my python file.
</html>
"""
class JSONInterface(webapp2.RequestHandler):
def post(self):
name =self.request.get('name')
nickname =self.request.get('nickname')
callback = self.request.get('callback')
if len(name) > 0 and len(nickname) >0:
newmsg = Entry(name=name, nickname=nickname)
newmsg.put()
if len(name)>0:
self.response.out.write(getJSONMessages(callback))
else:
self.response.out.write("something didnt work")
def get(self):
callback = self.request.get('callback')
self.response.out.write(getJSONMessages(callback))
This handler is meant to handle the Ajax calls from the web app. I am unsure if I need javascript to be associated with my main page in order to do so, as I haven't found information on it yet with my searches.
Javascript
$(document).ready( function() {
$("#post").bind('click', function(event){
var name = $("#name").val();
var nickname = $("#nickname").val();
postData = {name: name, nickname: nickname, callback: "newMessage"};
$.ajax({
type: "POST",
url: "http://localhost:27080/json",
data: postData,
dataType: "json",
done: function() {
// Clear out the posted message...
$("#nickname").val('');
},
fail: function(e) {
confirm("Error", e.message);
}
});
// prevent default posting of form (since we're making an Ajax call)...
event.preventDefault();
});
The Javascript for the post
Can someone advise me on how I could resolve the problem I am having. Thanks for the time and help.
Did you ask the same question yesterday and then delete it? I swear I just answered the same question.
You're not sending your data as a JSON string. If you want to send as JSON, you need to encode data as a JSON string, or else you're just sending it as a query string.
data: JSON.stringify(postdata),
HOWERVER, your request handler is actually processing the request properly as query string instead of JSON, so you probably don't want to do that.
For starters, the ajax call is pretty close. The full path
"http:://localhost:27080/json"
is not necessary, the relative path will work, but that is not the problem.
Your callback, as it stands, will work as 'success':
success: function(response) {
alert(response);
// Clear out the posted message...
$("#nickname").val('');
}
However, this callback is being phased out in favor of other methods. 'Done' should be chained like so:
$.ajax({
type: "POST",
url: "/json",
data: postData,
dataType: "json"
}).done(function(data){
console.log(data);
});
Also, there might be problems on the server. If you use some logging, you will see that the data is indeed being sent to the server.
import json ## we'll get to this below
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
name = self.request.get('name')
logging.info(name) ## will print the value of 'name'
Unless your python function getJSONMessages(callback) is returning a json object, your callback will not be called, even after you add the response parameter.
In your python code:
import json
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
callback = self.request.get('callback')
logging.info(callback) # will print correctly
self.response.out.write(json.dumps(callback))
Using the json.dumps method encodes the passing object to json, which is what your ajax object is looking for.

ASP.NET MVC submitting json array to controller as regular post request (nonajax)

All the examples of json I can find online only show how to submit json arrays w/ the jquery command $.ajax(). I'm submitting some data from a custom user control as a json array. I was wondering if it's possible to submit a json array as a regular post request to the server (like a normal form) so the browser renders the page returned.
Controller:
[JsonFilter(Param = "record", JsonDataType = typeof(TitleViewModel))]
public ActionResult SaveTitle(TitleViewModel record)
{
// save the title.
return RedirectToAction("Index", new { titleId = tid });
}
Javascript:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
});
}
Which is called from a save button. Everything works fine but the browser stays on the page after submitting. I was thinking of returning some kind of custom xml from the server and do javascript redirect but it seems like a very hacky way of doing things. Any help would be greatly appreciated.
This is an old question but this might be useful for anyone finding it --
You could return a JsonResult with your new titleId from the web page
public ActionResult SaveTitle(TitleViewModel record) {
string tId = //save the title
return Json(tId)
}
and then on your ajax request add a success function:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
success: function(data) { window.location = "/Listing/Index?titleId=" + data; }
});
}
That would redirect the page after a successful ajax request.
I just saw that you mentioned this at the end of your post but I think it is an easy and quick way of getting around the issue.
Phil Haack has a nice post discussing this scenario and shows the usage of a custom value provider instead of an action filter.
I don't understand why you would want to post Json if you're wanting to do a full page post. Why not just post normal form variables from the Html form element?

Categories