Example on Making rest call to Python server using angular js client - javascript

Can anybody give an example on using rest in getting and posting data from/to python server using Angularjs .
Please provide an example for both client(angularjs) and server(python) ..
where my sample client-side code is
var student_id = 12
$http({
method:"POST" // or get
url: //url to the python file
data: //this is what confusing me .. how to send that student id
}).success(function(data){
console.log(data);
})
and in python i want to run a function which prints student id
def print_info(id): ## here id is the student id that shall be recieved
print "student id is %s" %id
here i want the js client to send that student_id value to python server where it should receive it and send that value of print_info function to the client..
Thanks in advance..

You can use it like this:
$http.post('<your_url>', data).success(function(data) {
//handle the data returned
}, function(error) {
//handle if an error is thrown
})
And the format of your data can be a json like this:
data = {
"student_id": value
}

Related

Send POST request from JavasScript to Sinatra endpoint

so I have a javascript file that saves a specific value in a variable send that I need to send to my ruby routes file through a POST request. I'm a little confused if I can do this since what I have does not seem to work. I'm using the MVC structure so my routes file is saved in my controllers folder.
In my JS file, I have the following:
var send = "test"`
$.ajax({
url : window.location.href + "senddata/",
type : ",
data : { send: send },
}).done(function(response) {
alert('1');
}).fail(function (error) {
alert('2');
});
In my Ruby file, I'm not sure what to do to be able to receive this data? I know I need to do #variable = params[:send] but not sure from there. I'm using Sinatra.
My ruby code is as follows:
post '/senddata/' do
flash[:success] = "Reached"
end

How to send a single string to python function from ajax query

Context: I am using JavaScript to send a string as a parameter to a python function over the flask.
But I always get "the missing 1 parameter error" on the python side.
This is what my Ajax query looks like:
$.ajax({
url : 'ListMaker',
data: 'Q1',
success: function(data) {
//does something
}
});
This is what my python function looks like:
#app.route("/ListMaker",methods=["POST","GET"])
def ListMaker(text):
#make it a string just incase
quarter=str(text)
//do things with string
Any other similar questions I can find online, only talk about issues with Ajax and don't really cover the python side. In my case, the function is clearly being called, but it claims to receive no data to work with.
Am I sending the data wrongly from the Ajax side? Or am I parsing it wrongly on the python side?
Clarification for NoneType error from the comments below:
I am sending over:
data: JSON.stringify({"letter": "Q", "value": "25%"})
I am receiving it on the python side like so:
data=request.get_json()
letter=data["letter"]
value=data["value"]
The parameters in a Flask route are for variables in the path, called "variable rules" in Flask:
#app.route("/ListMaker/<text>", methods=["POST", "GET"])
def ListMaker(text):
...
As jQuery Ajax requests are GET by default, your data will be converted to a query string, in this case /ListMaker?Q1. You can access the query string in Flask with flask.request.args.
However, query strings are key-value, and you are only supplying a key, which will correspond to the Python dict {'Q1': ''}. You should either set the Ajax data to a string like quarter=Q1, or use an object:
$.ajax({
url : 'ListMaker',
data: {'quarter': 'Q1'}, // or 'quarter=Q1'
success: function(data) {
//does something
}
});
Then you will be able to access it in Flask:
#app.route("/ListMaker", methods=["POST", "GET"])
def ListMaker(): # no parameters needed
quarter = flask.request.args["quarter"]
# quarter == "Q1"
If you want to use a POST request, set method: 'POST' in the Ajax-call, and use flask.request.get_data() or flask.request.get_json() on the Flask side.

Getting None values for POST request (via the Axios library) sent to Python/Django

I am building a web app with Django/Python and trying to send data to a controller via a POST request using the Axios library (within Vue.js code).
The POST QueryDict seems to be empty and I can't see why that is happening:
changeCountry: function(e, id){
console.log("Let's change the country")
console.log(e.target.value) // is printing correctly
console.log(id) // also printing correctly
axios({
method: 'post',
url: '/template/country',
data: {
id: id,
country: e.target.value
},
headers: {
'X-CSRFToken': "{{csrf_token}}"
}
})
.then(function (response) {
alert(response.data); // this is returning what I expect
})
.catch(function (error) {
console.log(error);
})
},
The Python method looks like this:
def update_template_country(request):
pprint(request.POST) # prints an empty QueryDict
id = request.POST.get('id')
country = request.POST.get('country')
print(id, country) #prints None None
return HttpResponse("The country is changed") # this is being returned back to the client
The console.log messages at the top print what I expect and since there is no error I am assuming the CSRF header token is fine. Have I missed something obvious or misunderstood how this is working?
EDIT: looking at the Chrome Network tab, it seems the data is being 'POSTed' correctly:
It shows this:
{"id":"593ff2270098e6e8d3292b60","country":"US"}
and that's what I expect, so I suspect the issue is with Django. But I can't see what that might be.
Write your python POST request like this:
def update_template_country(request):
data = json.loads(request.body)
id = data["id"]
country = data["country"]
'''Any other function you want to perform'''
return HttpResponse(json.dumps({'message':'The country is changed'},status=200)
Basically the problem is with the format of POST request, Django is not able to parse it properly that's why when you print the POST request it return an empty dictionary.

Node js server not receiving data from angularjs

I have a data at angularjs client. when i send the data to server using $http.post, i am not able to read data at server. I dont understand where i have gone wrong ?
This is the angular code:
var data = $.param({
id:$scope.user_id,
});
alert(JSON.stringify(data));
$http.post('/getdetails',data)
Here is the node js server code:
app.post('/getdetails',function(req,res){
console.log(req.body);
console.log(req.body.id);
});
output at server log:
{}
undefined
I am not concerned about data i send, i am only concerned whether it is readable at server or not.
Thanks !
You are trying to serialise your data using $.param() which is used only in the GET method and not in post. Just send your JSON data directly to nodeJs like this :
var data = {
id:$scope.user_id,
};
$http.post('/getdetails',data)
In you headers specify :
"Content-Type" : "application/json"
So the final request will be like this :
$http.post('/getdetails',data,{headers : {"Content-Type" : "application/json"}})

Passing a string from Python to Javascript

I'm trying to pass a string from Python to Javascript via ajax POST request but i'm finding serious difficulties.
I've tried both with and without using JSON.
Here's the code
JAVASCRIPT
$.ajax({
url: url, #url of the python server and file
type: "POST",
data: {'data1': "hey"},
success: function (response) {
console.log(" response ----> "+JSON.parse(response));
console.log(" response no JSON ---> " +response);
},
error: function (xhr, errmsg, err) {
console.log("errmsg");
}
});
Python
import json
print "Access-Control-Allow-Origin: *";
if form.getvalue("data1") == "hey":
out = {'key': 'value', 'key2': 4}
print json.dumps(out)
Result is a empty JSON. when i do something like JSON.parse in javascript I get a unexpected end of input error, and when i try to get the length of the response data the size I get is 0.
I suppose that there should be some problems with the client server communication (I use a CGIHTTPServer) or maybe something wrong with the datatype that python or javascript expects.
I also tried without JSON, with something like
Python
print "heyyyyy"
Javascript
alert(response) //case of success
but I also got an empty string.
Could you please give me some advices for handling this problem ?
Thanks a lot!
You may want to compare the two snippets of code CGIHTTPRequestHandler run php or python script in python and http://uthcode.blogspot.com/2009/03/simple-cgihttpserver-and-client-in.html.
There isn't enough code to tell where your request handling code is but if it's in a class inheriting from CGIHTTPRequestHandler then you need to use self.wfile.write(json.dumps(out)), etc.
I managed to solve the problem using the method HTTPResponse from the Django Framework.
Now it's something very similar to this
PYTHON (answering the client with a JSON)
from django.http import HttpResponse
...
data = {}
data['key1'] = 'value1'
data['key2'] = 'value2'
.....
response = HttpResponse(json.dumps(data), content_type = "application/json")
print response;
JAVASCRIPT (Retireving and reading JSON)
success(response)
alert(JSON.stringify(response));
Or if I just want to send a String or an integer without JSON
PYTHON (no JSON)
response = HttpResponse("ayyyyy", content_type="text/plain")
print response
JAVASCRIPT (Retrieving String or value)
success: function (response) {
alert(response);
This works very good, and it's very readable and simple in my opinion!
Instead of print json.dumps(out) you should use return json.dumps(out)
The print will only display it in python's console, just as console in javascript.

Categories

Resources