Tips for refreshing a Twitter feed in real-time by utilizing AJAX requests and JavaScript

I recently started learning javascript and I'm struggling with loading a new twitter feed based on user input. Here is the code I have been working on:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Custom Twitter Feed</title>
<style type="text/css">
body    {
    background: #111111;
    position: relative;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
    font-weight: bold;
    color: #ccc;
}
h1 { padding: 20px 0 0 15px; margin: 0; letter-spacing: -3px; }
h2 { padding: 0 0 0 15px; margin: 0; color: #777; letter-spacing: -2px; }
.loader     { position: absolute; top: 250px; left: 105px; }
#twitter    { position: relative; width: 280px; background: #222; height: 820px; margin:     50px 0 0 250px;  }
#twitter li p   { padding: 0 0 15px; }
#twitter p a:link, #twitter p a:active, #twitter p a:visited    { color: #6fb2cd;     text-decoration: none; }
#twitter p a:hover  { text-decoration: underline; }
#twitter ul {
    width: 260px;
    height: auto;
    padding: 15px 0 0 15px;
    margin: 0;
}
#twitter li {
    float: left;
    margin: 3px 0;
    list-style-type: none;
}
li.twitter_date {
    background: url(../images/date_bg.jpg) no-repeat left top;
    width: 95px;
    height: 23px;
    text-align: center;
    line-height: 21px;
}
.twitter_date a:active, .twitter_date a:link, .twitter_date a:visited   {
    color: #666;
    background: #333;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 11px;
    text-decoration: none;
    text-transform: uppercase;
    padding: 7px;
}
.twitter_date a:hover   {
    color: #666;
}
a:link#go_back, a:active#go_back, a:visited#go_back {
    display: block;
    background: url(/demos/go_back.jpg) no-repeat top left;
    width: 120px;
    height: 40px;
    position: absolute;
    top: 50px;
    left: 100px;
    text-indent: -9999px;
    color: #111;
}
a:hover#go_back {
    background: url(/demos/go_back.jpg) no-repeat -120px 0;
}
</style>
<script type="text/javascript"     src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">


//Twitter
window.onload = function() {
    var ajax_load = "<img class='loader' src=' loader.gif' alt='Loading...' />";
    var url = 'http://twitter.com/statuses/user_timeline/' + 'coldplay' + '.json?call    back=twitterCallback2&count=6';
    var script = document.createElement('script');  
    $("#twitter_feed").html(ajax_load);
    script.setAttribute('src', url);
    document.body.appendChild(script);
}

changeFeed is supposed to update the feed but it's not functioning correctly. Any suggestions?

function changeFeed(){
    var ajax_load = "<img class='loader' src=' loader.gif' alt='Loading...' />";
    var newSearch = $('#query').val();
    var url = 'http://twitter.com/statuses/user_timeline/' + newSearch + '.json?callback=twitterCallback2&count=6';
    var script = document.createElement('script');  
    $("#twitter_feed").html(ajax_load);
    script.setAttribute('src', url);
    document.body.appendChild(script);
}

function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, 
function(url) { return '<a href="'+url+'">'+url+'</a>';
}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
  return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
});
statusHTML.push('<li class="twitter_date"><a href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li> <li><p>'+status+'</p></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + " " + values[5] + " " + values[3];
  var parsed_date = new Date();
  parsed_date.setTime(Date.parse(time_value));  
  var months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec');
  var m = parsed_date.getMonth();
  var postedAt = '';
  postedAt = months[m];
  postedAt += " "+ parsed_date.getDate();
  postedAt += ","
  postedAt += " "+ parsed_date.getFullYear();
  return postedAt;
}                                        

</script>
</head>

<body>
<a id="go_back" href="javascript:history.go(-1)">Go Back</a>
<div id="twitter">
    <form>
    Search: <input type="text" name="searchstring" id="query" /><br />
    </form>
    <button type="button" onclick="changeFeed();">Search</button>

    <h1>searchstring.text()</h1>
    <h2>Twitter Feed</h2>
    <ul id="twitter_update_list">
    </ul>
</div>

Answer №1

It slipped my mind to generate the newSearch element. I resolved the issue by adding this line:

var newSearch = document.createElement('newSearch')

After making this addition, everything began functioning smoothly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to combine two addEventListeners into one for a single click event?

preview of a to-do list app I am faced with a situation where I have two addEventListeners, one to change the text color and another to change the circle color. In Condition 1: When I click on the circle, both the text and circle colors are changed. In ...

Creating grids and dividing them using a combination of CSS, JavaScript, and PHP

I've encountered an interesting challenge while working on a web project and would love some advice on how to tackle it: Within a database, I have a collection of images that I want to display in a grid format. The twist is that higher ranked images ...

Creating an interactive placeholder using React hooks

Would you like to create a dynamic placeholder for your input field? Here is an example of an array of filters: const filters = [ { id: "search", label: "Search", icon: <SearchIcon /> }, { id: "contains", ...

Is there a way to keep my fixed footer container from moving while zooming in and out on a webpage

Is there a way to prevent the bottom text from shifting when zoomed in or out on the page? The rest of the content remains stable, but due to using position:absolute for this section to stay at the bottom of another div (content), it causes movement. #con ...

Excessive indentation detected within the website's formatting

There seems to be an issue with the mobile version of the website, possibly related to flexbox, SVG, or width settings that are unclear to me. Inspecting with Devtools reveals indents from the SVG and text itself. Check out the website here My goal is to ...

When the page is refreshed, reorienting axes in three.js encounters difficulties

I am currently working on a project that involves using the three.js editor source code available for download on the three.js website. As part of this project, I am required to adjust the orientation of the axes to align with standard airplane coordinate ...

What is the best way to avoid duplicating this JQM function multiple times and instead reuse it efficiently?

After coming across this interactive demo, I successfully implemented it on my website using JQM. However, in order to activate the panel swipe feature, I had to include the following function: $( document ).on( "pagecreate", "#demo-page", function() { ...

Issue with nested views in Angular UI-Router not displaying properly

The issue I'm facing is that the template <h1>HELLO</h1> is not loading into the nested ui-view in analysis.client.view.html. However, the ui-view in the analysis.client.view.html file is being loaded successfully. I've tried naming t ...

Understanding the behavior of a React component when passed as a prop

Typically, components are passed down as children to another component. However, I have noticed in some UI libraries that components can also be passed using standard named props. I attempted this approach myself but encountered some limitations without an ...

Response text from AJAX in PHP

I am working on an AJAX sign up form and I would like to incorporate a gear wheel animation similar to this When the server successfully signs up a user, I want a specific bar to change to green. To achieve this, I have echoed the names of the functions I ...

How can user-side access rights be dynamically granted to a database in PHP?

Seeking a solution to dynamically assign access rights such as edit, view, and delete values in the database for users using PHP. This will allow the super admin to easily change privileges within the application interface without having to manually upda ...

What is the best way to position a div in relation to a table header (th) but not inside it?

I'm trying to create a table header that displays a help text (div) when clicked on. However, the help div is causing the table header to be larger than the other headers. Below is the code snippet: #help_box { border-radius: 20px; ba ...

The TSX file is encountering difficulty rendering an imported React Component

Upon attempting to import the Day component into the Week component (both .tsx files), an error is thrown: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. ...

What is the best way to submit updated data from an Angular form?

Currently, I have a situation where multiple forms are connected to a backend service for storing data. My query is whether there exists a typical angular method to identify which properties of the model have been altered and only send those in the POST r ...

Tips for using the .join() method in React when the array is not initially present

I'm currently working on a functional React component that retrieves data from an API request and displays it. The object initially is empty until the request is made. Inside the object, there is an array structured like this: ['US', ' ...

Tips for exporting data to a JSON file using the Google Play Scraper in NodeJS

Recently, I've been exploring the Google Play Scraper and I'm in need of a complete list of all appIds using NodeJS. The issue I'm facing is that it only outputs to console.log. What I really require is to save this output to JSON and then c ...

Encountering an error when attempting to apply the addClass method to the anchor tag referred to by

function showImage(imageSrc) { $('a.slideTabLinkBlock').removeClass('active'); alert($(this).attr('class')); $(this).addClass('active'); } <script src="htt ...

Determine if a JSON object is void

Using jQuery, I am checking whether the object returned from an AJAX call is empty or not. In the first example, the AJAX call is successful and returns some data. console.log("obj before JSON parse:", response); var test = $.isEmptyObject(response); con ...

The error "Cannot access property of undefined during an Ajax POST request" indicates

I am currently facing an issue with uploading a music file using AJAX to save the data into my MongoDB when I click the 'upload' button. Unfortunately, I keep receiving an error stating that "fieldname is undefined". It seems like there might be ...

Utilizing jQuery's $(window).width function for handling browser window width

Currently, my website utilizes $(window).width() in a JavaScript function. For my Selenium testing, I need to verify whether the function was executed and a div contains the value of $(window).width() * 0.8. Is there a feasible way to accomplish this tas ...