I am having problem extracting data sent from the Ajax call to the python flask backend.
I am able to extract the key:value string pair only from the request.args object. But the problem is the data I am sending is of mixed type :
e.g. data:{'data':'stringdata','Email':['abc#example.com','def#example.com'],'checkbox':'[true,true]'}
when I am reading this data from the request.args in my python module.. I am able to get request.args['data'] which returns 'stringdata' but for the other keys like request.args['Email'] I am getting BAD REQUEST errors.
I have tried JSON.stringify the data separately for each item plus the whole data object but none of it is working.
I have also tried setting the data type and the contentType in the Ajax call but still no good.
$.ajax
({
url: '/abc',
data : {
"data": 'stringdata',
"Email": ['abc#example.com','def#example.com'] ,
"Hbeat":[true,true],
"Creport" : [true,true] ,
"Treport" : [true,true] ,
"Preport" : [true,true]
},
success: function(data)
{
},
complete: function()
{
}
});
Here the python part where I am trying to get the data.:
#app.route('/abc', methods=['POST','GET'])
def checkingdata():
print(request.args)
print(request.args['data'])
print(request.args['Email']) # this is where I am getting errors.
I expect to get the data as the form they are in. e.g. where I am passing the list of emails I need to get them as list. and where there are single string values I should get them as single string values.
thanks so much for your time. Please help if you can.
You need to use request.args.getlist:
emails = request.args.getlist('Email')
Related
So, I've been struggling with this for the entire weekend and I still can't figure out what's wrong. I'm trying to pass some data through json_decode to be able to save it to a file and I keep getting the error it expects a string but an array is given. I'm using jQuery and PHP.
The data I send through the ajax call is, according to console.log(noBrack):
{"ID":2,"LLID":"LLID2","volNaam":"Test - 0","norm":"Zicht","instalDatum":"17-11-2017","endDate":"18-11-2017","serie":"0","klant":"Testklant","file":"data/Testklant (Heerenveen)/LLID2.json","gelDat":"27-10-2018"}
My Ajax call is:
$.ajax({
url: 'quickGrade.php',
type: 'POST',
data: noBrack,
datatype: 'json',
success:function(data){
alert(data );
}
});
My PHP code is:
$testSave = 'data/gradeTest.json';
$decode = json_decode($_POST, true);
file_put_contents($testSave, $decode);
Can anyone find out what I'm doing wrong? I've tested my string with an online json_decode tester and it said it was valid so I'm kinda hardstuck here.
The way you are sending data will give you $_POST array in php code. So actually you do not need to decode because the data is coming as $_POST array not a JSON string.
You should use json_encode to get JSON string to store in file. Because $_POST is an array, so you can't decode it like a Json string.
Your code will become this:
$testSave = 'data/gradeTest.json';
file_put_contents($testSave, json_encode($_POST));
You can read more about:
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php
I would like to use a web-service that takes in JSON object (The object binds two arrays) in a POST request and returns a JSON object array.
I would now like to send request to the webservice from my AngularJS. Here is my code:
wellApp.factory('Search', ['$resource',function($resource){
return $resource('/filetables/searchdata/:tagSearchInput',
{
},
{
searchData:{
method:'POST',
isArray: true,
params:{ tag: '#tagSearchInput.tag',
details: '#tagSearchInput.details'
}
}
})
}])
function myWellsCtrl($scope,$resource, Wells, Tags, Search) {
$scope.wellSearchResult = Search.searchData({tag: ["TypeOfWell"],
details: ["Vertical"]});
};
If I do this, I get a NullPointerException at the server side, meaning that the arguments that I pass are getting passed as null.
How do I pass in this object such that the server interprets them as an object containing two arrays. I'm new to AngularJS and am not able to understand the # notation of assigning the incoming parameter. It'd be great if someone here can lend me some help.
You shouldn't need to include params in searchData since the JSON will be sent in the body of the POST request. Try removing them from searchData. Then in your controller, try calling your service like this:
Search.searchData({}, {tag: ["TypeOfWell"], details: ["Vertical"]})
Note the {} as the first parameter, which is the params for your request. The second {} is for the payload. This will send your JSON in the request payload instead of as params. Let me know if that doesn't work for you. I have done something similar to what you're doing and this way worked for me.
You didn't mention which server side you are using. But, the first thing you probably need to do is set the HTTP Header content type. I usually set it globally on the $http object, like this:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
With the default content-type header, the form parameters are not attached to the request as form parameters and they cannot be accessed as form parameters on the server side code.
Second, this:
{
tag: '#tagSearchInput.tag',
details: '#tagSearchInput.details'
}
is not a valid JSON object. The property names must be enclosed in double quotes. Here they are enclosed in none. The property values must also be enclosed in single quotes; here they are enclosed in single quotes.
I believe that should be a valid JavaScript object; but it isn't JSON. You can tweak it here:
{
"tag": "#tagSearchInput.tag",
"details": "#tagSearchInput.details"
}
I wrote up a blog post about my experiences integrating AngularJS with ColdFusion. What I have been doing is converting my objects to JSON Strings before passing them over the wire. Then the server side will deserialize the JSON string.
Here is a great post, similar to mine, that is PHP focused.
I'm new to passing objects through AJAX, and since I am unsure of both the passing and retrieving, I am having trouble debugging.
Basically, I am making an AJAX request to a PHP controller, and echoing data out to a page. I can't be sure I'm passing my object successfully. I am getting null when printing to my page view.
This is my js:
// creating a js filters object with sub arrays for each kind
var filters = {};
// specify arrays within the object to hold the the list of elements that need filtering
// names match the input name of the checkbox group the element belongs to
filters['countries'] = ["mexico", "usa", "nigeria"];
filters['stations'] = ["station1", "station2"];
filters['subjects'] = ["math", "science"];
// when a checkbox is clicked
$("input[type=checkbox]").click(function() {
// send my object to server
$.ajax({
type: 'POST',
url: '/results/search_filter',
success: function(response) {
// inject the results
$('#search_results').html(response);
},
data: JSON.stringify({filters: filters})
}); // end ajax setup
});
My PHP controller:
public function search_filter() {
// create an instance of the view
$filtered_results = View::instance('v_results_search_filter');
$filtered_results->filters = $_POST['filters'];
echo $filtered_results;
}
My PHP view:
<?php var_dump($filters);?>
Perhaps I need to use a jsondecode PHP function, but I'm not sure that my object is getting passed in the first place.
IIRC the data attribute of the $.ajax jQuery method accepts json data directly, no need to use JSON.stringify here :
data: {filters: filters}
This way, you're receiving your json data as regular key/value pairs suitable for reading in PHP through the $_POST superglobal array, as you would expect.
http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php
When you use ajax the page is not reloaded so the php variable isn't of use.
You may want to look for a tutorial to help. I put one at the beginning as I don't see how to format this on my tablet
you will need to json_encode your response as the tutorial shows
you may want to print to a log on the server when you are in the php function and make it world readable so you can access it via a browser
I like to use the developer tools in Chrome to see what is actually returned from the server
i have a problem regarding the responseXML of ajax..
I have this code from my callback function:
var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue;
However, the linestring can only hold up to 4096 characters max.. the remaining characters are rejected.
I dont know what to use to get all the values that the lineString
returns. its quite a big data thats why I thought of using the responseXml
of AJAX, BUT turned out it still cannot accomodate everything.
My linestring consists of lines from a logfile which I concatenated and just
put line separator. I need to get this data in my form so that is why after reading from the php, i send it back via AJAX
Do you have suggestions guys.
XML adds a lot of extra markup for most ajax requests. If you are expecting some kind of list with data entities, sending them in a JSON format is the way to go.
I used JSON to get quite huge arrays with data.
First of all, JSON is just Javascript Object Notation meaning that the Ajax Request would request a String which will actually be evaluated as a Javascript object.
Some browsers offer support for JSON parsing out of the box. Other need a little help. I've used this little library to parse the responseText in all webapps that I developed and had no problems with it.
Now that you know what JSON is and how to use it, here's how the PHP code would look like.
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response );
Try it and see what it echos. I used the php 5.4 array declaration syntax because it's cool! :)
When requesting the data via Ajax you would do:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
Recap:
JSON parsing needs a little help via JSON2 library
PHP can send maps as JSON
Success boolean is widely used as a "successful/unsuccessful" flag
Also, if you're into jQuery, you can just set the dataType : "json" property in the $.ajax call to receive the JSON response in the success callback.
I'm trying to send json string in the get request to the server, here is how it looks before encoding :
filters={"groupOp":"AND","rules":[{"field":"countrycode","op":"eq","data":"ARG"}]}
Naturally I end up with null pointer when trying to get this json string, then I googled this encodeURIComponent and it partially encodes this string like this :
filters={"groupOp"%3A"AND"%2C"rules"%3A[{"field"%3A"countrycode"%2C"op"%3A"eq"%2C"data"%3A"ARG"}]}
But this is how it supposed to be in order to work :
filters=%7B%22groupOp%22%3A%22AND%22%2C%22rules%22%3A%5B%7B%22field%22%3A%22countrycode%22%2C%22op%22%3A%22eq%22%2C%22data%22%3A%22ARG%22%7D%5D%7D
How do I get this, entirely encoded string so I can read it at server side properly ?
Reason why I used get instead of post
I'm sending this filter(json) content to the server side, web service gets data from the database and returns pdf document.
Using post, I'm able to send correct data and the response is successfully displayed in my firebug console. But I need to return pdf doc to override the current page or open new window/tab and return in that one.
I think you're overworking this problem. Or encoding too many times. Or something.
You've got a JSON string, and you are trying to JSON encode it. That seems...unhelpful.
A better approach might be to produce a Javascript object, then JSON.Stringify that, and then transmit it as a parameter.
var thing = {
groupOp : "AND",
rules : [
{ field : "countrycode", op : "eq", data : "ARG" },
...
],
...
};
var stringrep = JSON.stringify(thing);
// post via jQuery
$.ajax({
type: 'POST',
url: url,
data: stringrep,
dataType: 'json'
success: function() { ... },
});
Normally for a JSON stringified message to or from the server, you'd want to use HTTP POST. HTTP GET puts all "parameters" in the URL; there is no message body. In contrast, HTTP POST allows you to attach a message body to the HTTP message, which can be "anything". With that approach, you don't need to url-encode the quotes and spaces; the JSON message just gets transmitted as the message body of the HTTP message.
HTTP POST is the way applications upload images, or transmit XML documents, and so on. Anything complex gets transmitted via POST.
var filtersParameter = 'filters=' + encodeURI(JSON.stringify(filters));
var filtersParameter = 'filters=' + atob(JSON.stringify(filters));
Note: atob() method uses base64 algorithm to encode the data. This encoded data can be easily passed to a server where it can be decoded using corresponding decoding methods (in python base64.b64decode(encoded_string) is used).