How to store data from ajax with webapp2(python) - javascript

I want to receive data from ajax, but I got "None" as my variable
class update(webapp2.RequestHandler):
def post(self):
print("data",self.request.POST.get('data'))
app = webapp2.WSGIApplication([
('/update', update)
], debug=True)
data= 3;
$.ajax({
url: "/update",
data: data, //data=3
type: "POST",
success: function( xml ) {
alert( "It worked!" );
},
});
i got: ('data', '') as result when i expected: "data '3'"
Edit: if possible, please keep the answer to just one line: like:
print("data",self.request.POST.get('data'))

Thanks to Beniamin H,the solution is simple.
data= {
'a':3 // I changed data to a dictionary
// edit:you don't need quotes for a, so, a:3 works also
}
$.ajax({
url: "/update",
data: data,
type: "POST",
success: function( xml ) { //more edit:xml is the data returned
alert( "It worked!" ); //from the webbapp you can name it what
//ever you want
//this gets data from the server
console.log(xml['a']) //prints out 3
},
});
class update(webapp2.RequestHandler):
def post(self):
data=self.request.POST.get('a')
print("data: "+data)
#edit: to return a data to javascript, make a dictionary like:
# data={
# 'a':3
# 'b':5 #you need quotes i think
# }
#and then write:
# self.response.write(data)
This prints out: data: 3

Related

Not able to retrieve data values from Ajax GET call into Django view

I am trying to query the employee list based on parameter I send
through ajax call inside data, but it giving me an error (i want it
through GET req only )
Js ajax func
$(document).ready(function () {
$(".call_ajax").click(function () {
$.ajax({
url: "/employee_list",
type: "GET",
contentType: "application/json",
dataType: "json",
data: {
designation: "soft eng",
},
headers: {
"X-CSRFToken": csrftoken,
Authorization: my_token,
},
success: function (data) {
console.log(data);
},
error: function (xhr) {
//Do Something to handle error
console.log(xhr.error);
},
});
});
my view
#csrf_exempt
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
#permission_classes([IsAuthenticated])
#authentication_classes([TokenAuthentication])
def employee_list(request):
if request.method == 'GET':
data_ = request.data['designation']
print(data_)
employees = Employee.objects.all()
students = Student.objects.all()
user = MyUser.objects.all()
serializer = EmployeeSerializer(employees, many=True)
serialized_sudents = StudentSerializer(students, many=True)
multi = {
'employees': serializer.data,
'students': serialized_sudents.data
}
# serializer2 = UserSerializer(user, many=True)
return JsonResponse(multi, safe=False)
error i am getting in browser
GET http://127.0.0.1:8000/employee_list/ 500 (Internal Server Error)
error in Django log
File "C:\Users\atif\PycharmProjects\CodePlatform\syntax_fight\api_\views.py", line 42, in employee_list
data_ = request.data['designation']
KeyError: 'designation'
request.data returns the parsed content of the request body.
This is similar to the standard request.POST and request.FILES
You can use request.GET.get('designation')
#csrf_exempt
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
#permission_classes([IsAuthenticated])
#authentication_classes([TokenAuthentication])
def employee_list(request):
if request.method == 'GET':
data_ = request.GET.get('designation') # Here I made changes
print(data_)
employees = Employee.objects.filter(designation=data_) # Map parsed data with database field
students = Student.objects.all()
user = MyUser.objects.all()
serializer = EmployeeSerializer(employees, many=True)
serialized_sudents = StudentSerializer(students, many=True)
multi = {
'employees': serializer.data,
'students': serialized_sudents.data
}
# serializer2 = UserSerializer(user, many=True)
return JsonResponse(multi, safe=False)
or
You can override get_queryset method. As for query string parameters request.data holds POST data, you can get query string params through request.query_params
def get_queryset(self):
data = self.request.query_params.get('designation')
queryset = Model.objects.filter() # use whatever you want filter
return queryset
To know more about request.data and request.query_params, here is the link
Request parsing link
It is most probably because you are using GET, but the data resides in body. Have a look at this. To try to fix this, change your request method to POST:
$.ajax({
url: "/employee_list",
type: "POST",
...

Access ajax elements with django

i am using ajax to fetch django model and get results
views.py
def browse_jobs(request):
keyword = request.GET.get('keyword', None)
company = Company.objects.filter(title__icontains=keyword)
data = serializers.serialize("json", company, fields=('title'))
return JsonResponse({'data':data,})
ajax request
$.ajax({
url: '/browse_jobs',
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
if (data) {
console.log(data.title);
}
}
});
and i am getting this response from django
{"data": "[{\"model\": \"app.company\", \"pk\": 1, \"fields\": {\"title\": \"Facebook\"}}, {\"model\": \"app.company\", \"pk\": 2, \"fields\": {\"title\": \"Fabook\"}}]"}
my question is how i can access the title.
You here double serialized the value for the "data" key: first by the serializers.serialize(..) that constructed a string, and the you again serialize it (constructing an string literal), making it harder to obtain the elements.
We can prevent this, for examply by turning the JSON blob back into a vanilla Python object first:
from json import loads as json_loads
def browse_jobs(request):
keyword = request.GET.get('keyword', None)
company = Company.objects.filter(title__icontains=keyword)
data = serializers.serialize("json", company, fields=('title'))
return JsonResponse({'data': json_loads(data), })
Then the AJAX call will receive a JSON blob where "data" does not map to a string, but a list of subdictionaries, making it easier accessible.
Here there are two results for your query, you can print the first title with:
$.ajax({
url: '/browse_jobs',
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
console.log(data.data[0].fields.title);
}
});

Pass just one field via AJAX with Flask

I have a VERY simple HTML form with just one <input type='text'> field, an email address, that I need to pass back to a Python script via AJAX. I can't seem to receive the value on the other end. (And can all the JSON encoding/decoding be avoided, since there's just one field?)
Here's the code:
from flask import Flask, render_template, request, json
import logging
app = Flask(__name__)
#app.route('/')
def hello():
return render_template('index.htm')
#app.route('/start', methods=['POST'])
def start():
# next line outputs "email=myemail#gmail.com"
app.logger.debug(request.json);
email = request.json['email'];
# next line ALSO outputs "email=myemail#gmail.com"
app.logger.debug(email);
return json.dumps({ 'status': 'OK', 'email': email })
if __name__ == "__main__":
app.run()
And the Javascript that sends the AJAX from the HTML side--
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
d = "email=" + $('#email').val(); // this works correctly
// next line outputs 'sending data: myemail#gmail.com'
console.log("sending data: "+d);
$.ajax({
type: "POST",
url: "{{ url_for('start') }}",
data: JSON.stringify(d),
dataType: 'JSON',
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log("SUCCESS: ");
// next line outputs 'Object {email: "email=myemail#gmail.com", status: "OK"}'
console.log(result);
}
});
});
JSON.stringify is used to turn an object into a JSON-formatted string, but you don't have an object, just a string. Try this:
var d = { email: $('#email').val() };
JSON.stringify(d) will now turn that into a JSON-formatted string:
{email: "myemail#gmail.com"} which can be parsed by flask.
To do this without JSON:
var d = { email: $('#email').val() };
...
// AJAX
data: d,
success: ...
This will turn {email: "myemail#gmail.com"} into email=mymail#gmail.com and send that as body of the POST request. In Flask, use request.form['email'].

this.state.search_results.map is not a function but it's an array

render: function(){
console.log(this.state.search_results);
var renderedSearchResults = this.state.search_results.map((result) => {
The console.log prints:
[{"id": "testGroup2"}, {"id": "testGroup77777"}, {"id": "testGroup1"}, {"id": "testGroup3"}]
The data is obtained through:
$.ajax({
url: this.props.routes.search,
contentType: 'application/json',
type: 'POST',
data: JSON.stringify(searchObj),
success: function(data){
console.log(data);
this.setState({search_results:data});
}.bind(this),
error: function(xhr, status,err){
console.error("/api/response", status, err.toString());
}.bind(this)
});```
Through:
def post(self):
"""
Makes a request to search for a specific
searchtype: Group
searchstring: ""
requestedfields: []
"""
search_type = self.json_data.get('searchtype', 'Group')
search_string = self.json_data.get('searchstring', '')
requestedfields = self.json_data.get('requestedfields', ['id'])
search_model = {
'Group': Group(),
'User': User()
}[search_type]
search_fields = {
'Group': ['id', 'tags'],
'User': ['username']
}[search_type]
# check if requestedfields contains valid fields
for field in requestedfields:
if field == 'id':
continue
value = search_model.default().get(field, None)
if value is None:
return self.set_status(400, "Model {0} does not have requested field {1}".format(search_type, field))
try:
search_results = search_model.search_items(search_string, search_fields, requestedfields)
except err:
return self.set_status(400, "Something went wrong")
self.set_status(200, "Success")
return self.write(tornado.escape.json_encode(search_results))
I'm really confused as to how this.state.search_results isn't an array that I can iterate through, can anyone see what's going on?
I've tried using console.log(Object.prototype.toString.call(data)); inside the success function and I get:
[object String]
Try to set json data type in an explicit way, while doing your ajax request:
$.ajax({
dataType: 'json',
//...
});
Most probably Intelligent Guess that is used to detect data type by jQuery, is giving wrong result.
Found my answer, didn't set dataType: "json" in my ajax request.

ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },

Categories

Resources