Sending a json object from extjs page to backend - python

I am new to Extjs. I wanted to know how can I send a json object to the backend from an extjs page. I am using python to connect to the databse. What I wanted to do was, if an user enters data on the form, that data to be transfered to the database. I am not getting any good tutorials online. Can someone please help??
Thanks in advance.

There are two ways to send Json Object from a form to the Server side for processing and saving in database.
1st way:
Ext.Ajax.request({
url : 'your-server-url-to-post-to',
method : 'POST', //or GET, PUT, DELETE.. case sensitive
jsonData : your-json-object
params : {
//your-request-parameters
},
success : function(response){ //callback function },
failure : function(response) { //callback failure function}
});
For direct form submission:
Ext.form.action.submit({
form : your-form-instance,
method : 'POST',
url : 'url-to-post-to',
params : {
//your request params
}
});
or another way of doing it is :
your-form.submit({
//same config options as above, except form : your-form-instance
});
Read the docs for more config options to suit your needs.. Documentation is pretty good. For learning a good coding style for ext js check out the examples that are part of the download package.

Related

how to get json object from a webservice

i have the below posted json response.as shown below in json section, the parametersobject is emitted in this line (this is an angular application)
this._FromInsToSiteDataService.emitOnSubmitButtonClikedBroadcast(parameters)
and it is received in
this.subscriptionBroadcastEmitterOnSubmitButtonClicked = this._FromInsecticidesToSiteMapDataService.getBroascastEmitterOnSubmitButtonClicked().subscribe((response:Object)=>{
response['siteGeometry'] = this.selectedSite.geometry
console.log("response: ", response)
this.sSProvider.startWebServiceFor(response)
});
in the latter code i want to pass the response which is in json format to the webservice and receive it as show in the websrvicepostedbelow`
when i run the code, i expected to see the contents of the json object which is
{
"dist1": d1,
"dist2": d2,
"date1": date1,
"date2": date2,
"ingredient": activeIngredient
}
but i get NONE
please let me know how can i correctly get a json object from a webservice
json
private submit() {
let parameters = {
"dist1": d1,
"dist2": d2,
"date1": date1,
"date2": date2,
"ingredient": activeIngredient
}
this._FromInsToSiteDataService.emitOnSubmitButtonClikedBroadcast(parameters)
receiving the json object
this.subscriptionBroadcastEmitterOnSubmitButtonClicked = this._FromInsecticidesToSiteMapDataService.getBroascastEmitterOnSubmitButtonClicked().subscribe((response:Object)=>{
response['siteGeometry'] = this.selectedSite.geometry
console.log("response: ", response)
this.sSProvider.startWebServiceFor(response)
});
webservice:
#app.route("/insSpecifications/<parameters>", methods=['GET'] )
def insSpecifications(parameters):
# print(request.json())
print(request.get_json())//returns NONE
return "OK"
Intro
There are two parts to your question -
Making a request from JS
Creating a Flask API to handle the request
Both these have extensively answered on SO hence I will only summarize it here, please follow the links for more information
Answer
REST Method:
When sending JSON data from the front end to the backend, you need to make a POST request or PUT depending on the need. Please read up on REST API concepts to understand the methods and purposes.
https://www.w3schools.in/restful-web-services/rest-methods/
Making a request
Depending on which library you use in the front end, the request might look different, but essentially you need to send a request with JSON in the body and HEADERS set appropriately i.e. Content-Type: application/json
Using FETCH this can be achieved by (auto-generated from postman)
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"username": "Sample1",
"email": "test2#test.com"
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("localhost:5000/sample", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
But most libraries would have wrappers around this, please look into making a POST request for your respective JS library
Creating Flask API
Finally, you need a Flask API to consume this request. Assuming it's a POST request. You need to create a route with method as POST and get the JSON data using get_json() : https://stackoverflow.com/a/20001283/5236575
So once the HEADERS are correctly set and a post request is made, your code should work fine by changing GET to POST
Note: The parameters field is captured correctly hence I'm leaving it as is, but that is not where your JSON body comes from
#app.route("/insSpecifications/<parameters>", methods=['POST'] )
def insSpecifications(parameters):
# print(request.json())
print(request.get_json())
return "OK"
Testing
You can test your API using Postman or any other API testing tool to see how the API behaves and validate if the issue you have is in the API or in the front-end code.

Sending a POST request from Python to Wix?

I'm currently trying to send a POST request from a python tkinter GUI to a wix free website. I already sent several GET requests and were successful. But regardless of anything I do, the POST request yields a 500 internal server error. Here are the code of the http-functions.js in the backend of my wix.
export function post_posFunc(request) {
let options = {
"headers":{
"Content-Type":"application/json"
}
};
return request.body.text()
.then((body) =>{
return wixData.insert("vidinfo", JSON.parse(body));
})
.then((results)=> {
options.body={
"inserted":results
};
return created(options)
})
.catch((error) =>{
options.body = {
"error":error
};
return serverError(options)
});
}
and on my tkinter app, I pass a video's name, size, and class alongside a userId and the code is as follows
def runPost(a,b,c,d,e,f):
url = 'https://###.wixsite.com/###/_functions/posFunc/'
myobj = {
"vidUserId":a,
"videoName":b,
"videoSize":c,
"videoClass":d
}
z = requests.post(url, data=myobj)
print(json.dumps(data, indent=2, sort_keys=True))
print("done with post")
I have already tried it with postman and It worked successfully. The fields that are in vidinfo are displayed above as you can see. I have censored the website's name as someone told me it's against the rules to release private information but If I am allowed to post it please do let me know. What is wrong with my code?
UPDATE
managed to catch and print the error. Updated the code above and adding the error below
{
"error": {
"errorGroup": "User",
"name": "JsonSyntaxError"
}
}
UPDATE#2
Using json.dumps did the trick!
It might be helpful to find out what the actual error message is. In your python script, you are only printing the status code. Knowing the error response which is caught with .catch((error) => { ... }) and is sent with options.body = { error: error }
might give you (and us) some more clues as to what is going on.
Also note that it doesn't always make sense to send a 'server error', namely when the issue is really with the request and not server side. Knowing the error message (and thus, potentially what is causing the error) will help you send the appropriate response and status code.
Without knowing any further error message information, I wonder if how you are handling the request is causing the issue. Are you sure that you can parse the request by using request.body.text() and/or JSON.parse from the python-sent request? It's possible that the python requests module does not serialize data in the same way that Postman does.
Hopefully what I've said can be helpful. I will keep following if you happen to make any updates to what you've posted above. Good luck!!
UPDATE:
After seeing your response error, it looks to me like you might be handling the request incorrectly. As I stated above, Postman may serialize the object differently from python requests.
Try using request.post(url, data=json.dumps(data)).
Again, are you sure that the data can be retrieved from the request.body.text() method? I am not sure what http framework is being used server-side, but if request.body.text() isn't actually able to return any data, it is likely passing undefined to your first promise handler .then((body) => { ... }). Since your error is a JsonSyntaxError, it is likely that JSON.parse cannot actually parse what it is trying to parse, whether that be undefined or an invalid JSON string.

Populating backend script for Django form

I'm trying to create a web front end to do various management tasks with Django. I've never needed a front end but now they want different BU's to be able to utilize them and they need something pretty to press a button on. So what I want to do is:
User inputs form data and submits it
Site access's external script using the post data as args
User is redirected to confirmation page
Right now I can post data and I can run the script with args, I just don't know how to combine the two. Any help or hints on what I should look into would be greatly appreciated. I didn't post snippets because I'd have to sterilize them but upon request I can if it's needed in order to help.
The easiest way to interact directly is to leverage Ajax, whereby you use Ajax Post to send JSON to Django and then handle the arguments as a dict(). Here is an example:
In browser (JQuery/JavaScript):
function newModule() {
var my_data = $("#my_element").val(); // Whatever value you want to be sent.
$.ajax({
url: "{% url 'modules' %}", // Handler as defined in Django URLs.
type: "POST", // Method.
dataType: "json", // Format as JSON (Default).
data: {
path: my_data, // Dictionary key (JSON).
csrfmiddlewaretoken:
'{{ csrf_token }}' // Unique key.
},
success: function (json) {
// On success do this.
},
error: function (xhr, errmsg, err) {
// On failure do this.
}
});
In server engine (Python):
def handle(request):
# Post request containing the key.
if request.method == 'POST' and 'my_data' in request.POST.keys():
# Retrieving the value.
my_data = request.POST['my_data']
# ...
Now all you need to do is to direct your HTML form to call the JavaScript function and communicate the data to the engine.
To redirect the user to another page upon success, you can use this in your success function:
window.location.href = "http://www.example.com";
Which simulates a reaction similar to that of clicking on an anchor tag (link).
Hope this helps.

Authentication Error with Paypal Sandbox and Google App Engine

I'm having trouble getting the Paypal Adaptive Payments API to work with GAE - I'm specifically going to be using Implicit Payments.
The error returned is that my api credentials are incorrect, but from what i've read I should be suspicious of the header format as well.
Here's the snippet of code - I'm using the urlfetch module in GAE:
headers = {
"X-PAYPAL-USERID" : "xxxx_123456789_biz_api1.xxxx.com",
"X-PAYPAL-SECURITY-PASSWORD" : "1234567890",
"X-PAYPAL-SECURITY-SIGNATURE" : "Ahg-XXXXXXXXXXXXXXXXXXXXXX",
"X-PAYPAL-REQUEST-DATA-FORMAT" : "JSON",
"X-PAYPAL-RESPONSE-DATA-FORMAT" : "JSON",
"X-PAYPAL-APPLICATION-ID" : "APP-80W284485P519543T"
}
request_body = {
"actionType" : "PAY",
"senderEmail" : "xxxx_123456789_biz_api1#xxxx.com",
"receiverList.receiver(0).email" : "xxxx_123456789_per#xxxx.com",
"receiverList.receiver(0).amount" : 100.00,
"currencyCode" : "USD",
"cancelUrl" : "some_url.com",
"returnUrl" : "some_url.com",
"requestEnvelope.errorLanguage" : "en_US"
}
url = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay"
result = urlfetch.fetch(url=url,payload=request_body,headers=headers)
I've Xed out some values, but everything I'm using is coming from the sandbox "API Credentials" section.
Is there a problem with the header format? Am I using the wrong set of credentials? Can I even use the sandbox to test Implicit Payments?
Any help is much appreciated.
Thanks!
For any of those having similar problems, follow the excellent tutorial located here:
Awesome Paypal Adaptive Payments Tutorial
The headers do tend to cause authentication errors if not formed correctly. I was pretty far off :)
go to your headers, and make a change like this
the key
'X-PAYPAL-USERID'
should become
'X-PAYPAL-SECURITY-USERID'.
You forgot to set the POST method inside the urlfetch.fetch call; without it, the payload data is ignored.
result = urlfetch.fetch(url=url,
payload=request_body,
method=urlfetch.POST,
headers=headers)
The urllib2.Request used in the Tutorial instead switches automatically from GET to POST when the request data is set.
req = urllib2.Request(self.request_url,paypal_request_data,header_data)

$.ajax function : send json data : parse at serverside function

I am using $.ajax function to send json data to serverside function.
var jsonObjects = [{id:1, name:"amit"}, {id:2, name:"ankit"},{id:3,name:"atin"},{id:1, name:"puneet"}];
$.ajax({
url: "{{=URL('myControllerName')}}",
type: "POST",
context: document.body,
data: {students: JSON.stringify(jsonObjects) },
dataType: "json",
success: function(){
alert('ok');
}
});
In the serverside function, how do I access the data?
Somebody has give the code for grails as :---
//this code is written in grails
import grails.converters.JSON;
List<JSON> students = JSON.parse(params.students) //students in request params is parsed to json objects and stored in the List
println "Student id: " + students[0].studentId //first element of the students list is accessed as a map holding a key studentId
I want to do this in a python web framework viz. web2py.
Tried to access it as params.students and request.students, but no luck.
What is the correct syntax to access the data sent? (I checked the jQuery API, but couldn't find the same).
Thanks,
Vineet
You are confused.
"How to access the data on the serverside" has nothing to do with jquery, and everything to do with your server-side web framework.
You need to extract the data from the request object; the web2py documentation for that is here: http://web2py.com/book/default/chapter/04#request

Categories