Ive been tryin to solve this for a long time and now know why its not possible.
The url
http://twittercounter.com/api/?username=Anand_Dasgupta&output=json&results=3
returns a json but when i append a "&callback=get" along with it,it doesnt specify the callback wrapper function.
So the only solution now is to build a wrapper manually round the json data.
My question is how do i do that.
Is there some code already existing in php/javascript that i can change according to my specs.
Any advice will be appreciated.
Thank You
Anand
Well the purpose of JSONP is to wrap the JSON (which will be evaluated as JavaScript on the client side) into a callback that only the client requesting the data knows. This prevents the client from executing unwanted JavaScript code. Without the callback ou will have the same origin policy problem (which JSONP solves), so you can only request tot he URL the script came from.
Basically you will have to attach the callback with PHP, meaning on the server side, with a proxy script. The script retrieves the data from the other URL and wraps it into a callback:
<?php
// Don't know on the fly how to request data from another URL in PHP, but it's easy to find out
$response = request_url('http://twittercounter.com/api/?username=Anand%5FDasgupta&output=json&results=3');
echo $_GET['callback'] . '(' . $response . ')';
?>
Related
It took me a while to understand this, being that it was a little obvious. I will answer myself, so other can benefit of the answer and ofcourse to see if there's a better way to do this. The problem was based on Axios/Yii2 but I guess this will apply equally to other frontend libraries/frameworks sending data to Yii2.
I needed to post data from a small form made on Vuejs, sending the request Axios to a Action/Controller on Yii2, so data is sent on a simple POST request and the post is getting to the controller, but I was not able to receive the data on the action, $_POST | $post arrives empty (checked using xdebug).
As much as I remember, this had something to do with security. But I already tried by disabling public $enableCsrfValidation, so that was not the problem.
public $enableCsrfValidation = false;
But no matter what, data was not being added to the request/post data inside Yii2.
The following Image, explains the problem you will find there:
The Axisos method that sends the post with test data.
The Yii2 Action stpoed at the place, I should be able to see data.
The capture of the xdebug variables and data for the request.
The capture of Chrome where you can check the payload is sent.
The answer is as I said "kind of obvious", but I could not see that, and I am sure some other devs will probably fall on this.
After searching like crazy and asking everyone, I tried sending the request by using Postman app, yup the best thing I know to test apis.
Dont forgue to add the xdebug cookie to be able to debug your PHP Endpoint.
There I found the first clue «the obvious part», I was not sending data as a form-data, Axios and other libraries, send the data as a raw (application/json) payload.
This means that Yii2 will no be able to find the data inside the post request, yes its there but Yii2 magic will not work, neither you will find this data inside $GLOBALS or in $_POST.
So reading the Yii2 documentation I found that inside request I can use a function that will help me recovering the Raw data, so to do this use the following line:
$raw_data = Yii::$app->request->getRawBody();
Now, that data gets to you as a simple, raw json string, so use the power of PHP to parse it to an object.
$object= json_decode($raw_data );
And finally use the data inside by calling the properties you look for, sent on the pay load:
Json Payload:
{
"msg":"This is my payload",
"id":"11"
}
To use it:
echo $object->{'msg'}; // prints: This is my payload
So that's the way to handle that, now I would like some other points of view to see if there's a better way or cleaner way to do this. Hope it helps.
My 4D database has a method that calls an external application to make an HTTP request to an API site, e.g. https://somewhere.com/api/?key=somekey¶m=someparam. The request returns a JSON response. However, the external application only returns a call success or fail. I am not able to extract the JSON response.
My 4D database is still in version 12 and have no plans to migrate yet to latest version. Is there any way for me to make an HTTP request and get the JSON response? I was thinking of using the built-in PHP engine and make cURL call. Has anybody done this in 4D?
I recommend using Keisuke Miyako's OAuth plugin. https://github.com/miyako/4d-plugin-oauth. It comes with a cURL library and a JSON parsing library. I use it to pull JSON data from an api source. It looks like he's depricated the plug-in but has links to the separate components.
http://sources.4d.com/trac/4d_keisuke/wiki/Plugins/
ARRAY LONGINT($optionNames;0)
ARRAY TEXT($optionValues;0)
C_BLOB($inData;$outData)
$url:="https://api.atsomewhere.com/blahblah"
$error:=cURL ($url;$optionNames;$optionValues;$inData;$outData)
If ($error=0)
$jsonText:=BLOB to text($outData;UTF8 text without length)
$root:=JSON Parse text ($jsonText)
JSON GET CHILD NODES ($root;$nodes;$types;$names)
$node:=JSON Get child by name ($root;"Success";JSON_CASE_INSENSITIVE)
$status:=JSON Get bool ($node)
If ($status=1)
$ResponseRoot:=JSON Get child by name ($root;"Response";JSON_CASE_INSENSITIVE)
$node1:=JSON Get child by name ($ResponseRoot;"SourceId";JSON_CASE_INSENSITIVE)
$node2:=JSON Get child by name ($ResponseRoot;"SourceName";JSON_CASE_INSENSITIVE)
$output1:=JSON Get text ($node1)
$output2:=JSON Get text ($node2)
End if
End if
4D v12 has built-in support for PHP. I used the PHP EXECUTE command to call a PHP file. But since 4D v12 PHP does not have native support for cURL I used file_get_contents()
My 4D code is as follows:
C_TEXT($result)
C_TEXT($param1)
C_BOOLEAN($isOk)
$param1:="Tiger"
//someFunction is a function in index.php. $result will hold the JSON return value.
//I pass value "Tiger" as parameter
$isOk:=PHP Execute("C:\\index.php";"someFunction";$result;$param1)
C:\index.php contains the PHP script that 4D v12 will run. The code is
<?php
function someFunction($p1){
$somekey = 'A$ga593^bna,al';
$api_URL = 'https://somewhere.com/api/?key='. $somekey. '¶m='.$p1;
return file_get_contents($api_URL);
}
?>
This approach is applicable for GET request. But this already serves my purpose.
I'm brand new to Pentaho and I'm trying to do the following workflow:
read a bunch of lines out of a DB
do some transformations
POST them to a REST web service in JSON
I've got the first two figured out using an input step and the Json Output step.
However I have two problems doing the final step:
1) I can't get the JSON formatted how I want. It insists on doing {""=[{...}]} when I just want {...}. This isn't a big deal - I can work around this since I have control over the web service and I could relax the input requirements a bit. (Note: this page http://wiki.pentaho.com/display/EAI/JSON+output gives an example for the output I want by setting no. rows in a block=1 and an empty JSON block name, but it doesn't work as advertised.)
2) This is the critical one. I can't get the data to POST as JSON. It posts as key=value, where the key is the name I specify in the HTTP Post field name (on the 'Fields' tab) and the value is the encoded JSON. I just want to post the JSON as the request body. I've tried googling on this but can't find anyone else doing it, leading me to believe that I'm just approaching this wrong. Any pointers in the right direction?
Edit: I'm comfortable scripting (in Javascript or another language) but when I tried to use XmlHttpRequest in a custom javascript snippet I got an error that XmlHttpRequest is not defined.
Thanks!
This was trivial...just needed to use the REST Client (http://wiki.pentaho.com/display/EAI/Rest+Client) instead of the HTTP Post task. Somehow all my googling didn't discover that, so I'll leave this answer here in case someone else has the same problem as me.
You need to parse the JSON using a Modified JavaScript step. e.g. if the Output Value from the JSON Output is called result and its contents are {"data"=[{...}]}, you should call var plainJSON = JSON.stringify(JSON.parse(result).data[0]) to get the JSON.
In the HTTP Post step, the Request entity field should be plainJSON. Also, don't forget to add a header for Content-Type as application/json (you might have to add that as a constant)
I can't seem to find a definitive answer on this -- what does the p in JSONP stand for?. The candidates I've found so far are padding and prints. Anyone know where the JSONP name came from?
Padding.
from http://en.wikipedia.org/wiki/JSONP
JSONP or "JSON with padding" is a complement to the base JSON data
format, a pattern of usage allowing a page to request data from a
server in a different domain. JSONP is a solution to this problem,
forming an alternative to a more recent method called Cross-Origin
Resource Sharing.
Padding
While the padding (prefix) is typically the name of a callback
function that is defined within the execution context of the browser,
it may also be a variable assignment, an if statement, or any other
Javascript statement. The response to a JSONP request (namely, a
request following the JSONP usage pattern) is not JSON and is not
parsed as JSON; the returned payload can be any arbitrary JavaScript
expression, and it does not need to include any JSON at all. But
conventionally, it is a Javascript fragment that invokes a function
call on some JSON-formatted data.
Said differently, the typical use of JSONP provides cross-domain
access to an existing JSON API, by wrapping a JSON payload in a
function call.
Hope that helped. Google wins!
Stone,
What I know, it stands for 'Padding'. There is a explaination about it on Wikipedia: JsonP
What it does?
It gives you the possibility to make a CROSS-DOMAIN request and get JSON data returned.
Normally via the HTML script tag you call for another JavaScript.
But JsonP provide you a callback function and you can return noraml Json response.
Example:
You create a script tag:
<script type="text/javascript" scr="http://anotherDomain/Car?CarId=5&jsonp=GiveCarResponse"></script>
In this script the GiveCarResponse is the callback function on the other Domain. Invoking this function will result in a Json response. In example:
{"CarId":5, "Brand":"BMVV", "GAS": false}
Does this make sense?
From wikipedia, it stands for "padding" (or with padding).
http://en.wikipedia.org/wiki/JSONP
Umm ... you've seen the wikipedia page, and you mistrust its accuracy?
This standards site seems to confirm the "with padding".
It basically means to add a calling function around JSON.
AJAX can be called from your own server only and is not a cross domain. So to load data from different servers at client side, you make a JSONP request, basically you load a normal javascript file from other server just like you include a normal javascript file. Bust as JSON is not a valid javascript file, JSON is wrapped up in a function call to make it valid js file. the wrapped up function (already in your code) then extracts that data and show it on your page.
I have a php page called 'dataFetch.php' which sits on one webserver. On another webserver, I have a JS file which issues JSON calls to dataFetch. dataFetch connects to a database, retrieves data and puts it in a JSON format which is fed back to the calling program. In IE, this works fine. In other browsers it does not because of the cross domain restriction.
To get across the cross-domain restriction, I make a call to a file, proxy.php, which then makes the call to dataFetch. My problem now is that proxy.php retrieves the file from dataFetch but the JS script file no longer sees the response from proxy.php as a JSON format and so I can't process it. Can anybody help me out?
Have a look at using JSONP instead, which solves the cross site difficulties you have had.
Please explain how the proxy works. A proxy should be very simple, something like this:
<?php
$url = $_GET['ur'];
echo file_get_contents($url);
?>
And used like this:
http://www.example.com/proxy.php?url=http://www.someothersite.com/dataFetch.php