return jsonp instead of json - php

I slowly implement jsonp compared to json as I read jsonp approach is safer, it prevent CORS. So in my server side how should the jsonp look like?
What I did for json is just
$arr = array();
$arr[] = {'a'=>'apple','b'=>'ballon'}
json_encode($arr);
what if it's for jsonp?

JSONP doesn't "prevent CORS", JSONP is a workaround to enable GET requests from third-party domains by explicitly requiring the server to cooperate with the Javascript. The way that works is that the requesting Javascript passes along the name of a callback function it would like to be executed. The server then cooperates by wrapping its response in this callback function. When this response returns to the browser as embedded code, the callback is executed with the data from the server.
If the request gives the callback name foo, the response should look like:
foo({"a": "apple", ...});
So:
printf('%s(%s);', $_GET['callback'], json_encode($arr));

Related

HTTP PUT, DELETE and I/O streams with PHP

Is there any way I can access data that was sent via HTTP PUT method other than $putdata = fopen("php://input", "r");?
I have never worked with PUT and DELETE methods and $putdata = fopen("php://input", "r"); seems a bit sketchy. Will it work everywhere is a specific server/php.ini configuration required?
I know that I can get the request method from $_SERVER['REQUEST_METHOD'];
But will the data be in $_REQUEST, if yes then what php://input is about?
And how do I access data that was sent via DELETE?
No, you will need to parse the request manually. $_REQUEST only contains data coming from GET and POST requests; for everything else you are on your own.
If your HTTP request has Content-Type: application/x-www-form-urlencoded, you can parse it back into a variables array very easily with parse_str like this:
parse_str(file_get_contents('php://input'), $vars);
print_r($vars);
You can use this content type with any HTTP method, there is no standard-imposed limitation.

Use JSONP without wrapping response

My server outputs this JSON when I put the URI in web browser. My client app will get this JSON using JSONP because it accesses the foreign domain.
{
"is_execution_successful":true,
"data": "something"
}
Is there a way to do a JSONP without wrapping the response like this:
echo $_GET['json_callback']. '('. json_encode($rtnjsonobj) . ')';
I don't have permission to edit the server output. How to get the JSON using AJAX/JQuery?
Reference I read: http://remysharp.com/2007/10/08/what-is-jsonp/
JSONP has technically nothing to do with JSON. It's simply javascript code.
So if the response is valid JSON, it will not do anything useful when you run it as javascript (JSONP). Especially in this case, the JSON causes a syntax error when executed as javascript.
You can make cross-origin ajax request to the resource, but this is only possible if the server sends this header:
Access-Control-Allow-Origin: *
The star can be replaced with your specific origin of course, it doesn't have to be a wildcard

Receive JSON object from HTTP Get in PHP

I am trying to implement a php client that sends an HTTP GET to the server which sends back a JSON object with the return information. I know how to decode the JSON once my php script has received it, but how would I go about actually getting it?
EDIT: Note - I send the server an HTTP GET, and it generates and sends back a JSON file. It is not a file sitting on the server.
Check out file_get_contents
$json = file_get_contents('http://somesite.com/getjson.php');
Browsers act differently based on what the server responds. It does not matter what type of request you make to the server (be it GET, POST, etc), but to return JSON as a response you have to set the header in the script you make the request to:
header('Content-Type: application/json;charset=utf-8;');
And then echo the JSON string, for example:
//...populating your result data array here...//
// Print out the JSON formatted data
echo json_encode($myData);
User agent will then get the JSON string. If AJAX made the request then you can simply parse that result into a JavaScript object that you can handle, like this:
//...AJAX request here...//
// Parse result to JavaScript object
var myData=JSON.parse(XMLHttp.responseText);
The header itself is not -really- necessary, but is sort-of good practice. JSON.parse() can parse the response regardless.

Json RPC request via jquery getJSON

I am trying to send json-rpc request to remote server with jquery getJSON method. Here is my code:
json_string=JSON.stringify(obj);
var jqxhr = $.getJSON("https://91.199.226.106/ssljson.php?jsoncallback=?", json_string, function(data){
alert("aaaaaa");
});
jqxhr.error(function() { alert("error"); })
Here is my json-rpc string example:
{"jsonrpc":"2.0","method":"merchant_check","params":[{"hostID":150999,"orderID":116,"amount":"150","currency":"051","mid":15001038,"tid":15531038,"mtpass":"12345","trxnDetails":""}],"id":116}
And here is the error I get:
{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Invalid JSON-RPC 2.0 request error (-32600)"}}
I can`t get what is the issue. Am I doing something wrong? Maybe I need to send request with php and not jquery? Then how should I do it?
The getJSON as the name say will send GET request if you want to use JSON-RPC you need to use POST like:
var json_string = JSON.stringify(obj);
$.post('https://91.199.226.106/ssljson.php', json_string, function(response) {
// process response
}, 'json');
but this will only work if your page is on the same server, unless you use CORS.
That specific error message is supposed to tell you that the message envelope is invalid per the JSON-RPC 2.0 spec, or that there's a parse error in the JSON itself.
Unfortunately, in practice, many services return this error under a much wider variety of circumstances. (e.g.: missing authentication token, etc)
Specific problems with your example message?
Does the web-service accept GET requests? (i.e: should this be a POST instead?)
Does the web-service actually require the ?jsoncallback=? bit? That's normally for a JSONP request rather than JSON-RPC. The service is returning a real JSON-RPC error status, so I'd be really surprised if it needed that GET parameter, and (depending on the web-service configuration) might be interpreted as part of the envelope, which would make it an invalid JSON-RPC request!
Does merchant_check take an array of one-or-more transactions as its only parameter? If not, then you've got the syntax wrong for params. Some services want params to be an Array, some services want it to be an Object. Consult the SMD/documentation to determine which is the case.
The service might require text/json (or something else) as the mime-type for the request.
Recommended Approach:
To avoid these issues, you should probably start by using a purpose-built JSON-RPC library, like the one provided in Dojo toolkit, and use the SMD published by the web-service if it has one. (I recommend against hand-constructing JSON-RPC messages).

How to get json data coming from another domain?

I want to use the google images api. In the past when I worked with json I simply used the ajax function to get the json from my own server. But now I will be getting it from an external domain:
https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy monkey&v=1.0
Obviously I can't load this using js since its not from an internal url. So in these cases how does one work with json data. Are you supposed to load it via CURL using a server side script or is there another way?
You can make use of JSONP by adding a callback GET param.
https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0&callback=hello
Then you can request it with jQuery's $.getJSON().
$.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0&callback=?', function(response) {
console.log(response.responseData);
});
jsFiddle.
You must use Cross Origin Resource Sharing (CORS http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing)
It's not as complicated as it sounds...simply set your request headers appropriately...in Python it would look like:
self.response.headers.add_header('Access-Control-Allow-Origin', '*');
self.response.headers.add_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
self.response.headers.add_header('Access-Control-Allow-Headers', 'X-Requested-With');
self.response.headers.add_header('Access-Control-Max-Age', '86400');

Categories