I'm having real trouble getting remote JSON file using AngularJS from a remote server, and even when I get it, I can't find a way of using the data.
Here is the angular code:
var artistControllers = angular.module('artistControllers', ['ngAnimate']);
artistControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.json('http://remotehost.mobi/temp.json').
success(function(data){
console.log('success');
console.log(data);
}).
error(function(data, status ){
console.log('error');
console.log('status');
});
}]);
Usually what I get are just all type of errors:
when trying to get dynamic JSON from PHP script, I need to send a
callback, which sometimes works, but the callback fires a function
which is outside the scope, so it is irrelevant for my needs.
when trying to load JSON from a .json file (like in the example)I get
errors.
when using $http.get I always get the cross domain security
message.
I'm looking for a way to load json data from a remote server, generated dynamically by PHP,with angular JS controller and use it inside that controller.
Thanks
You need to change the server to allow CORS (see this) or use $http.jsonp and change the response to JSONP format (JSON body wrapped in a callback function call).
If you do not control the remote server, you can proxy the request through your own server so that it is no longer cross-domain.
A example of a proxy that enables CORS is corsproxy.com
CORE is safer then jsonp cuz it has no way of executing javascript code. On the plus side you get more control over statechange/timeout/progress and abortion with CORS since its now ajax
The only risk now is do you trust corsproxy.com to read the data that are being passed through & the updown?
The only thing you have to do is replace http:// with http://www.corsproxy.com/ (don't think it works for https...)
var artistControllers = angular.module('artistControllers', ['ngAnimate']);
artistControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.json('http://www.corsproxy.com/kinneret.mobi/temp.json').
success(function(data){
console.log('success');
console.log(data);
}).
error(function(data, status ){
console.log('error');
console.log('status');
});
}]);
Thanks for the help. I guess my issue was a bit different, that's why I post this solution.
Evantualy I have added the a new header to allow cross origin to my PHP that dynamically generates the JSON code:
header('Access-Control-Allow-Origin: *');
header('content-type: application/json; charset=utf-8');
This goes right before the function encode and returns the json. Another thing I have added is formatting the JSON before it sent back. I have found that sending the "raw" unformatted JSON back cause unexpected problems. Since PHP 5.4 you can add JSON_PRETTY_PRINT to the json_encode:
echo json_encode($data_array, JSON_PRETTY_PRINT);
In the angular code, I checked many combinations, include #Endless suggestion to use corsproxy.com, but found that after these adjustments you can simply use $http.get .
Hope this helps if anyone encounter strange problems with this cross domain policy.
Related
I implemented a Rest Service using the PHP framework named Slim, the service works fine, because i also tested in SoapUI and works without problems. The Service is very simple, it just saves the data into txt file. Although when i consume the service via javascript using a Ajax post method it works, and the data is saved in the file, but the error function is executed instead the success function. Any ideas, whats going wrong?
Service-> PHP SLIM FRAMEWORK
<?php
require 'vendor/autoload.php';
$app=new \Slim\Slim();
$app->post('/gravar_documento', 'gravar_doc');
function gravar_doc(){
$request=Slim\Slim::getInstance()->request();
$data=$request->getbody();
$dados=json_decode($data,true);
file_put_contents('test.txt', $dados["test"]);
$app=Slim\Slim::getInstance();
$response = $app->response();
$response['Content-Type'] = 'application/json';
$response->status(200);
$response->body(json_encode((object) array('success'=>true)));
}
$app->run();
AJAX
$.ajax({
type:'POST',
url: "Service_url->hidden for safety",
data: JSON.stringify( { test: 1, val: 2} ),
success: function(data){
alert("IN");
},
error: function(data){
alert("Fail");
}
});
Thanks
well you still need to see the return data, thats why you should console.log the data back. the callback data is not the same scope as the data that you stringify. If you output the data out prior to your alert, it will tell you what is your API response to your request.
I finally can get the solution. I want to thank to everybody who tried to help me, the simple solution is to add in the first line of PHP code the following:
header('Access-Control-Allow-Origin: *');
And it will work, at least works for me.
I just started to work on calls to a php file which is present in a different server. I am aware of CORS which is essential for cross domain requests. I have been trying to call this file through ajax methods refering to other websites and tutorials and I have seen discussions to find a solution but they are not working for me. Please help.
here is my calling method:
$.ajax({
type: "GET",
url: "http://cs-server.usc.edu:27952/ResponseProg.php?callback=?", //Relative or absolute path to response.php file
datatype: "jsonp",
data: dataInput,
jsonp:'jsoncallback',
crossDomain:true,
success: function(data)
{
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found")
{
var paginate=setPager(0);
$("#pgn").html(paginate);
}
},
error: function() {
$("#rtrn").html("Data not retrieved successfully");
}
});
Here is my PHP code snippet:
<?php
#code for data processing...
$rsltjson = json_encode($result,JSON_UNESCAPED_SLASHES);
echo $_GET['jsoncallback']."(".$rsltjson.");";
?>
I am trying to accomplish this by using JSONP. Should I have any headers?
Are there any errors in my code?....How can I accomplish this? dataInput is the serialized form of form data
The CORS way
You need to put the appropriate header in your php script and output only the JSON:
<?php
header('Access-Control-Allow-Origin: *');
// rest of the code
// output JSON only
echo $rsltjson;
?>
Then using a XMLHttpRequest/ajax call should retrieve the data just fine as JSON without resorting to JSONP.
Mozilla has plenty to read about it
The JSONP way
Since the whole point of JSONP is to bypass cross-domain restrictions, calling a JSONP resource with XMLHttpRequest/ajax, a method in which cross-domain security is fully applied (presumably), is completely useless.
JSONP works by injecting code directly into your page, calling a function that you defined, which is why a JSONP url takes an argument. Therefore, the correct way to call your JSONP url is this:
<script>
function myDataFunc(data) {
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found") {
var paginate=setPager(0);
$("#pgn").html(paginate);
}
}
</script>
<script src="http://cs-server.usc.edu:27952/ResponseProg.php?jsoncallback=myDataFunc"></script>
The JSONP url will return something that looks like this:
myDataFunc({"a":"fhsfg","b":"qfdgers","c":"difgij"});
Since it is included as a script, it will be executed directly in your page, calling the function myDataFunc() that you defined earlier.
Also note that your php file use the GET parameter jsoncallback while your javascript calls the url with the parameter callback, which would not work.
Finally, you use jQuery.parseJSON(), which produces this error from your code:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
The reason can be found in the jQuery docs:
jQuery.parseJSON( json )
Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
Passing in a malformed JSON string results in a JavaScript exception being thrown.
Your php script feeds your callback with a JSON object
{"a":"fhsfg","b":"qfdgers","c":"difgij"}
rather than a string representing a JSON object
'{"a":"fhsfg","b":"qfdgers","c":"difgij"}'
Note the surrounding quotes, which makes this data a string. We fix this in php by adding the quotes around the data:
echo $_GET['jsoncallback']."('".$rsltjson."');";
Obviously if your JSON data contains single quotes, you will have to escape them.
Just now I found some code in a webpage which confuses me a lot:
$.ajax({
url: "/foo/bar/save.json",
data: {
key: value
},
type: "POST",
success: function(a) {
//some code
},
error: function(a) {
//some code
},
dataType: "json"
})
I know that it sends data to url using HTTP method POST, if the url is like /foo/bar/save.php or /foo/bar/save then there's no problem, but it ends with .json...
What kind of server-side languages can handle requests sent to a path ended with json?
Does json have any special meanings or is it just the same as .action .do which I can rename as whatever I like?
Thanks!
What kind of server-side languages can handle requests sent to a path ended with json?
Any. There is no need for a server to use file extensions to map URLs onto programs (or files).
Does json have any special meanings
Using it in a URL hints (without even having to make the request) at the data type being returned (instead of how the software used to produce it was written). This is much more useful to people using clients to fetch the data.
What kind of server-side languages can handle requests sent to a path ended with json?
Any kind.
This is just an url, the way it is handled, redirected or rewritten by the server is not shown to the client.
As an example, using a standard apache / php setup, you can have a rewrite rule on the server :
^(.*)\.json $1.php?json=true
and have your content dynamically generated by a php script.
I wasn't 100% how to phrase this question. I have a request to a URL similar to
example.php?miscData=JSON_FILE_NAME
Now JSON_FILE_NAME contains data unique to that file. I've got example.php set-up similar to below
xmlHttpReq.open('GET', strURL, true);
xmlHttpReq.onload = function(e) {
var data = JSON.parse(this.response);
}
xmlHttpReq.send();
The request file has a function to handle the success of the call and is set up as below
function(retData, textStatus, xhr) { }
I expected retData would contain the JSON data {"name":"Dominic"} etc... But it doesn't. what am I doing wrong?
Your server side code from http://pastebin.com/c7h8V9JK is responding with an HTML page, not a JSON response. The code outside of your PHP is nothing but HTML. So naturally, when requesting the page, the server will return the HTML you've put outside of that php script.
Keep in mind, an AJAX request at its most basic is nothing special in terms of sending and receiving data from the server. Imagine that you have another tab open in your favorite tabbed browser, and that tab is navigating to the URL that your AJAX request is navigating to. That's what's going on when you make an AJAX request.
If you're trying to get JSON data from example.php, begin by removing all of the HTML from that file and serialize the data that you're trying to get using a JSON serializer.
encode json using php?
i tried these two codes but it is not functioning.. i only want to ask for the data output from another domain from http://vrynxzent.info/hello.php
first code
$.post("http://vrynxzent.info/hello.php",function(e){
alert(e);
});
second code
alert(askData());
function askData()
{
var strUrlList = "http://vrynxzent.info/hello.php";
var strReply = "";
jQuery.ajax({
url:strUrlList, success:function(html){strReply = html;}, async:false
});
return strReply;
}
is there another way for this? or is it posible to do this? i want the "Hello World!" output to store in a variable in javascript..
Same old same origin policy.
The most common way to solve this is to do query in back-end (php in your case). I.e., browser sends ajax request to your host, which sends requests to other domain, receives response and sends it back to browser.
There're also some options if you own that other domain. JSONP, for example.
edit
Forgot to tell, this jquery plugin allows cross-domain requests through YQL. Tried myself.
http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
It doesn't work in all cases (in particular, if webmaster has banned robots from his site), but it's still fairly simple and usable.
Because of same origin policy you cannot make ajax requests like this to some other domain,.
i would suggest using a proxy in between,.
for that what you have to do is have a script proxy.php on your own domain and then your ajax request will be
$.post( 'proxy.php' )
then proxy.php would send a request to http://vrynxzent.info/hello.php using curl and send you back the response
By default this does not work because of the "Same Origin Policy."
There are workarounds... see: http://www.ajax-cross-domain.com/