I have had a search but not finding anything that is helping me solve my little issue. It would be nice if I was throwing some kind of error but the following code executes partially perfectly.
In essense, I have a list of train departure at a station (returned in JSON format by a custom API departures.php), but as I am looping through this returned array, I want to call a second custom API which brings up details of the service (based on a variable pulled from the first API which is the unique identifier) using service.php.
Here is an example of the service unique ID
Y5G8DkxFcxw7+xmbbBNM1g==
However the second getJSON returns nothing at all.. its as though it doesn't exist.. though the php API functionality perfectly if used on its own
Here is the code, any pointers greatly appreciated. PLease note I have stripped out a lot of the HTML that generates the view from departure.php returned data and just left the bare basics in.
NOTE : this is purely an experiment, and not a commercial product.
var $crs = GetURLParameter('crs');
$.getJSON('departures.php?crs='+$crs, function (data) {
var headertemplate = '<div class="col-md-6"><h2>Departure from ' + data.GetStationBoardResult.locationName + '</h2></div>';
var date = new Date(data.GetStationBoardResult.generatedAt);
var dateString = date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).substr(-2) + '-' + ("0" + date.getDate()).substr(-2);
var timeString = ("0" + date.getHours()).substr(-2) + ':' + ("0" + date.getMinutes()).substr(-2);
headertemplate += '<div class="col-md-6 text-right"><h2>Last updated: ' + timeString + ' </h2></div>';
$("#headerArea").html(headertemplate);
var template = '<table class="table">';
template += '<tbody>';
for (var i in data.GetStationBoardResult.trainServices.service) {
template += '<tr>';
template += '<td colspan="4">Calling at ';
$service = data.GetStationBoardResult.trainServices.service[i].serviceID;
$.getJSON('servicedetails.php?service='+$service, function (data2) {
for (var j in data2.GetServiceDetailsResult.subsequentCallingPoints.callingPointList.callingPoint) {
template += data2.GetServiceDetailsResult.subsequentCallingPoints.callingPointList.callingPoint[j].locationName;
template += ', ';
}
});
template += '</tr>';
}
template += '</tbody>';
template += '</table>';
$("#dataArea").html(template);
});
Just to follow this through, the URL sends a three letter string which is used to pull off the station departure which is an array.
The script generates the station information and returns into the div with id header.
The script then loops through all the departures, building up the template which it then injects into the div with id dataArea.
In each departure, the script pulls off the details of each service to list where the train will be calling at - THIS is the bit that is totally ignored.
Related
I'll try to keep this simple and clear. I'm pretty new to using API's but I'm using the Flickr API to search for and display photos on my website based on a certain tag. For a simple, static web page this is quite simple and I've already got it working as intended. This is the jquery script I found to use:
$(function() {
var apiKey = 'MY_API_KEY_IS_IN_HERE';
var tag = '%23FFLIVE2014-09-03';
var perPage = '25';
var showOnPage = '6';
$.getJSON('http://api.flickr.com/services/rest/?format=json&method='+
'flickr.photos.search&api_key=' + apiKey +
'&tags=' + tag + '&per_page=' + perPage + '&jsoncallback=?',
function(data){
var classShown = 'class="lightbox"';
var classHidden = 'class="lightbox hidden"';
$.each(data.photos.photo, function(i, rPhoto){
var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/'
+ rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret;
var thumbPhotoURL = basePhotoURL + '_s.jpg';
var mediumPhotoURL = basePhotoURL + '.jpg';
var photoStringStart = '<a ';
var photoStringEnd = 'title="' + rPhoto.title + '" href="'+
mediumPhotoURL +'"><img src="' + thumbPhotoURL + '" alt="' +
rPhoto.title + '"/></a>;'
var photoString = (i < showOnPage) ?
photoStringStart + classShown + photoStringEnd :
photoStringStart + classHidden + photoStringEnd;
$(photoString).appendTo("#flickr");
});
$("a.lightbox").lightBox();
});
});
Create a #flickr div on a page and load that script, photos tagged #FFLIVE2014-09-03 would be displayed, if there are any. My problem is that the site/page I want to show the photos on is dynamic with data generated from a database. So website.com/page.php is the single page, in the database is data for a certain date and a performance that happened on it (For a band).
So what I'm struggling with is how to dynamically edit the tags searched for in the script. With the above script placed in my page.php obviously page.php?id=1 and page.php?id=261 will show the same photos, because the tags searched will be the same when in fact they should be different, based on the date for the data.
So, is there some way to do this? Generate the correct date tag to search for based on the database data? I can generate the correct tag inside the PHP file itself quite easily, just echo the first part of the tag then the date. But how would I do that in relation to the javascript? I gather it is possible to use PHP within Javascript but that would be outside the database, so it wouldn't know what it was generating.
I hope that makes sense!
I've been wrestling with a problem that I just cannot seem to solve. I've got a web form that is built from a MySQL query that's run from PHP and returned to JQuery that displays a gallery of movies that the user can give a numeric rating. I'm wanting to send the form back to PHP for processing and writing to the database.
function loadGallery()
{
$('content').append('<form id="movieRatings" action="../php/saveRatings.php" method="post">).html();
$.get('../php/getMovies.php')
.done(function(data) {
var query = $.parseJSON(data);
for (var i = 0, len = query.length; i < len; i++) {
var galleryMovies = '<div class="movContainer">' +
'<div class="movie">' +
'<a title="' + query[i].mov_title + '" href="../' + query[i].mov_title + '.html">' +
'<h3>' + query[i].mov_title + '</h3>' +
'<img src="../imgs/' + query[i].poster_path + '" /></a>' +
'<input type="number" name="' + query[i].mov_title + '" >' +
'</div>' +
'</div>';
$('#content').append(galleryMovies).html();
}
$('#content').append('<input type="submit" value="Submit"></form>');
})
.fail(function() {
$('#content').html("Epic Fail!") ;
});
}
The form displays without any issues, but clicking the submit button doesn't even send the request for the "saveRatings" PHP file. I'm sure I'm missing something simple, I just can't seem to figure out what that is. My first thought was that it was because the gallery isn't part of the actual html, but from what I've read that shouldn't have anything to do with it.
And pointers/sugestions/insight would be appreciated.
instead of
$('#ID').click(function(){
// do something here
});
switch to
$(document).on("click", "#ID", function(){
// do smth here
});
Your first assumption was true, if the element is not part of the initial html, then any events bound to it won't work unless you go with my second approach. You can find more about this behavior in the jquery documentation.
L.E: same goes for the submit action, in case i was not clear with the click example:
$(document).on("submit", 'form#formID',function(){
// do smth here...
});
I have the code to dynamically generate the textboxes. I want to multiply the values of quantity and rate textboxes and display the result in total textbox and post it to next page.
The fiddle http://jsfiddle.net/hEByw/ that shows how textboxes are dynamically generated.
I have tried the following part of code to multiply the two textbox values but its not working for me. please see the fiddle for complete code.
//To multiply two textbox values
$('#qty + counter + ').keyup(calculate);
$('#rates + counter + ').keyup(calculate);
function calculate(e)
{
$('#total + counter + ').val($('#qty + counter +').val() * $('#rates + counter+').val());
}
Can any one suggest where am I going wrong or the correct way of doing it. I am new to jquery. Any help is appreciated.Thanks in advance.
I think the problem is here
$('#rates + counter + ')
It should be made to
$('#rates' + counter)
EDIT :
I analysed it with jsfiddle but the problem is with your logic. How can you get the counter when you are pressing a key. Counter will be used and it will be undefined once the controls are added.
Edit 2 :
At last I came up with the answer.
I had to tweak around a bit but that i hope it will satisfy you
Check This JsFiddle Link
Sorry for editing your own link
I just added a title attribute and i used it instead of the counter variable.
e.target.title For the counter
title = '+ counter + ' in your HTml
Refer the link. Hope this helps you
As long as you are using jquery 1.4+:
$('#qty' + counter).live('keyup', function(){ calculate(counter); });
$('#rates' + counter).live('keyup', function(){ calculate(counter); });
function calculate(counter)
{
total = Number($('#qty' + counter).val())*Number($('#rates' + counter).val())'
$('#total' + counter).val(total);
}
You never know the value of counter when the event triggers.
$('#qty' + counter).on("blur", function() {
calculate($(this));
});
$('#rates' + counter).on("blur", function() {
calculate($(this));
});
function calculate(el) {
var counter = el.attr("id").indexOf("qty") != -1 ? el.attr("id").substring(3) : el.attr("id").substring(5);
var qty = isNaN(parseInt($('#qty' + counter).val())) ? 0 : parseInt($('#qty' + counter).val());
var rate = isNaN(parseInt($('#rates' + counter).val())) ? 0 : parseInt($('#rates' + counter).val());
$("#total" + counter).val(qty * rate);
}
I have been searching for hours and it is probably just me being a novice but I am having a very hard time figuring out how to dynamically enter text into a sqlite3 query as they do not accept variables (or so I believe).
Here is what I am attempting to do:
A user can currently view recipes in my TideSDK app - the content of the recipe is generated from a file called recipes.db
This code loads an individual recipe into the main screen:
function doMainChange70() {
var db = Ti.Database.openFile(Ti.Filesystem.getFile(Ti.Filesystem.getApplicationDataDirectory(), 'recipes.db'));
var rows = db.execute("SELECT * FROM recipe WHERE number = '70'");
while (rows.isValidRow()) {
$('#foodFoto').empty();
$('#titleArea').empty();
$('#servings').empty();
$('#tagline').empty();
$('#ingredients').empty();
$('#directions').empty();
$('#nutrition').empty();
$('#foodFoto').append("<img src='foodPics/r" + rows.fieldByName('number') + ".jpg' />");
$('#titleArea').append("<p>" + rows.fieldByName('title') + '</p>');
$('#servings').append("<p>" + rows.fieldByName('servings') + '</p>');
$('#tagline').append("<p>" + rows.fieldByName('tagline') + '</p>');
//$('#ingredients').
$('#directions').append("<p>" + rows.fieldByName('directions') + '</p>');
$('#nutrition').append("<p>" + rows.fieldByName('nutrition') + '</p>');
$('#editBtn').remove();
$('#mainBtns').append("<a href='#' id='editBtn'" + 'onclick=' + 'editRecipe' + rows.fieldByName('number') + "()><img src='RecipeButton5.png' /></a>");
rows.next();
rows.close();
db.close();
return false;
}
}
I would now like the user to be able to edit the recipe. Currently when the edit button is clicked all of the fields of the recipe change to input tags and the user can edit:
function editRecipe70() {
$('#editBtn').removeAttr('onclick');
var db = Ti.Database.openFile(Ti.Filesystem.getFile(Ti.Filesystem.getApplicationDataDirectory(), 'recipes.db'));
var rows = db.execute("SELECT * FROM recipe WHERE number = '70'");
while (rows.isValidRow()) {
$('#editBtn').html("<img src='saveRecipeButton.png' />");
$('#formContainer').empty();
$('#formContainer').append("<form id='sendEdit'><textarea type='text' name='title' id='title'>" + rows.fieldByName('title') + "</textarea><br>" + "<textarea type='text' name='servings'>" + rows.fieldByName('servings') + "</textarea><br>" + "<textarea type='text' name='tagline'>" + rows.fieldByName('tagline') + "</textarea><br>" + "<textarea type='text' name='directions'>" + rows.fieldByName('directions') + "</textarea><br>" + "<textarea type='text' name='nutrition'>" + rows.fieldByName('nutrition') + "</textarea><br>" + "<input type='submit'></form>");
}
My problem is that at this point I can't figure out a way to capture what the user has placed in the input fields (or more accurately textareas) and place it into the sqlite3 query string.
I am able to query the db in js with something like this:
UPDATE recipeTable SET title='best recipe ever' WHERE number='70';
But nothing like this (which is what I need):
UPDATE recipeTable SET title = '[formValueForTitle]' WHERE number = '70';
Hopefully I am making sense, I do apologize it is my first question. I have looked at many posts here on the site and the immediate solution would seem to be preprocessing the form values using php but I have read the php module in TideSDK doesn't have sqlite3 support right now and I have been unable to bring the processed code back into the index.html to run in js.
So long and short, I would like to figure out a way to let users edit recipes and I am totally stuck. Any direction would be much appreciated!
Thank You
This is how I'd do it:
var inputfromform = 'I got this back from the form';
var number = 7;
db = Ti.Database.open(dbname); // or openFile etc
db.execute("BEGIN IMMEDIATE TRANSACTION;");
db.execute("UPDATE recipeTable SET title = ? WHERE number = ?;", inputfromform, number);
db.execute("COMMIT TRANSACTION;");
db.close();
Hope this helps
Consider the following script which is used for counting twitter followers. For some reason I get the list twice. I just want the follower count stats for the elements in the array. Any help is greatly appreciated.
echo "<div id='twitter'>
<script type='text/javascript'>
$(document).ready(function(){
var i;
twitterusername = ['Sinbg','followfog','miniclip','vgames'];
for(i=0; i<4; i++){
(function(i){
$.getJSON('http://twitter.com/users/' + twitterusername[i] + '.json?callback=?',
function(data){
$('#twitter').html( document.getElementById('twitter').innerHTML + twitterusername[i] + ' ' +
data.followers_count + ' Followers' + '<br/>');
}
) // end getJSON
})(i);
}// end for??
});</script></div>";
Move the script-tag out of the twitter-div.
Here the example with the script inside.
Here with the script after the div.
I can't reproduce the error with the code you've posted:
http://jsfiddle.net/mLCHX/
You might want to check your php code to see if you are outputting the javascript twice.
Another option would be to clear the contents of #twitter before getting the info.