GAPI Client 404 Error - javascript

I am trying to authorize a google account with this code, and the client.js file does not work
The error is in line 2.
I think the // starts a comment so the entire line is not read properly?? How do I fix this?
var gapi=window.gapi=window.gapi||{};gapi._bs=new Date().getTime();(function(){var f=null,g=window,h="push",i="replace",k="length";var m=g,r=document,u=m.location,w=function(){},x=/\[native code\]/,A=function(a,b,c){return a[b]=a[b]||c},C=function(a){for(var b=0;b<this[k];b++)if(this[b]===a)return b;return-1},D=function(){var a;if((a=Object.create)&&x.test(a))a=a(f);else{a={};for(var b in a)a[b]=void 0}return a},E=A(m,"gapi",{});var F;F=A(m,"___jsl",D());A(F,"I",0);A(F,"hel",10);var G=function(){var a=u.href,b;if(F.dpo)b=F.h;else{b=F.h;var c=RegExp("([#].*&|[#])jsh=([^&#]*)","g"),e=RegExp("([?#].*&|[?#])jsh=([^&#]*)","g");if(a=a&&(c.exec(a)||e.exec(a)))try{b=decodeURIComponent(a[2])}catch(d){}}return b},I=function(a){return A(A(F,"H",D()),a,D())};var J=A(F,"perf",D()),L=A(J,"g",D()),M=A(J,"i",D());A(J,"r",[]);D();D();var N=function(a,b,c){var e=J.r;"function"===typeof e?e(a,b,c):e[h]([a,b,c])},P=function(a,b,c){b&&0<b[k]&&(b=O(b),c&&0<c[k]&&(b+="___"+O(c)),28<b[k]&&(b=b.substr(0,28)+(b[k]-28)),c=b,b=A(M,"_p",D()),A(b,c,D())[a]=(new Date).getTime(),N(a,"_p",c))},O=function(a){return a.join("__")[i](/\./g,"_")[i](/\-/g,"_")[i](/\,/g,"_")};var Q=D(),R=[],S;S={a:"callback",g:"sync",e:"config",c:"_c",d:"h",l:"platform",i:"jsl",TIMEOUT:"timeout",f:"ontimeout",k:"mh",j:"u"};R[h]([S.i,function(a){for(var b in a)if(Object.prototype.hasOwnProperty.call(a,b)){var c=a[b];"object"==typeof c?F[b]=A(F,b,[]).concat(c):A(F,b,c)}if(b=a[S.j])a=A(F,"us",[]),a[h](b),(b=/^https:(.*)$/.exec(b))&&a[h]("http:"+b[1])}]);var T=decodeURI("%73cript");Q.m=function(a){var b=F.ms||"https://apis.google.com";a=a[0];var c;if(!(c=!a))c=0<=a.indexOf("..");if(c)throw"Bad hint";return b+"/"+a[i](/^\//,"")};
var U=function(a){return a.join(",")[i](/\./g,"_")[i](/-/g,"_")},W=function(a,b){for(var c=[],e=0;e<a[k];++e){var d=a[e];d&&0>C.call(b,d)&&c[h](d)}return c},aa=/^[\/_a-zA-Z0-9,.\-!:=]+$/,ba=/^https?:\/\/[^\/\?#]+\.google\.com(:\d+)?\/[^\?#]+$/,ca=/\/cb=/g,da=/\/\//g,X=function(a){var b=r.createElement(T);b.setAttribute("src",a);b.async="true";(a=r.getElementsByTagName(T)[0])?a.parentNode.insertBefore(b,a):(r.head||r.body||r.documentElement).appendChild(b)},Z=function(a,b){var c=b||{};"function"==
typeof b&&(c={},c[S.a]=b);var e=c,d=e&&e[S.c];if(d)for(var j=0;j<R[k];j++){var l=R[j][0],n=R[j][1];n&&Object.prototype.hasOwnProperty.call(d,l)&&n(d[l],a,e)}e=a?a.split(":"):[];if(!(d=c[S.d]))if(d=G(),!d)throw"Bad hint";j=d;l=A(F,"ah",D());if(!l["::"]||!e[k])Y(e||[],c,j);else{d=[];for(n=f;n=e.shift();){var q=n.split("."),q=l[n]||l[q[1]&&"ns:"+q[0]||""]||j,v=d[k]&&d[d[k]-1]||f,y=v;if(!v||v.hint!=q)y={hint:q,b:[]},d[h](y);y.b[h](n)}var B=d[k];if(1<B){var z=c[S.a];z&&(c[S.a]=function(){0==--B&&z()})}for(;e=
d.shift();)Y(e.b,c,e.hint)}},Y=function(a,b,c){var e=a.sort();a=[];for(var d=void 0,j=0;j<e[k];j++){var l=e[j];l!=d&&a[h](l);d=l}a=a||[];var n=b[S.a],q=b[S.e],d=b[S.TIMEOUT],v=b[S.f],y=f,B=!1;if(d&&!v||!d&&v)throw"Timeout requires both the timeout parameter and ontimeout parameter to be set";var e=A(I(c),"r",[]).sort(),z=A(I(c),"L",[]).sort(),H=[].concat(e),V=function(a,b){if(B)return 0;m.clearTimeout(y);z[h].apply(z,p);var d=((E||{}).config||{}).update;d?d(q):q&&A(F,"cu",[])[h](q);if(b){P("me0",
a,H);try{$(function(){var a;a=c===G()?A(E,"_",D()):D();a=A(I(c),"_",a);b(a)})}finally{P("me1",a,H)}}n&&n();return 1};0<d&&(y=m.setTimeout(function(){B=!0;v()},d));var p=W(a,z);if(p[k]){var p=W(a,e),s=A(F,"CP",[]),t=s[k];s[t]=function(a){if(!a)return 0;P("ml1",p,H);var b=function(){s[t]=f;return V(p,a)};if(0<t&&s[t-1])s[t]=b;else for(b();(b=s[++t])&&b(););};if(p[k]){var K="loaded_"+F.I++;E[K]=function(a){s[t](a);E[K]=f};a=c.split(";");a=(d=Q[a.shift()])&&d(a);if(!a)throw"Bad hint:"+c;d=a=a[i]("__features__",
U(p))[i](/\/$/,"")+(e[k]?"/ed=1/exm="+U(e):"")+("/cb=gapi."+K);j=d.match(da);l=d.match(ca);if(!l||!(1===l[k]&&ba.test(d)&&aa.test(d)&&j&&1===j[k]))throw"Bad URL "+a;e[h].apply(e,p);P("ml0",p,H);b[S.g]||m.___gapisync?(b=a,"loading"!=r.readyState?X(b):r.write("<"+T+' src="'+encodeURI(b)+'"></'+T+">")):X(a)}else s[t](w)}else V(p)};var $=function(a){if(F.hee&&0<F.hel)try{return a()}catch(b){F.hel--,Z("debug_error",function(){g.___jsl.hefn(b)})}else return a()};E.load=function(a,b){return $(function(){return Z(a,b)})};L.bs0=g.gapi._bs||(new Date).getTime();N("bs0");L.bs1=(new Date).getTime();N("bs1");delete g.gapi._bs;})();
gapi.load("client",{callback:window["gapi_onload"],_c:{"jsl":{"ci":{"services":{},"deviceType":"desktop","lexps":[69,100,71,96,97,79,74,45,17,86,82,92,94,61,90,30],"inline":{"css":1},"report":{},"oauth-flow":{"authUrl":"https://accounts.google.com/o/oauth2/auth","proxyUrl":"https://accounts.google.com/o/oauth2/postmessageRelay"},"isPlusUser":true,"iframes":{"additnow":{"methods":["launchurl"],"url":"https://apis.google.com/additnow/additnow.html?bsv"},"plus":{"methods":["onauth"],"url":":socialhost:/u/:session_index:/_/pages/badge?bsv"},":socialhost:":"https://plusone.google.com","plus_followers":{"params":{"url":""},"url":":socialhost:/_/im/_/widget/render/plus/followers?bsv"},"recobox":{"params":{"url":""},"url":":socialhost:/:session_prefix:_/widget/render/recobox?bsv"},"autocomplete":{"params":{"url":""},"url":":socialhost:/:session_prefix:_/widget/render/autocomplete?bsv"},"plus_share":{"params":{"url":""},"url":":socialhost:/:session_prefix:_/+1/sharebutton?plusShare\u003dtrue\u0026bsv"},"savetowallet":{"url":"https://clients5.google.com/s2w/o/savetowallet?bsv"},"plus_circle":{"params":{"url":""},"url":":socialhost:/:session_prefix:_/widget/plus/circle?bsv"},"hangout":{"url":"https://talkgadget.google.com/widget/go?bsv"},"savetodrive":{"methods":["save"],"url":"https://drive.google.com/savetodrivebutton?bsv"},"card":{"url":":socialhost:/:session_prefix:_/hovercard/card?bsv"},"evwidget":{"params":{"url":""},"url":":socialhost:/:session_prefix:_/events/widget?bsv"},":signuphost:":"https://plus.google.com","plusone":{"preloadUrl":["https://ssl.gstatic.com/s2/oz/images/stars/po/Publisher/sprite4-a67f741843ffc4220554c34bd01bb0bb.png"],"params":{"count":"","size":"","url":""},"url":":socialhost:/:session_prefix:_/+1/fastbutton?bsv"}},"debug":{"host":"https://plusone.google.com","reportExceptionRate":0.05,"rethrowException":true},"csi":{"rate":0.0},"googleapis.config":{"mobilesignupurl":"https://m.google.com/app/plus/oob?"}},"h":"m;/_/scs/apps-static/_/js/k\u003doz.gapi.en.vHd7LY8Dlg8.O/m\u003d__features__/am\u003dQQ/rt\u003dj/d\u003d1/rs\u003dAItRSTO5p_m_dG1ldcl9bjOI8CWzKtU0Fw","u":"https://apis.google.com/js/client.js","hee":true,"fp":"83f9c596ff17d5bcc310163eb7a2861e8b3d7915","dpo":false},"fp":"83f9c596ff17d5bcc310163eb7a2861e8b3d7915","annotation":["autocomplete","profile"],"bimodal":[]}});

It's maybe a little late but the simplest way to authorize your user on Google is using OAuth.io.
There is a blog post which describe the authorization on Google plus with OAuth.io.
And the good news, you'll be able to make it in the same way with Twitter, Facebook and 90 others providers.
OAuth.popup('Google_plus', function(err, res) {
// you can use res.access_token to get the Access Token
res.get('/v1/people/me').done(function(data) {
alert('Hello ' + data.displayName)
})
})

Related

Thousands facebook ip visits a day trigger js error (TypeError: Illegal invocation)

Since May 12th our website gets more than 2000 visits a day that always trigger a js error (in our case TypeError: Illegal invocation) with the following characteristics:
referrer is http://m.facebook.com
all ips are registered to facebook
user agent is an iPhone 99.9% of the time, reported screen size is 2000x2000
We'd like to resolve this error but we are not able to find the reason of these sudden visits. If it's a facebook bot or crawler it's not using the correct user agent, on the other hand if it's real users we don't understand why the visits trigger a js error and point to ips registered to facebook.
Unfortunately I didn't get an answer at https://developers.facebook.com
If anyone can help with that would be appreciated
Example ips:
31.13.114.53, 173.252.124.54, 173.252.84.115, 66.220.151.89, 173.252.84.86, 66.220.151.178, 66.220.151.90, 31.13.114.117, 173.252.92.114, 173.252.99.252, 69.171.240.18, 173.252.84.92, 69.171.224.213, 69.171.240.252, 69.171.240.23, 173.252.98.119, 173.252.90.170, 66.220.151.180, 66.220.156.22, 31.13.113.198, 173.252.84.88, 173.252.92.113, 173.252.124.57, 69.171.240.16, 69.171.240.17, 173.252.91.252, 31.13.114.50, 31.13.114.48, 66.220.156.23, 173.252.84.89, 173.252.99.17, 173.252.84.55, 31.13.113.192, 69.171.240.22, 66.220.156.60, 173.252.122.60, 66.220.156.18, 31.13.114.114, 31.13.114.119, 173.252.84.56, 173.252.122.54, 69.171.240.20, 173.252.123.183, 173.252.99.246, 173.252.92.244, 173.252.98.28, 31.13.113.195, 66.220.151.93, 66.220.156.16, 66.220.156.19, 66.220.156.17, 173.252.88.118, 173.252.127.23, 69.171.251.10, 173.252.121.118, 31.13.114.116, 31.13.114.146, 173.252.98.114, 173.252.98.117, 66.220.156.20, 173.252.98.27, 31.13.114.6, 31.13.113.197, 173.252.122.57, 69.171.240.21, 173.252.98.112, 173.252.123.182, 173.252.99.20, 173.252.92.116, 66.220.156.55, 66.220.156.150, 173.252.123.181, 31.13.114.51, 173.252.93.19, 173.252.91.251, 31.13.114.49, 173.252.98.86, 173.252.91.247, 173.252.84.91, 173.252.92.117, 173.252.84.116, 66.220.151.86, 66.220.148.169, 69.171.224.249, 31.13.113.194, 173.252.85.26, 66.220.156.145, 31.13.113.180, 31.13.111.90, 173.252.91.248, 173.252.91.250, 69.171.240.247, 173.252.92.241, 173.252.92.118, 173.252.99.23, 173.252.124.120, 173.252.122.59, 173.252.98.26, 173.252.99.52, 66.220.156.146, 31.13.114.12, 66.220.148.170, 173.252.93.18, 173.252.92.208, 31.13.113.176, 69.171.224.210, 69.171.224.211, 173.252.84.113, 31.13.111.84, 31.13.114.52, 69.171.240.248, 173.252.99.189, 173.252.99.183, 31.13.114.208, 69.171.240.251, 69.171.240.253, 173.252.92.115, 31.13.114.112, 173.252.122.58, 173.252.85.27, 173.252.98.80, 173.252.124.122, 173.252.98.25, 173.252.84.87, 66.220.151.208, 31.13.114.145, 173.252.98.85, 173.252.98.84, 69.171.224.214, 69.171.224.209, 173.252.85.25, 66.220.156.56, 66.220.151.181, 173.252.85.49, 173.252.85.48, 66.220.151.211, 173.252.124.60, 173.252.123.185, 69.171.224.215, 173.252.92.240, 31.13.113.196, 173.252.98.115, 66.220.151.241, 173.252.98.82, 31.13.113.193, 66.220.156.149, 173.252.123.184, 173.252.89.22, 173.252.98.29, 173.252.124.119, 69.171.240.19, 173.252.92.247, 66.220.148.171, 66.220.148.166, 69.171.224.247, 173.252.98.113, 173.252.124.124, 173.252.92.246, 173.252.124.61

Return Youtube video URL from keyword search with Javascript

Alright , so I'm making a bot in Discord for my server, and something I wanted to implement is a youtube command.
I've been searching all over and looking in the Youtube API and all I can find is their search for what seems like a browser
I'm using nodejs to run it off of my laptop, and my bot runs off of discord.jsI have a similar command that does a MAL and a Urban Dictionary search, but I've found nothing and have no idea how to do the same with youtube
I used to have a command for a python bot that was able to due this, and I've seen other Discord bots able to do it as well, so I know it's obviously possible
Basically what I'm saying is I need to be able to search for and return a youtube video URL (the first search result) from a string of search terms so the usage would look like
>>youtube Tunak Tunak Tun
Would return
https://www.youtube.com/watch?v=vTIIMJ9tUc8 , which is the first search result for that keyword(s)
EDIT:I've found the python command that would do this, but have nigh the skills nor the confidence to try to translate this to JavaScript
elif prefix and cmd=="youtube" and len(args) > 0:
try:
yword=args.replace(" ","_")
ydata= urlreq.urlopen("http://gdata.youtube.com/feeds/api/videos?vq="+yword+"&racy=include&orderby=relevance&max-results=1")
yread= str(ydata.read())
if "<openSearch:totalResults>0</openSearch:totalResults>" in yread:
room.message("I got nothin' for ya by the name of "+args)
else:
trash , yclean=yread.split("<media:player url='http://www.youtube.com/watch?v=",1)
yclean , trash=yclean.split("&",1)
room.message("http://http://www.youtube.com/watch?v="+yclean,True)
except:
room.message("Somethin ain't right")
EDIT2 (Apologies for length) : Alright! I've found something that's gotten me a lot closer!
https://www.npmjs.com/package/youtube-search
I've got a command in my bot now that goes something like this:
if (commandIs("yt" , message)){
search(args.join(' ').substring(4), opts, function(err, results) {
if(err) return console.log(err);
message.channel.sendMessage(results);
console.log(results);
});
}
So now when I enter >>yt Tunak Tunak Tun I get
[ { id: 'vTIIMJ9tUc8',
link: 'https://www.youtube.com/watch?v=vTIIMJ9tUc8',
kind: 'youtube#video',
publishedAt: '2014-03-21T07:00:01.000Z',
channelId: 'UC3MLnJtqc_phABBriLRhtgQ',
channelTitle: 'SonyMusicIndiaVEVO',
title: 'Daler Mehndi - Tunak Tunak Tun Video',
description: 'Presenting \'Tunak Tunak Tun\' music video sung by the talented Daler Mehndi Song Name - Tunak Tunak Tun Album - Tunak Tunak Tun Singer - Daler Mehndi ...',
thumbnails: { default: [Object], medium: [Object], high: [Object] } } ]
in the console and [object Object] in the discord channel.
http://i.imgur.com/Vorpn0f.png
So the problem now is I have the link in my reach, but I can not get it to return JUST the link, and I've no idea how to pull it out of that mess.
It sounds like your results object is a JSON string. This essentially means that it is a string representation of a javascript object. You can parse this into an object by using JSON.parse().
var objResults = JSON.parse(results);
console.log(objResults);
console.log(objResults.link);
EDIT
Failed to notice that your result is actually an array. You just need to access it like this: console.log(results[0].link). Shouldn't need to JSON.parse()
Okay, here's another approach that is working for me, using the google javascript API. Once again, the SO snippet doesn't run it, so I'll link you to the fiddle.
This method requires you to setup a google API key, then enable youtube API access.
I've removed my google API key from the fiddle, so you'll need to set that up. I can PM you mine if you want to test first though.
var apiKey = null //put your API key here
function search() {
var searchTerm = $('#txtSearch').val()
gapi.client.init({
'apiKey': apiKey,
'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest']
}).then(function() {
return gapi.client.youtube.search.list({
q: searchTerm,
part: 'snippet'
});
}).then(function(response) {
var searchResult = response.result;
$('#search-results').append(JSON.stringify(searchResult, null, 4))
console.log(searchResult.items[0])
var firstVideo = searchResult.items[0]
firstVideo.url = `https://youtube.com/watch?v=${firstVideo.id.videoId}`
$('#first-video').text(firstVideo.url).attr('href', firstVideo.url)
$('#first-video-title').text(firstVideo.snippet.title)
$('#first-video-description').text(firstVideo.snippet.description)
});
}
$('#btnSearch').on('click', function() {
$('#first-video-title').text("")
if (!apiKey) {
$('#first-video-title').text("You need to set an apiKey!")
return;
}
gapi.load('client', search)
});
#search-results { white-space: pre; font-family: monospace; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='https://apis.google.com/js/api.js'></script>
<div id="container">
<input id="txtSearch" type="text" />
<button id="btnSearch">
Search!
</button>
<br />
<p id='first-video-title'> </p>
<p id='first-video-description'></p>
<a target="_blank" id="first-video"></a>
<div id='search-results'>
</div>
</div>

how can convert string to hash using jquery

list = "{"mins_spent_in_stor":"{"AM 01:00":0,"AM 02:00":0,"AM 03:00":0,"AM 04:00":0,"AM 05:00":0,"AM 06:00":0,"AM 07:00":0,"AM 08:00":0,"AM 09:00":0,"AM 10:00":0,"AM 11:00":0,"PM 12:00":273,"PM 01:00":0,"PM 02:00":30,"PM 03:00":0,"PM 04:00":0,"PM 05:00":0,"PM 06:00":0,"PM 07:00":0,"PM 08:00":0,"PM 09:00":0,"PM 10:00":0,"PM 11:00":0,"AM 12:00":0}","store_hr_opt":"{"00:0C:66:20:0E:3A":{"AM 01:00":0,"AM 02:00":0,"AM 03:00":0,"AM 04:00":0,"AM 05:00":0,"AM 06:00":0,"AM 07:00":0,"AM 08:00":0,"AM 09:00":0,"AM 10:00":0,"AM 11:00":0,"PM 12:00":5,"PM 01:00":0,"PM 02:00":0,"PM 03:00":0,"PM 04:00":0,"PM 05:00":0,"PM 06:00":0,"PM 07:00":0,"PM 08:00":0,"PM 09:00":0,"PM 10:00":0,"PM 11:00":0,"AM 12:00":0}}"}"
I need to convert this string into hash, but when am using this command JSON.parse(list), i'm getting this error
SyntaxError: Unexpected token A,
Please anyone help me..
I got it to work with a couple of replaces:
var list = '{"mins_spent_in_stor":"{"AM 01:00":0,"AM 02:00":0,"AM 03:00":0,"AM 04:00":0,"AM 05:00":0,"AM 06:00":0,"AM 07:00":0,"AM 08:00":0,"AM 09:00":0,"AM 10:00":0,"AM 11:00":0,"PM 12:00":273,"PM 01:00":0,"PM 02:00":30,"PM 03:00":0,"PM 04:00":0,"PM 05:00":0,"PM 06:00":0,"PM 07:00":0,"PM 08:00":0,"PM 09:00":0,"PM 10:00":0,"PM 11:00":0,"AM 12:00":0}","store_hr_opt":"{"00:0C:66:20:0E:3A":{"AM 01:00":0,"AM 02:00":0,"AM 03:00":0,"AM 04:00":0,"AM 05:00":0,"AM 06:00":0,"AM 07:00":0,"AM 08:00":0,"AM 09:00":0,"AM 10:00":0,"AM 11:00":0,"PM 12:00":5,"PM 01:00":0,"PM 02:00":0,"PM 03:00":0,"PM 04:00":0,"PM 05:00":0,"PM 06:00":0,"PM 07:00":0,"PM 08:00":0,"PM 09:00":0,"PM 10:00":0,"PM 11:00":0,"AM 12:00":0}}"}'.replace(/\"\{/g,"{").replace(/}\"/g,"}");
But that is by no means an elegant or good solution and is only likely to work on this particular input and will break if you get any other garbled JSON string.
So you should really fix the source of the data.
http://jsonlint.com/ is a nice tool to quickly check if a JSON is valid.

Grails RemoteFunction creates bad javascript

I am taking over a project from an engineer that left my company, and am having to quickly come up to speed on Grails, so if this is a noob question, well, I'm a noob.
In one of one of my GSP files, I've got a remoteFunction call in the middle of a javaScript function:
function fnCreateEntitiesPerForceChart() {
var interval = $("#entitiesPerForceTimeIntervalSelect").val();
var url = '${createLink(controller: 'federation', action: 'createEntitiesPerForceChart')}?interval='+escape(interval);
$("#entitiesPerForceChart").attr("src", url);
${remoteFunction(controller: 'federation',
action: 'getEntitiesPerForceTable',
params: '\'interval=\'+interval',
onSuccess: 'fnUpdateEntitiesPerForceTable(data,textStatus)')};
}
That remoteFunction call is being sent to the client as:
try{DojoGrailsSpinner.show();}catch(e){} dojo.xhr('Get',{content:{'interval='+interval}, preventCache:true, url:'/FederationReporter/federation/getEntitiesPerForceTable', load:function(response){ fnUpdateEntitiesPerForceTable(data,textStatus); }, handle:function(response,ioargs){try{DojoGrailsSpinner.hide();}catch(e){} }, error:function(error,ioargs){try{DojoGrailsSpinner.hide();}catch(e){} } });;
Which is causing a error:
SyntaxError: missing : after property id
...){} dojo.xhr('Get',{content:{'interval='+interval}, preventCache:true, url:'/Fed...
federation (line 400, col 60) (which is the bolded '+' before the second 'interval'
What am I missing?
Dojo content should be a key-value pair.
{content:{'interval': interval}

Twitter like "x new tweets" with .arte or .ajax?

I've found this great example to implement a twitter like "x new tweets" http://blog.hycus.com/2011/03/14/realtime-updates-like-twitter-using-phpmysqljquery/
In this example the .arte jQuery plug-in is used. However I think it can be done just as the same with .ajax and I've coded as:
$.ajax({
url:'async.php? main='+$('.boxOfMainPage:first').attr('id'),
success:function(results)
{
if(results!='')
{
if(results.indexOf('boxOfMainPage')>=0)
$('#tweetEveryone').prepend(results);
else
$('#newTweet').html("<center><a href=''>I found "+results+" new tweets</a></center>").show();
}
}
});
This checks the results and loads the result to tweetEveryone. Async.php simply makes a mysql_query and brings the new results. I've actually done exactly the same with the example however when I click the 'new tweet's like it sometimes causes a postback. In the example I haven't experience it. Can it be because of the difference between .arte and .ajax ?
It's nothing about the differences between arte and ajax (in fact and in a short way, arte is ajax that is called with an interval, trying to do something like "long polling")
So, u have a link without href value, this must "reload" ur page, ie, it will perform a GET request to the actual URL in window.location. A postback performs a POST request, this is really happening?
--- edited ---
If you wanna to do the same effect from twitter, it's simple.. In async.php, instead u write an link element that shows how many tweets has after the old state, make this page write a JSON object with all tweets, then, ur ajax function must get this JSON and convert it into a JS object. With this object, u'll be able to count how many updates u have to show and exactly which are they.
So, ur function could be like this (assuming that "#boxOfMainPage" is ur tweets container):
$.ajax({
url : 'async.php?main='+$('.boxOfMainPage:first').attr('id'),
success : function (tweets) {
window.NEW_TWEETS = tweets;
if ( NEW_TWEETS && NEW_TWEETS.length ) {
$('#newTweet').html("<center><a href='#' onclick='showNewTweets()'>I found "+NEW_TWEETS.length+" new tweets</a></center>").show();
}
}
});
The showNewTweets functions will be:
function showNewTweets() {
if ( window.NEW_TWEETS && NEW_TWEETS.length ) {
$('#newTweet').hide().html("");
for ( tweet in NEW_TWEETS ) {
$("#boxOfMainPage").prepend(buildTweetHTML(tweet));
}
}
}
And buildTweetHTML:
function buildTweetHTML(tweet) {
var $tweetElm = $("<div class='tweet'>");
$tweetElm.append("<h2>"+tweet.user+" said:</h2>");
$tweetElm.append("<p>"+tweet.content+"</p>");
$tweetElm.append("<p class='time'>"+tweet.time+"</p>");
return $tweetElm;
}
Finally, async.php should write JSON object like this:
[
{ user : 'Rafael', content : 'The content from tweet', time : 'X time ago' },
{ user : 'George', content : 'The content from tweet', time : 'Y time ago' }
{ user : 'Jack', content : 'The content from tweet', time : 'H time ago' }
]

Categories

Resources