How to integrate CORS, Google Blog and JavaScript? - javascript

I have a working JavaScript on a web page that gets my blog from a blog site and displays it in a sidebar on my web page. In other words I blog in one place, but also display my blog content in another place (my web page).
The script uses Cross Origin Sharing (CORS) and looks like this:
$(
function () {
$.get(
'http://www.corsproxy.com/my_name.soup.io/rss/original',
function (data) {
var items = data.getElementsByTagName('item');
var thoughts = $('#activity ul');
var count = 0;
$(items).each(function (i, e) {
count++;
if (count > 10) return;
thoughts.append('<li>'
+ e.getElementsByTagName('description')[0].textContent
+ '<small>'
+ $.timeago( new Date(e.getElementsByTagName('pubDate')[0].textContent) )
+ '</small></li>');
});
}, 'xml'
);
}
);
I want to move my blog to Google blogging and have an account URL that looks like this: http://my_name.blogspot.com/feeds/posts/default
But I think I still need to invoke CORS so that the JavaScript on the web site can cross domains to the Google site. I have tried using the Google URL directly but the script does not get the content.
How should I change the JavaScript so that my web page running the JavaScript will display the content from the Google blog?
As an aside: using the same JavaScript, I am able to display content (the title of the commit) from my Github account on my web page. In this case I do not use CORS; the following JavaScript works as expected:
$.getScript(
'/public/bin/jquery.timeago.js',
function () {
$.getScript(
'/public/bin/jquery.github-activity.js',
function () {
$("#gh-activity ul").githubActivityFor("my_name", { limit: 10 });
}
);
}
);
Why does the Github get work without using CORS?
Can I reconfigure the get for the Google blog to act in the same way as get for my Github account?

Examining the code for the githubActivityFor call, we see:
$.get('https://api.github.com/users/' + username + '/events?callback=?', function(activity) {
...
},
"jsonp");
The "jsonp" argument tells jQuery that that JSONP is being used here, and the resource should be loaded inside of <script> tag instead of fetched with Ajax. Sure enough, we we actually look at a user's activity feed from that URL template, it's a script. jQuery can therefore perform a JSONP script load in the usual way:
storing the callback function (i.e., the second argument) in a variable with a random, long name like jQuery35758395
replacing the ? in callback=? with the same value (e.g., jQuery35758395)
loading the script resource in a <script> tag
The Github resource (like any traditional JSONP server-side endpoint) is set up to use value of the callback parameter in a function call in the beginning of the script (e.g., jQuery35758395({ 'some': 'data' }). When script runs, the function call is executed, and it triggers the randomly-named callback we set up before the fetch.
Turns out Blogger supports JSONP on their server already. If you visit http://foobar.blogspot.com/feeds/posts/default?callback=foobaz you'll see the feed data wrapped inside of a function call. To take advantage of this, simply perform your $.get with a callback=? parameter:
$.get(
'http://my_name.blogspot.com/feeds/posts/default?callback=?',
function (data) {
...
},
"jsonp");
This will automatically do JSONP behind the scenes and correctly invoke your callback function with the XML string. Unfortunately, the string won't be parsed into a DOM structure for you already, but the jQuery function (a.k.a., $) can parse the data string for you:
var feedDOM = $(data).get(1);
The get call pulls the DOM structure out of the jQuery object, but you can also keep it in the jQuery object and use jQuery functions to examine it. Alternatively, you can supply the XML string as a context argument for a jQuery selector:
var authorTags = $("author", data);

Related

Cannot carry out Ajax request from wikipedia

I want to use wikipedia API in my project to grab images of people, but fail. I use this url:https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100
When i console browser says the following
Refused to execute script from 'https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albe…Callback&callback=jQuery22409288979864744966_1470068280411&_=1470068280412' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
My code
var general = {
// The URL to the quote API
url: 'http://api.forismatic.com/api/1.0/',
// What to display as the author name if s/he's unknown
unknownAuthor: 'Uknown',
// Base URL for the tweet links generation
tweetURL: 'http://twitter.com/home?status=',
wikiURL:'https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albert Einstein&pithumbsize=100&callback=wikiCallback'
};
var wikirequest = function() {
$.ajax({
url:general.wikiURL,
dataType: 'jsonp',
success: function(wikData) {
console.log(wikData);
//var image = wikiData.
displayQuote(image);
} // end of success
});
}// wikirequest
wikirequest();
Pen
Has anyone met the same issue?
You are trying to load the data using JSONP, but you are making a request to a URL that returns an HTML document. JSONP requests have to be answered with JavaScript programs (since that is a fundamental feature of how they work … and also why they are dangerous and should be avoided in favour of plain JSON and CORS).
To make it return JSONP you need to provided two additional query string parameters:
format=json
callback=YourCallbackName
… where YourCallbackName is the name of the function that should be executed and passed the data you are fetching as an argument. Most Ajax libraries will generate that name (and the function itself) dynamically when you specify callback=?.
https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json
You are missing the &format=json on the URL - The page was displaying the data with the html header and you would have been attempting to decode this. The above answer is actually better.

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

send a javascript request to another domain and get the response - not in jsonp

i am really banging my head here for more then a day, i am trying to send a request and get the response from another site. i'm doing it with jsonp (from the obvious reason). but the response is not a JavaScript function definition, so it keeps failing.
can anyone in this planet help me get the response the right way.
i attached the code i wrote, again: because the response is not in json it's not working. (try to run it yourself and you'll see).
any suggestions?
<script>
function test()
{
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: 'https://www.facebook.com/ajax/typeahead/first_degree.php?viewer=1000009843914&token=1-1&filter[0]=user&options[0]=pending_request&lazy=1&token=v7&stale_ok=1&__a=1&__user=1000009843914& viewer=1000009843914',
});
}
function jsonp_callback(data)
{
var val=JSON.stringify(data);
myString = val.slice( 11 );
$('#container').html(myString);
/*for (;;);*/
}
test();
</script>
The server must be programmed to include the JSONP callback within its script file. If it only knows to return JSON, it will have no effect when the dynamic script tag is inserted into the page since JSON can at most provide an object--but it won't go anywhere unless the same file calls the function. In this way, it is different from Ajax, since a dynamically inserted script tag can only interact with your own code if it knows to call one of your functions. Just as an example, it might return:
jsonp_callback({facebooKData:[...]});
You should investigate how the Facebook API supports JSONP (not just JSON) for whatever you are trying to do. Typically APIs will accept a "callback" variable to determine which callback function it should use (which jQuery handles for you).

How to pass data from one HTML page to another HTML page using JQuery?

I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.
session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?
Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page
Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
Next, inside your success handler function:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).
Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.
You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.

Write jquery.ajax from existing javascript

I found this article:
http://msdn.microsoft.com/en-us/library/dd251073.aspx
How could I write 'get' request using jquery.ajax?
You could use the .get() method.
http://api.jquery.com/jQuery.get/
Or just use the regular $.ajax() method (http://api.jquery.com/jQuery.ajax/), which defaults to a GET request.
It depends on whether Bing's API respects the standard ?callback=function method for specifying JSONP callbacks, but if so, then this simplified version of the Search() function should do it:
// Bing API 2.0 code sample demonstrating the use of the
// Spell SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=Mispeling words is a common ocurrence."
+ "&Sources=Spell"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Options=EnableHighlighting"
$.getJSON(requestStr, SearchCompleted);
}
Keep in mind that neither approach is directly triggering a GET, like you might be used to in AJAX requests to a local server using XMLHttpRequest.
To circumvent the cross-domain restriction on XHR, JSONP works by injecting a new script element into your document which then causes the browser to load (via GET) and execute that remote script. That remote script's contents are a single function call to your callback function, with the entire JSON payload as its parameter.
If that doesn't work, including those Bing-specific callback options should work fine in conjunction with jQuery:
// Bing API 2.0 code sample demonstrating the use of the
// Spell SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=Mispeling words is a common ocurrence."
+ "&Sources=Spell"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Options=EnableHighlighting"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
$.getJSON(requestStr);
}
Keep in mind that, at this point (and somewhat before), you aren't really using jQuery itself for much at all. Even though $.getJSON() or $.ajax() or $.get() seem like they're doing something more powerful than the MSDN example, jQuery is going to do exactly the same thing in this case (inject a script element with its srcpointed at requestStr).

Categories

Resources