I'm a beginner at javascript/jquery and completely new to API's and I'm wondering if anyone could help me with something
What I'm trying to achieve is to have a user enter a keyword/phrase into a textbox, they click search and the page returns a list of people who have that word in their tweet.
I have so far been able to display results from a hard-coded keyword (which I got from a website) but when trying to change it I am getting nothing back.
Here is the working one with hard code
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('http://search.twitter.com/search.json?q=earthquake&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
});
});
</script>
<h2>Twitter</h2>
<div class="content">
</div>
And here is the code I'm working on now
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
var button= document.getElementById('searchTwitter');
button.onclick= function(){
var text = document.getElementById('search').value;
}
var baseUrl = "http://search.twitter.com/search";
var query = document.getElementById('<%=searchTwitter.ClientID%>').value;
$(document).ready(function () {
$.ajax({
url: baseUrl + '&text' + '&lang=en&callback=?',
dataType: "jsonp",
success: showResults
});
});
function showResults(data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
}
</script>
<asp:TextBox ID="search" runat="server"></asp:TextBox>
<asp:Button ID="searchTwitter" runat="server" Text="Button" />
Any help would be much appreciated as I have been trying to find a way to do this for days.
thanks a lot
Here's a working example of what you are describing: http://jsfiddle.net/ZEjey/. You should be able to adapt it to your ASP code.
Relevant code below.
JQuery
$("#SearchButton").click(function() {
$.getJSON('http://search.twitter.com/search.json?q=' + $('#TextSearch').val() + '&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
});
});
HTML
<h2>Twitter</h2>
Search for: <input id="TextSearch" type="text" /> <input type="button" id="SearchButton" value="Go" />
<div class="content"></div>
---
EDIT 0
Okay, the code below works. The <asp:Button automatically causes a postback so you don't see anything ever get loaded. You either need to use <input type="button" ... instead or stop the normal events from occurring using event.preventDefault(); as I did below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Twitter</h2>
<asp:TextBox id="TextSearch" runat ="server"/>
<asp:Button id="SearchButton" runat="server" Text="Search"/>
<div class="content"></div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script>
$(document).ready(function () {
$("#SearchButton").click(function () {
event.preventDefault(); // ADD THIS LINE TO YOUR CODE
$('.content').html("<em>loading...<em>");
$.getJSON('http://search.twitter.com/search.json?q=' + $('#TextSearch').val() + '&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#" + data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>";
$('.content').html(html);
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
});
});
</script>
</form>
</body>
</html>
It looks like you're making an ajax request on document ready, rather than when the button is clicked. I also don't see where you're adding the value from the text box to the query. Here's how you could change your code:
//this code will run when the page loads and set up the button so the
//onclick event executes your function
$(document).ready(function () {
var button = document.getElementById('<%=searchTwitter.ClientID%>');
//you need to make the ajax request in this function, because this
//is fired when the search button is clicked
button.onclick = function() {
var text = document.getElementById('search').value;
var baseUrl = "http://search.twitter.com/search.json";
var query = document.getElementById('<%=search.ClientID%>').value;
$.ajax({
//you're building the request url here, with the text from the
//box as the q parameter
url: baseUrl + '?q=' + query + '&lang=en&callback=?',
dataType: "jsonp",
success: showResults
});
};
});
//this function can be defined outside ready()
function showResults(data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>";
//I'm assuming you have a div with a content class on your page
$('.content').html(html);
}
You might also want to try out the Chrome developer tools (or Firebug in Firefox). You can set breakpoints and see what's happening at each step. You can also see what requests have been sent and the data returned. That will help give you a better handle on what's going on.
Related
I am a bit confused here. I have a div which contains comments. Then when you click on the more comments icon, it calls php via ajax and appends the results to a div then slides it down. That part works fine. Then I have a hide icon which when you click on it, it collapses the expended div that was showing more comments. The problem, I am having is that if I collapse the div then click on show more comments again, the div no longer expands.
Below is the code which handles the more and hide clicks. Any tips would be appreciated.. Thanks
$("[id^='show_more_comments_']").on( 'click', function(e) {
var pagenum = $(this).data('newpage');
var photoid = $(this).data('photoid');
var commentsdiv = 'morecomments_' + photoid;
var moredots = 'show_more_comments_' + photoid;
var lessdots = 'hide_more_comments_' + photoid;
$.ajax({
type: "POST",
url: "showmorecomments.php",
data: {page: pagenum, photoid: photoid},
success: function(data){
$("#" + moredots).data('newpage', pagenum + 1);
$("#" + lessdots).show();
$(data).hide().appendTo("#" + commentsdiv).slideDown(500);
}
});
});
$("[id^='hide_more_comments_']").on( 'click', function(e) {
var photoid = $(this).data('photoid');
var commentsdiv = 'morecomments_' + photoid;
var moredots = 'show_more_comments_' + photoid;
var lessdots = 'hide_more_comments_' + photoid;
$("#" + commentsdiv).slideUp(500);
$("#" + lessdots).hide();
$("#" + moredots).data('newpage', 1);
$("#" + moredots).data('photoid', photoid);
});
If I set an alert to see the data values, they are correct. Its just no longer expanding the comments afyer I close them and try to open them again.
Thanks
JT
Figured it out, slideUp hides the comments div so you must use a callback function to show the comments div again.
$("#" + commentsdiv).slideUp(500, function(){
$(this).empty().show()
})
Check this code snippet:
var data = '<div id="content">'
data += 'These are the comments to be added to the comment div'
data += '<ul>'
data += ' <li>Comment 1</li>'
data += ' <li>Comment 2</li>'
data += ' <li>Comment 3</li>'
data += '</ul>'
data += '</div>';
$(function() {
$("#showBtn").click(function() {
$(data).hide().appendTo("#morecomments_1").slideDown(500)
})
$("#hideBtn").click(function() {
$("#morecomments_1").slideUp(500, function(){
$(this).empty().show()
})
})
})
<div id="morecomments_1"></div>
<button id="showBtn">Show</button>
<button id="hideBtn">Hide</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to allow clients to create a list of students then view more info by simply clicking on the button with the students name. I've got it to create the button and display the students name in the button but it only calls the function when I click submit to add the student to the list, the actual student button doesn't seem to function.
function updateStudentList() {
var html = "";
for (var i = 0; i < students.length; i++) {
html += "<li><button type='button' class='studentButton'" + "id=" + students[i].name +">" + students[i].name + "</button></li>";
}
$('#studentList').html(html);
for (var i = 0; i < students.length; i++) {
document.getElementById(students[i].name).addEventListener('click', openStudentInfo(students[i].name));
}
}
function openStudentInfo(studentName) {
console.log("Opening " + studentName + " info.");
var studentInfo = requestStudentByName(studentName);
if (studentInfo != null) {
var studentInfoForm = $("#studentInfoForm");
var html = "";
html += "<h3>Student Name: " + studentInfo.name + "</h3>";
html += "<h3>Student ID: " + studentInfo.studentID + "</h3>";
studentInfoForm.html(html);
$("#studentInfoModal").show();
}
}
HTML:
<ul data-role="listview" id="studentList"> </ul>
Note: I can't use the onclick tag in HTML, it causes security issues. Cordova also blocks this.
The way you binding the event is not ok. Try binding this way:
$(document).ready(function() {
$("#studentList").on("click", ".studentButton", function() {
var studentId = $(this).data("studentid");
openStudentInfo(studentId);
});
});
And in your HTML generation:
html += "<li><button type='button' class='studentButton' data-studentid='" + students[i].studentID +"'>" + students[i].name + "</button></li>";
This kind of event delagation works not metter how you create the elements inside the root element(studentList in this case), because the event was bound in it, and not on the dynamic elements.
no jquery version of DontVoteMeDown's answer
document.getElementById('studentList').addEventListener('click', function(event) {
var clickedEl = event.target;
if(clickedEl.className === 'studentButton') {
var studentId = clickedEl.dataset.studentId;
openStudentInfo(studentId);
}
});
I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.
I am using a jsnewsticker plugin (http://jsfiddle.net/stevenchu/ezEtK/) which uses <li> to display an item at a time.
The code below works if my <li> items are hard-coded into the HTML. But it doesn't work if I have to dynamically create the <li> items from an RSS feed which my script below does
The final HTML page has the <li> items but the JS isn't scrolling through them. I'm not getting any errors in the console. The JS is appending ticker-active class to my <ul> though.
Could this be a sequential issue - perhaps the JS script is firing before the list of <li> items has been fully rendered? If possible, is there a way I can test this theory?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/js/jsnewsticker.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.get('http://example.com/feed', function (data) {
var count = 0;
$(data).find("item").each(function () {
var newsfeed = $(this);
var newstitle = newsfeed.find("title").text();
var newslink = newsfeed.find("link").text();
var newslist = '';
if (count < 3) {
newslist += '<li class="newsitem">'
+ '<a href="'
+ newslink
+ '">Latest: '
+ newstitle
+ '</a>'
+ '</li>';
count++;
}
$(".latestnews").append(newslist);
});
});
$('.ticker').Ticker();
});
</script>
The HTML taken from browser source:
<ul class="latestnews ticker ticker-active">
<li class="newsitem">Example</li>
<li class="newsitem">Example</li>
<li class="newsitem">Example</li>
</ul>
You have answered your own question earlier. Yes, you are calling ticker before the async Ajax get call has completed, so it fires up the ticker against an empty list.
You need to call it inside the get. e.g. something like:
<script src="/js/jsnewsticker.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.get('http://example.com/feed', function (data) {
var count = 0;
$(data).find("item").each(function () {
var newsfeed = $(this);
var newstitle = newsfeed.find("title").text();
var newslink = newsfeed.find("link").text();
var newslist = '';
if (count < 3) {
newslist += '<li class="newsitem">'
+ '<a href="'
+ newslink
+ '">Latest: '
+ newstitle
+ '</a>'
+ '</li>';
count++;
}
$(".latestnews").append(newslist);
});
$('.ticker').Ticker();
});
});
</script>
I want to append data I fetched from server to a div tag, but I can't get it to work. That's HTML with a div tag to which I'd like to append data from the JS code.
HTML:
<body onload="initialize()">
<div id="text"></div>
</body>
And here is JavaScript code. I would like to replace document.write with a function that will append data to a div tag.
JS:
function initialize() {
$.getJSON('http://www.wawhost.com/izdelava-mobilne-aplikacije-2-del/fetch.php?callback=?', function (data) {
for (var i = 0; i < data.length; i++) {
document.write('<img src="' + data[i].image + '" />' + data[i].title + data[i].description + '<br>');
}
});
}
Fiddle: http://jsfiddle.net/GDxtf/
I just started learning JavaScript. Help will be greatly appreciated :)
Paste this code in the bottom of your HTML document, right before </body>:
<script>
// If you're not using an HTML5 doctype, use <script type="text/javascript> instead of just <script>
$(function () {
$targetDiv = $("#text");
$.getJSON('http://www.wawhost.com/izdelava-mobilne-aplikacije-2-del/fetch.php?callback=?', function (data) {
for (var i = 0; i < data.length; i++) {
var $div = $("<div />");
var $img = $("<img />");
$img.attr("src", data[i].image);
$img.appendTo($div);
var $title = $("<h2>" + data[i].title + "</h2>");
$title.appendTo($div);
var $description = $("<p>" + data[i].description + "</p>");
$description.appendTo($div);
$div.appendTo($targetDiv);
}
});
});
</script>
Did this solve your problem?