New page link from user input ajax request - javascript

Im creating a bus finder application. I want the user to be redirected to a new page after they have input information for the ajax api request. At the moment the information is inserted after page one but on the same page. How do I create a new page with the ajax results once the user has inout the information and sent the request. I have a variable created with the results as a virtual page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dublin Concert Listings</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/custom.css" />
<link rel="stylesheet" href="css/theme.min.css" />
<link rel="stylesheet" href="css/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="header">
<h1>Get Next Bus Details</h1>
</div>
<div data-role="content">
<div class="content-primary">
<div data-demo-html="true">
<div class="ui-input-search ui-shadow-inset ui-input-has-clear ui-body-inherit ui-corner-all">
<input data-type="search" placeholder="Bus Stop Id" id="bus_stop_id" name="bus_stop_id">
</div>
<input type="button" value="Get Current Update" id="button_get_bus">
</div>
</div>
</div>
</div>
<script type="text/javascript">
//On click of button this function get call
$('#button_get_bus').click(function(){
//Get Enter Bus Id
var bus_stop_id = document.getElementById("bus_stop_id").value;
//If Id is blank then given error
if(bus_stop_id == "")
{
alert("Please enter bus stop number");
return false;
}
// This Function post request to API with the given bus stop id
$.ajax({
url: "https://data.smartdublin.ie/cgi-bin/rtpi/realtimebusinformation?stopid="+bus_stop_id+"&format=json",
dataType: 'json',
success: function(results){
// It returnes json data
var str = JSON.stringify(results);
// Code for parsing json
var myObj = JSON.parse(str);
var destination = myObj.results[0].destination;
var origin = myObj.results[0].origin;
var arrivaldatetime = myObj.results[0].arrivaldatetime;
var departuredatetime = myObj.results[0].departuredatetime;
var routenumber = myObj.results[0].route
var virtualPage = "";
virtualPage +=
'<div data-role="page" data-theme="a" id="virtualPage">'
+ '<div data-role="header">'
+ '<h1>' + origin + '</h1>'
+ '<div data-role="content">'
+ '<h3>Venue: ' + destination + '</h3>'
+ '<h3>Date: ' + arrivaldatetime + '</h3>'
+ '<h3>Time: ' + departuredatetime + '</h3>'
+ '</div'
+ '<div class="wrapper"><a data-role="button" data-transition="slide" href="#pageone">Back</a></div>'
+ '</div>'
+ '</div>';
$(virtualPage).insertAfter($('#pageone'));
}
});
});
</script>
</body>
</html>
Before AJAX request
After AJAX request

Related

Shopping Basket - add items to local storage

I have a csv file which contains items scraped from a supermarket website. I have now displayed them on html and added a "Add to cart" button. I want the item name and price to be saved on to local storage when the button is pressed.
The idea is to then show these saved data in the basket.
Showing my existing code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!--<link href ="styles.css" type = "text/css" rel="stylesheet">-->
<title>CSV File to HTML Table Using AJAX jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<!-- Header-->
<div id="header">
<button type="button" class="button">Basket</button>
</div>
<!-- CSV FILE DATA WILL APPEAR HERE-->
<div class="container">
<div class="table-responsive">
<div id="order_list" onload="appendRow()"><p id="tableintro"> Choose your desired supermarket</p>
</div>
</div>
</div>
<!--THIS BUTTON WILL LOAD DATA FROM CSV FILE-->
<div id="sidebar">
<div align="center">
<button type="button" name="load_data" id="load_sainsburys" class="btn btn-info">Sainsburys Colindale</button>
</div>
</div>
//Save item to local storage - DOESNT SEEM TO WORK
<script>
function SaveItem() {
var usrObject = {};
usrObject.product = document.getElementsById("12at").value;
usrObject.price = document.getElementById("34at").value;
//Store User
localStorage[usrObject.product] = JSON.stringify(usrObject);
}
</script>
Below is the code i am using to retrieve data from my CSV file:
<script>
$(document).ready(function(){
$('#load_sainsburys').click(function(){
$.ajax({
url:"sainsburys.csv",
dataType:"text",
success:function(data)
{
var tesco_data = data.split(/\r?\n|\r/);
var table_data = '<table class="table table-bordered table-striped">';
for (var count = 0; count < tesco_data.length; count++)
{
var cell_data = tesco_data[count].split(",");
var name = cell_data[0];
var price = cell_data[1];
if (count === 0)
{
table_data += '<tr><th>' + name + '</th><th>' + price + '</th><th>action</th></tr>';
continue;
}
table_data += '<tr><td id="12at">' + name + '</td><td id="34at">' + price + '</td><td><button type="button onclick="SaveItem()">Add to cart</button></td></tr>';
}
table_data += '</table>';
$('#order_list').html(table_data);
}
});
});
});
</script>

How can i add weather geolocation on my website?

i want to add weather on my website. i tried to do it with json and jquery, but i have some problems. can you help me or advise me other way to do this, please? the problem is that in console show that these json links which i have in html page in are incorrect. please help me. what can i do?
here is my code
if("geolocation" in navigator){
navigator.geolocation.getCurrentPosition(function(position){
loadweather(position.coords.latitude + "," + position.coords.longitude);
});
}else {
loadweather("kolkata, in" );
}
$(document).ready(function(){
setInterval(getWeather, 10000);
});
function loadWeather (location, woeid){
$.simpleWeather({
location:location,
woeid:woeid,
unit:'c',
suncess:function(weather){
city = weather.city,
temp = weather.temp+'°';
wcode = '<img class="weathericon" src=images/weathericons/' + weather.code + '.svg';
wind = '<p>' + weather.wind.speed + '</p><p>' + weather.units.speed +'</p>';
humidity = weather.humidity + '%';
$(".location").text(city);
$(".temperature").html(temp);
$(".climate_bg").html(wcode);
$(".windspeed").html(wind);
$(".humidity").text(humidity);
},
error: function(error) {
$(".error").html('<p>' + error + '</p>');
}
});
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">
<title>Weather App</title>
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700,inherit,400" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="css/standardize.css">
<link rel="stylesheet" href="css/index.css">
</head>
<body class="body page-index clearfix">
<div class="container clearfix">
<p class="location"></p>
<p class="temperature"></p>
<div class="climate_bg"></div>
<div class="info_bg">
<img class="dropicon" src="images/Droplet.svg">
<p class="humidity"></p>
<img class="windicon" src="images/Wind.svg">
<div class="windspeed"></div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>

I can't figure out how to update my jQuery code to plain JS and utilize the Fetch method for my Movie Search app using API for data

I developed a basic site using CSS, semantic HTML, javascript, and API. I have built a basic search application using HTML, sass(scss), gulp, and javascript. It connects to an API that populates a page with the results. I chose to utilize the Movie Database API. However, I used jQuery and now need to convert it with just plain JS and the Fetch method. I can't seem to figure out how to do it.
Here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel ="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/main.css" />
<title>Movie Box</title>
</head>
<body>
<!-----*** HEADER ***----->
<header>
<div class="clearfix">
<nav>
<!-- LOGO -->
<h1>MovieBox Logo</h1>
<!-- NAV LINKS -->
<ul class="main-nav">
<li>
Home
</li>
<li>
About
</li>
<li>
Contact
</li>
</ul>
</nav>
</div>
<!-- SEARCH FORM -->
<form action="#" class="js-search-form">
<p class="form-p">Search for movies by Title</p>
<div class="search">
<span class="fa fa-search"></span>
<input type="text" class="js-query" placeholder="ex. Star Wars" autofocus>
</div>
<button id="ghost-btn" type="submit">Submit</button>
</form>
</header>
<!-----*** SECTION - SEARCH RESULTS ***----->
<section class="js-search-results clearfix">
</section>
<!-----*** SECTION - VIEW MORE ***----->
<section>
<p class="max center-text">Showing max result of 20</p>
<p class="center-text">
<a class="btn second-btn" href="https://www.imdb.com/find" target="_blank">View More Details on IMDB</a>
</p>
</section>
<!-----*** FOOTER ***----->
<footer>Built by Eileen Villahermosa for DWS2</footer>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="js/index.js"></script>
</body>
</html>
Here is my JS:
// Single state variable for endpoint
var MD_BASE_URL = "https://api.themoviedb.org/3/search/movie?
include_adult=false&page=1";
var state = {
query: ''
};
// State modification functions
function getApiData(searchTerm, callback) {
var query = {
query: searchTerm,
language: 'en-US',
api_key: 'sssssssssssssss', // took the key out for privacy
};
$.getJSON(MD_BASE_URL, query, callback);
}
// Render functions
function displayMDSearchData(data) {
var resultElement = '';
if(data.results.length > 1) {
resultElement += '<section class="js-search-results clearfix">';
resultElement += '<h2>' + '<span>' + "Results for " + state.query + '</span>' + '</h2>';
if(data.results)
data.results.forEach(function(results){
resultElement += '<article>';
resultElement += '<div class="container">';
resultElement += '<img src="https://image.tmdb.org/t/p/w500' + results.poster_path + '"/>';
resultElement += '<div class="content">';
if(results.title.length > 20) {
resultElement += '<h3>' + results.title.substr(0,20) +'...</h3>';
} else {
resultElement += '<h3>' + results.title + '</h3>';
}
resultElement += '<p>Released: ' + results.release_date + '</p>';
resultElement += '</div>';
resultElement += '</div>';
resultElement += '</article>';
});
resultElement += '</section>';
console.log(data);
} else {
resultElement += '<p class="no-results">No results</p>';
}
$('.js-search-results').html(resultElement);
}
// Event listeners
function watchSubmit() {
$('.js-search-form').submit(function(e) {
e.preventDefault();
state.query = $(this).find('.js-query').val();
var query = state.query;
getApiData(query, displayMDSearchData);
});
}
$(function(){watchSubmit();});

Load each clicked post into a page

I have the following code working but would like when I click on each posts, the post content to be displayed using either an external .html or within the default html a div page so that the content does not show the whole website contents:
HTML Code:
<head>
<meta charset="utf-8">
<title>Hope</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script src="css/style.css"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<div id="devotionpage" data-role="page">
<div data-role="header" class="sys_hd" data-position="fixed" data-id="sys_header" data-theme="c" >
<h1>Daily Devotional Messages</h1>
</div><!-- header -->
<div data-theme="c" data-role="content" id="devotionlist"> </div><!-- content -->
<div data-role="footer" data-position="fixed" data-id="sys_footer" data-theme="c">
<div data-role="navbar" >
<ul>
<li>Home</li>
<li>Disclaimer</li>
</ul>
</div><!-- navbar -->
</div><!-- footer -->
</div><!-- page -->
<div id="articlepost" data-role="page" data-transition="fade">
<div data-role="header" class="devotion_hd" data-position="fixed" data-theme="c" >
<div data-theme="c" data-role="content" id="articlecontent"> </div><!-- content -->
<div data-role="footer" data-position="fixed" data-id="sys_footer" >
<div data-role="navbar" >
<ul>
<li>Home</li>
<li>Disclaimer</li>
</ul>
</div><!-- navbar -->
</div><!-- footer -->
</div><!-- page -->
</body>
</html>
JS Code:
$(document).on("pagebeforeshow", "#devotionpage", function() {
$(this).find(".ui-listview-filter input").val("").trigger("change");
});
$( document).ready(function (){
var url = 'http://howtodeployit.com/category/daily-devotion/feed/?json=recentstories&callback=listPosts' ;
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert( 'Unable to load feed, Incorrect path or invalid feed' );
},
success: function(data ){
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">' ;
for (var i = 0 ; i < 6 ; i++) {
var entry = postlist[i];
html += '<li>';
html += '<a href="' + entry.link + '">';
html += '<div class="etitle">' + entry.title + '</div>' ;
html += '<div class="eauthor">' + entry.author + '</div>' ;
html += '<div class="epubdate">' + entry.publishedDate + '</div>';
html += '<div class="esnippet">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$( "#devotionlist" ).append(html);
$( "#devotionlist ul[data-role=listview]" ).listview();
}});
});
Thanks
I see one issue with the code. The function showarticle has this line
(html+='</ul>';) outside the ajax call's callback handler, but the variable html is declared inside it. So, actually the line
html+='</ul>' is translated to undefined += '</ul>', which is not correct, unless you have var html; declared globally outside.
"the post content to be displayed using either an external .html"
you can make an ajax call to the external html with content type as text/html, and load the response into a div.
I am afraid I should not post full workable code, because SO is for helping people achieve their solution, and point them in right direction. So, I will post only a code snippet.
$.ajax({
url: your_server_side_script.extension, //example: handleInput.php
dataType: 'text/html',
data: {postid: $('#postid').val()},
success: function(responseHTML) {
$('#postContentDiv').html(responseHTML);
}
});
your_server_side_script.extension (handleInput.php) should generate html tags and print it, so that it'll be available in responseHTML variable in ajax success.
I created a function to handle display of each post on a different page:
function showPost(id) {
$('#devotionlist').html("Please wait...");
$.getJSON('http://howtodeployit.com/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var output='';
html += '<h3>' + data.post.title + '</h3>';
html += data.post.content;
$('#devotionlist').html(html);
}); //get JSON Data for Stories
} //showPost
This bit calls the onClick function:
html += '<a href="#articlecontent" onclick="showPost(' + val.id + ')">';

How to Get a class with Jquery and perform a function

I am currently working on a project that deals with feed from a website.
I have successufully gotten the feed, but my challenge is getting the content and title of the feed when a user click on the feed link rather than taken the user to the feed site.
I have tried using different method to get the solution, but none works.
Below is my latest code (Jquery Mobile)
(function($){
$.fn.FeedEk=function(opt){
var def={FeedUrl:'', MaxCount:5, ShowDesc:true, ShowPubDate:true, ShowFullContent:true};
if(opt){
$.extend(def,opt)
}
var idd = $(this).attr('id');
if(def.FeedUrl==null || def.FeedUrl==''){
$('#'+idd).empty();
return;
}
var pubdate;
$('#'+idd).empty().append('<div style="text-align:center; margin: auto;"><img src="loader.gif" class="loader" /></div>');
$.ajax({
url:'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num='+def.MaxCount+'&output=json&q='+encodeURIComponent(def.FeedUrl)+'&callback=?',
dataType:'json',
success:function(data){
$('#'+idd).empty();
$('#post').empty();
var output = '<ul data-role="listview" data-filter="true">';
$.each(data.responseData.feed.entries,function(i,entry){
var i =new Array(i);
for(j=0;j<=i;j++)
{
var id = j;
}
var title =new Array(entry.title);
var content =new Array(entry.content);
for(t=0;t<title.length;t++){
for(c=0;c<content.length;c++){$('#post').append(title[t]+'<br/>'+content[c])}
}
//while(id ==
//if(i == id
//var post = '<div><h3>'+entry.title+'</h3></div>';
//post += '<div>Post content'+entry.content+'</div>';
output += '<li>';
output += ''+entry.title+'';
/*if(def.ShowPubDate){
pubdate=new Date(feed[0].entry.publishedDate);
output += '<br/><span class="ItemDate">'+pubdate.toLocaleDateString()+'</span';
}
if(def.ShowDesc){
output += '<br/><span class="ItemDesc">'+feed[0].entry.contentSnippet+'</span>';
}*/
output += '</li>';});
console.log(data.responseData.feed.entries);
output += '</ul>';
$('#'+idd).html(output);
if($('.'+id).click() == true){
$('#post').empty();
var postTitle = title[id];
var postContent = content[id];
$('#post').append('<div><h3>'+postTitle+'</h3></div><div>'+postContent+'</div>');
}
}
})
}
})
(jQuery);
Below is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>News on the GO!</title>
<link href="theme/news.min.css" rel="stylesheet" />
<link href="theme/jquery.mobile.structure-1.2.0.min.css" rel="stylesheet" />
<link href="theme/FeedEk.css" rel="stylesheet" type="text/css" />
<script type="application/javascript" src="js/jquery1.7.2-min.js" ></script>
<script type="application/javascript" src="js/jquery.mobile-1.2.0.min.js"></script>
<script type="application/javascript" src="js/FeedEk.js"></script>
<link href="theme/custom.css" rel="stylesheet" type="text/css" />
<script type="application/javascript" src='js/main.js'></script>
<script type="application/javascript">
$(document).ready(function() {
//latest
$("#ipaid").FeedEk({
FeedUrl : 'http://ipaidabribenaija.com/news?format=feed',
MaxCount : 7,
ShowDesc : true,
ShowPubDate:true,
ShowFullContent:true
});});
</script>
</head>
<body>
<div data-role="page" id="home">
<div data-role="header" data-position="fixed" data-theme="a">
<h2>Recent News</h2>
About
</div><!-- /header -->
<div class="imghome">
<img src="images/news.png" alt="news" width="300" height="200" />
</div>
<nav data-role="navbar">
<ul>
<li><a href="#latest" data-theme="a" data-transition="flip" >Local News</a></li></ul>
</nav>
<!--<div data-role="content" >
</div><!-- /content -->
<div data-role="footer" data-position="fixed" data-theme="a"></div><!-- /footer -->
</div><!-- /Page home -->
<div data-role="page" id="latest" data-title="Local News">
<div data-role="header" data-position="fixed" data-id="ipaid_header" data-theme="a">
<h2>Local News</h2>
Back
</div><!-- /header -->
<div data-role="content" >
<div id="ipaid">
</div>
</div><!-- /content -->
<div data-role="footer" data-position="fixed" data-id="ipaid_footer" data-theme="a">
<div data-role="navbar" data-theme="a">
<ul>
<li>Home</li>
<li>Politics</li>
<li>Sports</li>
<li>Business</li>
</ul>
</div><!-- /Footernavbar --></div><!-- /footer -->
</div><!-- /Page Latest --></body>
</html>
As far as I understood. You want to show each news feed on a separate page on your webpage, and prevent the link from opening a new window (leaving your webpage).
You could do the following, of course it needs some tuning and CSS styling, which can be done easily. The below code, prevents opening the link a new window, - using preventDefault() - it copies feed details (title, image, full article..etc) and appending them to a new page dynamically.
Each page has an auto-generated ID, in case you want to navigate between them using Swipe events or any other methods.
Working example
Code:
var pageid = 0;
$('#ipaid').on('click', 'a', function (e) {
pageid++;
e.preventDefault();
var clicked = $(this);
var root = clicked.closest('li');
var linkto = clicked.attr('href');
var title = clicked.text();
var date = clicked.parent('div').next('div').text();
var linkdiv = root.find('div.itemTitle');
var datediv = root.find('div.itemDate');
var contentdiv = root.find('div.itemContent');
var image = contentdiv.first('div').find('img').attr('src');
var article = '';
contentdiv.find('p').each(function () {
article += $(this).text();
});
var newPage = $("<div data-role=page id='page" + pageid + "'><div data-role=header><a data-iconpos='left' data-icon='back' href='#' data-role='button' data-rel='back'>Back</a><h1>" + title + "</h1></div><div data-role=content><p>Date:" + date + "</p><img src='" + image + "'></div><div class='article'><p>" + article + "</p></div></div></div");
newPage.appendTo($.mobile.pageContainer);
$.mobile.changePage('#page' + pageid);
});
I think you simple need jFeed. Sample code from the jFeed site:
jQuery.getFeed(options);
options:
* url: the feed URL (required).
* data: data to be sent to the server. See jQuery.ajax data property.
* success: a function to be called if the request succeeds.
The function gets passed one argument: the JFeed object.
Example:
jQuery.getFeed({
url: 'rss.xml',
success: function(feed) {
alert(feed.title);
}
});

Categories