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
Related
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.
I am trying to delete all the items from a Sharepoint List using Python. However, there is no official documentation of Sharepoint REST that supports Python. I have gone through many StackOverflow articles and have built up the python code to delete a single item. However, I am unable to understand how to delete all items at once. Also, iteration over all would be quite complex, since GET request returns a JSON with a lot of unnecessary metadata as well, hence parsing is a challenge. Hence, I am unable to go about deleting all the items at once. Currently I am using requests.post(https://{site_url}/_api/web/lists/getbytitle('List Name')/items(id), auth, headers) and specifying the following headers: X-RequestDigest: digestValue, X-HTTP-Method: DELETE, and IF-MATCH: *. This is working perfectly well and I am able to delete an item by its id but unable to delete all items of the list.
Any help is appreciated, especially involving using python requests as I am using that to perform CRUD operations. Also, the same code gives Bad Request error if I use https://{site_url}/_api/web/lists/getbytitle('List Name')/items/getitembyid(id) instead of https://{site_url}/_api/web/lists/getbytitle('List Name')/items(id). Besides, I am also unable to delete by using requests.post(https://{site_url}/_api/web/lists/getbytitle('List Name')/items?filter=Title eq 'title1'. It gives Bad Request once again. In both cases, apart from the Bad Request error, when I try to log it, it gives the following exception: Microsoft.Sharepoint.Client.InvalidClientQueryException with the error content saying The type SP.ListItemEntityCollection does not support HTTP DELETE method. Any insights into this are also welcome.
It's not possible to delete all list items at once. SharePoint Rest API has not exposed such an endpoint. We suggest you delete item one by one, put the delete request in a loop like below:
function deleteItem(url) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + url,
type: "DELETE",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"If-Match": "*"
},
success: function (data) {
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyList')/items",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
var items = data.d.results;
for(var item in items){
var url = "/_api/Web/Lists/getByTitle('MyList')/getItemById(item.ID)"
deleteItem(url);
}
},
error: function (error) {
alert(JSON.stringify(error));
}
});
More references:
Delete all items from SharePoint
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.
I'm making an AJAX call to a python function. That function does a database query based on the information sent to the function.
I can't work out how to get the variable that is sent to the function.
I was using request.vars.variableName, and I know the function is valid, it's just not receiving the variable to use properly. How do I get POST sent variables from a python function, using web2py?
ETA: This is the code I was using
jQuery.ajax(
{type: "POST",
url: '../../Printed/printedballoons/cost.json', //python function
data: typeSelected,//data sent to server
dataType: 'json',
error: function(msg){$("#ajaxerror").html(msg);},
success: function(data){
balloonPrice = data.cost;
},
timeout: 2000}
);
The error was in the "data: typeSelected" line, the variable name wasnt associated with any data, so the python query:
cost=db(db.balloonprices.type==request.vars.typeSelected).select(db.balloonprices.cost)
was looking for "" as opposed to a anything that actually is in the database.
This works for me:
AJAX call:
$.ajax({
type: "POST",
url: "/app/func",
data: "array="+JSON.stringify(tempArray)
}).done(function( msg ) { });
controller:
def func():
temparray = json.loads(request.post_vars.array)
Hope it'll help you
request.post_vars
They are copied to request.vars also if there is no request.get_vars
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.