Strange javascript / json error after server migration - javascript

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.

Related

Wikipedia API. File not found Error

I'm trying to make a wikipedia search bar. The idea is to send a new AJAX request every time search input is changed. I'm using https://www.mediawiki.org/wiki/API:Search_and_discovery as a guideline.
var search = $('#search');
search.keyup(function() {
if (search.val() === '') {
result.html('');
}
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: search.val()
},
dataType: 'jsonp',
success: function(response) {
console.log("success!");
}
});
});
However, success function is not even triggered.
On any keypress the error I get is this ("d" pressed):
jquery-2.1.1.min.js:4 GET file://en.wikipedia.org/w/api.php?>callback=jQuery21107844703783826772_1484403407494&action=query&list=search&srse>arch=d&format=json&_=1484403407495 net::ERR_FILE_NOT_FOUND
Thank you in advance for any help or guidance!
Well, you're probably trying to do a AJAX request without a local server (opening your file directly in the browser).
First of all, your url options starts with //en... (without the protocol). It indicates that it'll construct your full url using the same protocol you're using. In this case: file://. That's because your browser is trying to reach file://en.wikipedia.org/....
So, you can set your url to https://en.wikipedia.org/w/api.php to make it work.
Just replace:
url: '//en.wikipedia.org/w/api.php',
with:
url: 'https://en.wikipedia.org/w/api.php',
Looks like you're running it from a simple html file located in your filesystem, in other words not running it from a web server (even local).
Try calling the api with
url: 'https://en.wikipedia.org/w/api.php'
or run the file from a web server (can be a local one).

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

Using JSONP with flaskr and javascript

I'm using Flaskr to generate data via a RESTful API. My call looks like:
http get localhost:5000/v1.0/dataset dataset_id==f7e7510b3c1c4337be339446ca000d22
and returns something like:
{"sites": "a"}
Now I'm tring to fetch this data with my web app. I first ran into a cross-domain error, but after some reading, found out that I could by-pass that error by using jsonp. Basically copying a piece of code I found here, I put this together (I'm new to JavaScript):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
(function($) {
var url = 'http://localhost:5000/v1.0/dataset?dataset_id=f7e7510b3c1c4337be339446ca000d22&callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.sites);
},
error: function(e) {
console.log(e.message);
$('#data').html('the error was thrown');
}
});
})(jQuery);
</script>
</head>
<body>
<div id = 'data'></div>
<p> place holder </p>
</body>
and accordingly changed my python response to look like:
"jsonCallback({\"sites\":\"a\"});"
If this helps, my flaskr return line is the following:
return callback_function + '({"sites":"a"});'
I'm fairly confident my python side of the problem is good, but I'm not well versed enough in JS to determine where the error is coming from. My goal is to simply display my data on the page.
I'm not sure what's not working with your code. Because you haven't written any error message or what happens when your code runs.
Any way the following script does a JSONP request to http://jsonplaceholder.typicode.com/users/1/todos service and returns one todo item. I have used this only to have a service that returns some data.
If you are going to the developer console in your browser to network and click on the request to the rest service you'll see under response that jQuery is adding a callback to the JSON so you don't need to add it in your URL.
See the following screenshot. (The screenshot is from Firefox.)
I have added a working ajax example below. If you prefer jsFiddle, you'll find the same example here.
(function ($) {
//var url = 'http://localhost:5000/v1.0/dataset?dataset_id=f7e7510b3c1c4337be339446ca000d22';
var url = 'http://jsonplaceholder.typicode.com/todos/1'; // dummy url
var jsonCallback = function (data) {
console.log(data);
$('#data').html(JSON.stringify(data, null, 2));
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>

Rails: Get remote page via ajax

I use Rails3 and I try to get remote page via ajax. (https://play.google.com/store/apps/details?id=).
$.ajax({
url: app_url,
type: 'GET',
data: "id=<id>",
crossDomain : true,
dataType: 'jsonp',
success: function ( code ) {
alert("Good.");
}
});
When I run the script, the I see: "Uncaught SyntaxError: Unexpected token < " error message.
By the way, I tried do it as:
$.ajax({
url: app_url,
type: 'GET',
data: "id=<id>",
crossDomain : true,
dataType: 'jsonp',
success: function ( code ) {
alert("Good.");
}
});
But I see "Origin http://example.com:3000 is not allowed by Access-Control-Allow-Origin." error message.
How can I fix the error and get the page ?
Thanks.
If you are trying to access remote pages via AJAX, that page may be blocking your request. The error message would suggest this: https://developer.mozilla.org/en-US/docs/HTTP_access_control
EDIT
For clarity, Access-Control-Allow-Origin is the server setting which "origins" are allowed to retrieve from it. You could possibly grab this page server-side, and depending on google's level of security, you may have to spoof a browser. PHP CURL comes to mind. You would then set up an ajax call to your server script, your server would go get the page for you, then return it to you ajax call.

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