Unable to parse the json from url - javascript

<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
async: false,
contentType: "application/json",
url: "http://www.XXX.XXX.in/api/categories",//url:"dir/categories",
dataType: "jsonp", //dataType: "jsonp",
success: function (data) {
$.each(data, function(i,data) {
var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
$(det).appendTo("#display");
//alert(det);
});
alert(data);
},
error: function (data) {
alert("this is error "+data);
}
});
});
</script>
<div id="display"></div>
</body>
</html>
In the above code I am trying to access the categories json and print the details.
I am doing it in two ways:
I have kept the categories file in dir/ folder and accessing it which shows me result properly.
When I try to access it online it gives me an error:
When I give dataType:"json" instead of jsonp I gives following error:
OPTIONS http:// XXX.XXX.in/api/categories 404 (Not Found)
XMLHttpRequest cannot load http:// XXX.XXX.in/api/categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost:8080' is therefore not allowed access.
I dont know whether the server has cross platform ref. added.

You can't access data of another domain from your domain using JAVASCRIPT. It is a security rule known as the "Same origin Policy"
So, to get data of another domain, you could write server side script (maybe in PHP or some other language you're familiar with.), then you can make ajax request from your script to the server.
The same origin policy is enforced by the browser to protect websites from other websites making xhr requests and displaying their content as if it was their own.
So site A.com cannot connect to B.com with XHR or:
http://A.com cannot connect to http://sub.A.com
localhost:80 cannot connect to localhhost:8080
Edit
As you requested, here is the solution using PHP script.
get_json_from_url.php
<?php
header("Content-type: text/json");
$response = fopen('http://www.eazydial.logicengine.in/api/categories', "rb");
echo stream_get_contents($response);
?>
HTML page
<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "get_json_from_url.php",
dataType: "json",
success: function (data) {
$.each(data, function(i,data) {
var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
$(det).appendTo("#display");
});
console.log(data); //alert can't print [object] so always use console.log() to inspect object and it values. (see output in browser console)
},
error: function (data) {
console.log("Err:");
console.log(data);
}
});
});
</script>
<div id="display"></div>
</body>
</html>
The solution provided here in PHP script will work only for GET request method. If you want to use POST request for any API then look for cURL library to get data from api.

Related

create javascript file for use on different servers

I want to create a JS file that others can include on their websites so they can reference the functions which access my db using an api similar to the facebook like button which shows the total liked and who of your friends like the page. What I've been doing as part of my testing is the following:
JS file
function getItemRating(id){
var result = "";
$.ajax({
type: "POST",
url: "http://siteurl.com/api/rating.php",
data: {i : id},
dataType: "json",
async: false,
success: function(data) { // callback for successful completion
result = data;
},
error: function() { // callback if there's an error
result = 'error';
}
});
return result;
}
Reference file includes:
header("Access-Control-Allow-Origin: *");
and on the other server I've tried a few ways including:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="www.siteurl.com/api/rating-file.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var result = getItemRating(1);
console.log(result);
});
</script>
</head>
<body></body>
</html>
But currently I'm getting the error in console:
VM133:1 Access to XMLHttpRequest at 'http://siteurl.com/api/rating.php' from origin 'http://otherurl.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
siteurl.com = my server where the js file (with function) is located
otherurl.com = different server that the html including the js is located
The error message tells you that the problem is with the response to the preflight request, but you shouldn't be triggering one in the first place.
Remove:
contentType: "application/json; charset=utf-8",
because:
It is a lie. You aren't POSTing JSON in your GET request.
Setting the content-type to that value triggers a preflight request.

Get html file from a given url using javascript($ajax)

var $ = require('jquery');
$.ajax({
type:"GET",
dataType: 'html',
url: 'http://www.google.com/',
success: function(res){
console.log(res);
}
});
I am getting this error in the console:
XMLHttpRequest cannot load http://www.google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
What can I do to avoid this error? Please help.
If you control the backend, you can proxy this request to the backend, i.e. using PHP:
// get.php
echo file_get_contents($_GET['url']);
// frontend JS
$.ajax({
type:"GET",
dataType: 'html',
url: '/get.php?url=http://www.google.com/',
success: function(res){
console.log(res);
}
});
PHP will be able to fetch the data, as it's not checking CORS.
You cannot send cross origin requests because it is a security vulnerability.
Its because google.com goes not have cross origin requests enabled. If you try a site that does like for example:
$.ajax({
type:"GET",
dataType: 'html',
url: 'https://cors-test.appspot.com/test',
success: function(res){
console.log(res);
}
});
Then you will get the desired result
I think this is because of security problem while fetching another domain.
Please check this
"No 'Access-Control-Allow-Origin' header is present on the requested resource"

Uncaught SyntaxError: Unexpected token < in <!DOCTYPE html>

i am sending a ajax request to external domain. Here is my code,
There might be an issue on JSONP response while converting the html data to jsonp. I have tried so many solution because i am requesting to cross domain so i have to use JSONP else i have to face cross domain error. Error when Use simple JSON ERROR: " XMLHttpRequest cannot load http://www.blink.com.kw/search-result.aspx?text=apple&searchfor=all. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:49324' is therefore not allowed access."
Response error:
Uncaught SyntaxError: Unexpected token <
<script type="text/javascript">
$(document).ready(function(){
$("#bt").click(function(){
$.ajax({
type: 'GET',
url: 'http://www.blink.com.kw/search-result.aspx?text=apple&searchfor=all',
dataType: 'jsonp',
success: function (data) {
console.log(data);
//$("#data").html(data);
}
});
});
});
</script>
This is probably happening because you are specifying it as JSONP, which executes the data as a script in order to execute a callback function. If it sends back a normal HTML document with the doctype being the first line it sees, this would occur.
Try this code, basically we should not use url like this.
Also, this url is not return any json or jsonp format, please check your link as well
<script type="text/javascript">
$(document).ready(function(){
$("#bt").click(function(){
$.ajax({
type: 'GET',
url: 'http://www.blink.com.kw/search-result.aspx',
dataType: 'jsonp',
data:{
text: apple,
searchfor: all
}
success: function (data) {
console.log(data);
}
});
});
});
</script>
Hope this helps :)

Strange javascript / json error after server migration

I have a website hosted on server A that sends a request to a website on server B.
The website on server B has recently seen moved to another server. Lets call that server C.
Since the server migration the information that gets requested is not longer being displayed on server A.
The javascript that server A uses to send the request can be seen below:
<script type="text/javascript">
jQuery(document).ready(function() {
var ppUrl = 'http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=jsonp1372412035546&_=1372412036723';
jQuery.getJSON(ppUrl, function(data) {
jQuery('.ipPopularPosts').append(data.content);
});
});
</script>
Interestingly, if you put the request URL into a broswer, it dislays the correct information.
http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=jsonp1372412035546&_=1372412036723
But when the website requests this information, I get the following javascript errors:
Resource interpreted as Script but transferred with MIME type text/html: "http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=jsonp1372416916349&_=1372416917575". jquery.js:3501
Uncaught SyntaxError: Unexpected token < index.php:1
The error above relates to line 1 on index.php which can be seen below:
<script type="text/javascript">window.jQuery || document.write("<script src='http://www.nowgamernetwork.com/js/libs/jquery-1.5.1.min.js'>\x3C/script>")</script>
For some reason, Server A doesn't like the fact that the response it is getting from server C starts with a '<'.
How can I fix this problem?
Any help would be appreciated!
use &callback=?' in the url
dataType: 'jsonp'
(function($) {
var url = 'http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
$(document.body).html(json.content)
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
<script src='http://www.nowgamernetwork.com/js/libs/jquery-1.5.1.min.js'>\x3C/script>
See the problem?
Fixed it.
The PHP script on server C was using 'ob_get_contents' to pull all of the html into a json format. I noticed ob_start was missing so I added that and it now returns that data in the correct format.
For some reason server B didn't require ob_start to make it work.

API call over jQuery

I'm trying to build a .js file that sends data to an external API, waits for a response and interprets the results. The external API is XML-based and accepts an HTTPS Post with the XML as body (content-type; text/xml). I can call the API correctly via cURL.
This is what I have so far:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body onload="CallService()">
<script type="text/javascript">
var webServiceURL = 'https://www.url.com';
var xmlString = '<xml><parameter1>value1</parameter1>
<parameter2>value2</parameter2></xml>';
function CallService() {
$.ajax({
url: webServiceURL,
type: "POST",
dataType: "xml",
data: xmlString,
processData: false,
contentType: "text/xml; charset=\"utf-8\"",
success: OnSuccess,
error: OnError
});
return false;
}
function OnSuccess(data, status) {
alert(data.d);
}
function OnError(request, status, error) {
alert('error');
}
$(document).ready(function() {
jQuery.support.cors = true;
});
</script>
</body>
</html>
When I open the HTML I get an alert saying "error" and nothing appears on the other end (the external API's). Is there a way to do this using just JavaScript/Ajax/jQuery or do I need a "supporting" code that receives the JS call?
When you want to make cross domain queries, you have basically 3 types of solution :
1) use JSONP, which won't interest you if you're using XML and not JSON
2) not really do cross-domain, by setting a kind of proxy (or any type of get) on the server serving the main html page
3) changing headers on the server to specify to the browser that you accept cross-domain queries. This is new but yet accepted by all major browsers. That's called CORS. It's easy to change the headers ("Access-control-...") in all server-side languages so that should now be the preferred way (if you have issues (security, rights, bandwidth, ad, etc.) with cross-domain access to the data you serve, you can restrain the allowed origins).

Categories

Resources