Trouble migrating from twitter search api to status api - javascript

I was using search api to fetch tweets of a particular user. It worked perfectly except that it couldn't fetch tweets where username contained numbers.
So upon suggestion I replaced the query with that of status api. But am unable to parse it now!!
Posting below the old code to display the tweet details.
function displayTweets(data) {
//var data = JSON.parse(d);
$("#heading").html("Tweets: <span class='handleName'>#"+handle+"</span>");
$("#loading").remove();
$("#tweets").children().remove();
alert("1");
$.each(data.results, function(i, tweet) {
alert("hi");
if(tweet.text !== undefined) {
// Calculate how many hours ago was the tweet posted
var date_tweet = new Date(tweet.created_at);
var date_now = new Date();
var date_diff = date_now - date_tweet;
var hours = Math.round(date_diff/(1000*60*60)); // calc time to tweet in hours
if(hours < 1){
hours = Math.round(date_diff/(1000*60));
if(hours<1){
$("#tweets").append($("<li/>").html(tweet.text+" <span class='tweetTime'>--a moment ago.</span>"));
}else{
$("#tweets").append($("<li/>").html(tweet.text+" <span class='tweetTime'>--"+hours+" minute(s) ago.</span>"));
}
}else{
$("#tweets").append($("<li/>").html(tweet.text+" <span class='tweetTime'>--"+hours+" hour(s) ago.</span>"));
}
}
});
}
Now the query string i am using to get the response and store the response in localstorage:
function sendRequest(handle, noOfTweets, boolDisplay){
$.getJSON("http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+ handle + "&count=" + noOfTweets + "&callback=?", function(data) {
if(boolDisplay){
displayTweets(data);
}
localStorage.setItem("tweets"+handle, JSON.stringify(data));
});
Please tell me what changes are needed!!
}

The structures of the returned JSON is completely different. See the examples at https://dev.twitter.com/docs/api/1/get/search and https://dev.twitter.com/docs/api/1/get/statuses/user_timeline
For example, you're saying
$.each(data.results, function(i, tweet) {
But the user timeline doesn't contain a results element.
You want something like
$.each(data, (function(i, tweet) {

Related

How to make API request from HTML select tags?

I need help with this scenario, getting all data from multiple select tag
and use those data to send an API request.
I have these three select tags, and one button to send a request to a news API.
The user needs to select a value from those select tags to set data like "source" and "category".
Example: "https://xxxxxxxxxxxx.org/v2/top-headlines?source='+ source +' + '&category='+ cat +'&apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Not sure if this the efficient way.
Below is my js code.
//global variables
var apiUrl = 'https://xxxxxxxxxxxxxxxxxx',
apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxx',
displayRequest = document.querySelector('.displayRequestData'),
requestBtn = document.querySelector('#runApi'), //Btn to display data
newsOpt = document.querySelector('#news-selection'), //news select tag
catOpt = document.querySelector('#news-category'); //category select tag
requestBtn.addEventListener('click', newsRequest); //onclick
function sourceSelected() { //news option
var source = newsOpt !== null ? newsOpt.options[newsOpt.selectedIndex].value : 'the-next-web';
var cat = catOpt !== null ? catOpt.options[catOpt.selectedIndex].value : 'general';
return newsRequest(source, cat);
}
function newsRequest(source, cat) {
axios.get(apiUrl + 'top-headlines?sources=' + source + '&language=' + cat + '&apiKey=' + apiKey)
.then(function (response) {
var reStringify = JSON.stringify(response);
var rejson = JSON.parse(reStringify);
if (rejson.data.status == 'ok'){
console.log(rejson.data.articles[1].source.name);
//console.log(requestBtn);
}
})
.catch(function (error) {
console.log(error);
});
}
By the way, i got this error
VM7472:1 GET https://xxxxxxxxxxxxxxxxxxxxxxxx/v2/top-headlines?sources=[object%20MouseEvent]&language=undefined&apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxx 400 (Bad Request)
When you add the event listener to call newsRequest via onClick, the first and only parameter that will be sent to that function is the event object. Therefore, the parameters of source and cat are not passed to newsRequest when they click on the button. (This is why your resulting URL has the [object MouseEvent] in it)
Instead, you might want to call your sourceSelected function in the onClick event which is fetching the current field values and then calling the newsRequest function.
I play around with my code, it's working now.
Note: The news API I'm using not allowing me to mix some data like country, source and langauge. So I try things that only allowed for free account and it works.
requestBtn.addEventListener('click', sourceSelected); //onchange
function sourceSelected() { //news option
var source = newsOpt !== null ? newsOpt.options[newsOpt.selectedIndex].value : 'en';
var cat = catOpt !== null ? catOpt.options[catOpt.selectedIndex].value : 'general';
return newsRequest(source, cat);
} //end of sourceSelected
function newsRequest(source, cat) {
axios.get(apiUrl + 'top-headlines?country=' + source + '&category=' + cat + '&apiKey=' + apiKey)
.then(function (response) {
var reStringify = JSON.stringify(response);
var rejson = JSON.parse(reStringify);
if (rejson.data.status == 'ok') {
console.log(rejson.data.articles[1].source.name);
//console.log(requestBtn);
}
})
.catch(function (error) {
console.log(error);
});
}//newsRequest

Insert data from Javascript to MySQL using PHP

I have a calendar with the days and times. And the user can select which days and times is he available. Im saving that information in the database. At the moment, if the user select for example Monday from 08:00 until 10:00 I save on the database one line per slot.
What I want to do, is to save only one line (the last line). Instead of all of them. So basically, I need to save the information from click to click. I don't really know how to achive that. This is the code so far:
function isSlotSelected($slot) { return $slot.is('[data-selected]'); }
function isSlotSelecting($slot) { return $slot.is('[data-selecting]'); }
/**
* Get the selected time slots given a starting and a ending slot
* #private
* #returns {Array} An array of selected time slots
*/
function getSelection(plugin, $a, $b) {
var $slots, small, large, temp;
if (!$a.hasClass('time-slot') || !$b.hasClass('time-slot') ||
($a.data('day') != $b.data('day'))) { return []; }
$slots = plugin.$el.find('.time-slot[data-day="' + $a.data('day') + '"]');
small = $slots.index($a); large = $slots.index($b);
if (small > large) { temp = small; small = large; large = temp; }
return $slots.slice(small, large + 1);
}
DayScheduleSelector.prototype.attachEvents = function () {
var plugin = this
, options = this.options
, $slots;
this.$el.on('click', '.time-slot', function () {
var day = $(this).data('day');
if (!plugin.isSelecting()) { // if we are not in selecting mode
if (isSlotSelected($(this))) { plugin.deselect($(this)); }
else { // then start selecting
plugin.$selectingStart = $(this);
$(this).attr('data-selecting', 'selecting');
plugin.$el.find('.time-slot').attr('data-disabled', 'disabled');
plugin.$el.find('.time-slot[data-day="' + day + '"]').removeAttr('data-disabled');
}
} else { // if we are in selecting mode
if (day == plugin.$selectingStart.data('day')) { // if clicking on the same day column
// then end of selection
plugin.$el.find('.time-slot[data-day="' + day + '"]').filter('[data-selecting]')
.attr('data-selected', 'selected').removeAttr('data-selecting');
plugin.$el.find('.time-slot').removeAttr('data-disabled');
plugin.$el.trigger('selected.artsy.dayScheduleSelector', [getSelection(plugin, plugin.$selectingStart, $(this))]);
plugin.$selectingStart = null;
}
}
});
this.$el.on('mouseover', '.time-slot', function () {
var $slots, day, start, end, temp, endAux;
if (plugin.isSelecting()) { // if we are in selecting mode
day = plugin.$selectingStart.data('day');
$slots = plugin.$el.find('.time-slot[data-day="' + day + '"]');
$slots.filter('[data-selecting]').removeAttr('data-selecting');
start = $slots.index(plugin.$selectingStart);
end = $slots.index(this);
if (end < 0) return; // not hovering on the same column
if (start > end) { temp = start; start = end; end = temp; }
$slots.slice(start, end + 1).attr('data-selecting', 'selecting');
}
$.ajax({
url: "/Member/test.php",
dataType:"json",
type: "POST",
data: {
day,
start,
end
}
}).success( function( weekDay, startTime, endTime) {
console.log( weekDay );
console.log( startTime );
console.log( endTime );
}).error( function( error ) {
console.log( "error:", error );
})
});
};
And this is the PHP where I save the information in the database:
<?php
include 'connection.php';
session_start();
$raw_json = json_encode( $_POST );
if($raw_json != "[]"){
$sql = "INSERT INTO Users (day) VALUES ('$raw_json')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
Any help will be appreciated. Thanks.
You are making a request to your server on each mouseover of a .time-slot element (probably one of those rectangles in your calendar):
this.$el.on('mouseover', '.time-slot', function () {
So if you start at 0800 AM and drag to 10:00 AM the mouseover event is triggered each time the user hovers over a .time-slot element, resulting in multiple queries being executed. You probably want to use the mouseup event and check what the last .time-slot being hovered over is.
In psuedo-code that is something like this:
mouseover:
lastSlot = element hovered over
mouseup:
send request to server with lastSlot
Seeing as you are using DayScheduleSelector, the plugin fires an event after a selection is made:
selected.artsy.dayScheduleSelector
Triggered when a selection is made. Passes the event and an array of selected time slots to the event handler.
$("#weekly-schedule").on('selected.artsy.dayScheduleSelector', function (e, selected) {
/* selected is an array of time slots selected this time. */
/* pop the last element of selected and execute your request */
}
If you only want the last selected entry, pop it off the selected array and send it a request. This isn't an exact implementation, but this should give you enough pointers to adapt it to your needs.
On a side note, your current query is susceptible for MySQL injection. Please read: How can I prevent SQL-injection in PHP?. Your code is also badly formatted and not clear, which doesn't really motivate people to help you in the first place; it takes more time to understand what your code does(n't), than to offer useful help.

Parsing links from an XML files with JavaScript

To display my latest blog-posts on a different page I want to parse the rss-feed from the blog and then generate elements with it.
I first tried to parse a fixed .xml file for which I wrote the following code:
var maxBlogposts = 5;
var blogPosts = 0;
$.get("rss.xml", function(data) {
$(data).find("item").each(function() {
if(blogPosts === maxBlogposts) return;
var el = $(this);
//Only display 3 posts on small devices.
var extra = (blogPosts >= 3) ? "not-small 12u(small)" : "12u(small)";
var div = $('<div class="6u ' + extra + '" class="blog-entry"></div>');
var h = $('<h4>' + el.find("title").text() + '</h4>');
var description = el.find("description").text().replace('[…]', '[…]');
var p = $('<p>' + description + '</p>');
div.append(h);
div.append(p);
$('#blog').append(div);
blogPosts++;
});
});
This worked perfectly fine. Now I want to parse the actual rss-feed. For this I wrote a PHP script which simply gets the feed and echos it.
<?php
$rss = file_get_contents('http://xn--der-grne-baum-1ob.net/feed/');
die($rss);
?>
And again I get the correct XML file on the frontend.
The problem I have is that now my code is no longer working. Getting the description was failing as well as the links. I fixed the description by accessing
el.find(description")[0].innerHTML
However I can't seem to get the links to work. The data returned from the PHP file contains a node with the link in it. The "el"-element also contains children named "link" but those no longer contain the actual link.
I feel like the links may get "escaped" during parsing? At least that is the only reason i could think of that would result in what I am observing.
The XML I am parsing comes from http://xn--der-grne-baum-1ob.net/feed/
Try
var maxBlogposts = 5
, blogPosts = 0;
$.get("https://query.yahooapis.com/v1/public/yql?q=select"
+ " * from feed where url='http://xn--der-grne-baum-1ob.net/feed/'")
.then(function(data) {
$(data.documentElement).find("results item")
.each(function() {
if(blogPosts === maxBlogposts) return;
var el = $(this);
//Only display 3 posts on small devices.
var extra = (blogPosts >= 3) ? "not-small 12u(small)" : "12u(small)";
var div = $('<div class="6u ' + extra + '" class="blog-entry"></div>');
var h = $('<h4>' + el.find("title").text() + '</h4>');
var description = el.find("description").text().replace('[…]', '[…]');
var p = $('<p>' + description + '</p>');
div.append(h);
div.append(p);
$('#blog').append(div);
blogPosts++;
});
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blog"></div>
See YQL Console

How does Google Script send an email when it detects changes in the background, like cron?

I have a Google spreadsheet with a script that checks a local library catalog to see if an ISBN-searched book has shown up or not. There's no API or RSS feature so I'm using UrlFetchApp to screen scrape for certain unique phrases that appear in the HTML source for a given book status.
Right now my spreadsheet only updates the "Status" column (which invokes the script based on an ISBN field) when I open the spreadsheet. Is there a way I can have Google Script run my main function and then trigger for changes? The documentation I've read has only mentioned user edits, which is not what I'm looking for.
function ISBNsearch(ISBN){
var consortURL = "http://LIBRARYURL/search~S6/?searchtype=i&searcharg=" + ISBN + "&searchscope=4";
var retrieveURL = UrlFetchApp.fetch(consortURL).getContentText();
var searchURLno = retrieveURL.search("BROWSE SCREEN TABLE");
var searchURLyes = retrieveURL.search("Item Location");
var searchURLordered = retrieveURL.search("copy ordered for");
if (searchURLno > -1){
var answer = "Not found"
} else if (searchURLyes > "-1") {
answer = "in Consort"
} else if (searchURLordered > "-1") {
answer = "on order"
} else if ((searchURLno == "-1") && (searchURLyes == "-1") && (searchURLordered == "-1")) {
answer = "no input"; }
return answer;
}
function testScript(){
var response = ISBNsearch("9782711802036");
Logger.log("The answer is " + response);
return response;
}
You can use Time Driven triggers to schedule function executions.
You can also programmatically manage these triggers.

jQuery AJAX and Google Currency calculator

I have some code that performs an AJAX call to the google currency calculator. Which in theory should return a JSON array that i can ten use to get some exchange rate related data.
The Link is:
http://www.google.com/ig/calculator?hl=en&q=1USD=?CNY
Going to the link shows
{lhs: "1 U.S. dollar",rhs: "6.49148317 Chinese yuan",error: "",icc: true}
My javascript code (I tired this with both POST and GET):
jQuery.ajax({
type: "GET",
url: "http://www.google.com/ig/calculator",
data: "hl=en&q=1USD=?CNY",
success: function(msg) {
var currency = $.parseJSON(msg);
alert (currency ['rhs'];);
}
});
Examining fire bug shows in red with an empty response
GET http://www.google.com/ig/calculator?hl=en&q=1USD=?CNY 200 OK 255ms
What am I doing wrong?
You can't perform cross domain requests with jQuery. You need to use JSONP to perform this request. These links might help:
http://api.jquery.com/jQuery.getJSON/#jsonp
jsonp with jquery
JSONP requests are not subject to same-origin policy restrictions.
heard google has stopped services from iGoogle from Nov 1st..
the link no longer works.
As we know google has stopped services from iGoogle from Nov 1st/2013..
But we can use https://www.google.com/finance/converter to get the real time data.
Following example of jquery will work for you.
function CurrencyConvetor(amount, from, to) {
var result = '';
var url = "https://www.google.com/finance/converter?a=" + amount + "&from=" + from + "&to=" + to;
$.ajaxSetup({async: false});
$.get(url,
function (data) {
var startPos = data.search('<div id=currency_converter_result>');
var endPos = data.search('<input type=submit value="Convert">');
if (startPos > 0) {
result = data.substring(startPos, endPos);
result = result.replace('<div id=currency_converter_result>', '');
result = result.replace('<span class=bld>', '');
result = result.replace('</span>', '');
}
})
return result;
}

Categories

Resources