Insert form data into sqlite3 query without php in TideSDK - php

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

Related

getJSON within getJSON

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.

Generating tags to search for in Flickr API from database

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!

A button when pressed from another page reloads the page being viewed by all visitors. Which languages are needed to be learnt for this?

I'm learning JavaScript but I want the following thing in my little (self-started) project as soon as possible.
Suppose the page of my website is www.mywebsite.com/myPage.html
Here is a scenario that 10 users are viewing myPage.html from my website. As I make any change to myPage.html from server (being admin), I want all viewers of myPage.html to see refreshed page with new changes taken effect just after I make any change in myPage.html. It should be very fast.
For this I think I'll have to create a button which will refresh the page myPage.html. As I'll make changes to myPage.html, I'll press that button and that button will reload every viewer's browser's page (myPage.html). And they will see the result of modified myPage.html in their browsers.
Kindly explain your answer properly, since I'm a beginner. Which Languages are needed for this?
i think the best option here would be some kind of push implementation / web sockets ... here are a few links to get you started in the right direction ...
Websockets : Using modern HTML5 technology for true server push
Push Notifications to the Browser With Server Sent Events
In the case of socket.io in client side(browser) subscribe every client with a particular channel and make the page reload with javascript when request from server via that channel is recieved. And in server you can broadcast message to that particular channel whenever you want to reload the page.
you can create an AJAX function that is executing in intervals(like every 10 seconds) and this function will connect to server to ask for any update from mysql, so if there's any updates! you notify the user.
so you should create a table in DB to be updated with page update info when you update a page.
AJAX(asynchronous javascript and xml ) is a technology connect to your server without having to use Forms to post, and you can refresh part of your page automatically.
now here is an example:
I wanted to create an online chat, so here is the code:
this code use ajax to post to ChatNotifyController.php to see if theres anyone online,if there's any it will notify the user.
//notify user if someone has or had send a message
setInterval(function(){
xmlhttp.open("POST" , "../controller/ChatNotifyController.php" , true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
if((xmlhttp.response).length > 4)
{
var friendName = (xmlhttp.response).replace(/^\s*$[\n\r]{1,}/gm, '');
var responseArea = document.getElementById( friendName + 'ChatArea');
var x = friendName ;
if(x.indexOf('.') > 0)
{
x = x.replace('.', '\\.');
}
var link = $('#' + x);
var input = $('#' + x + 'ChatInput');
var e = jQuery.Event("keydown");
e.which = 13;
if(link.length > 0)
{
link.click();
input.trigger(e);
}
else
{
var html = "<li><a class=\"onlineUserLink\" id=\"" + friendName + "\" onclick=\"chat(" + "'" + friendName + "'" + ")\" >" + friendName + "</a></li>";
html += "<div class=\"chatDialog\" title=\"'" + friendName + "\"' id=\"'" + friendName + 'ChatDialog' + "'\">";
html += "<div class=\"chatArea\"" + " id=\"'" + friendName + "ChatArea" + "'\">" + "</div>";
html += "<input class=\"chatInput\"" + " id=\"'" + friendName + 'ChatInput' + "'\" size=\"21\" onkeydown=\"chatController(event , '" + friendName + "' , '" + window.user + "')>" + "</div>";
window.onlineArea.innerHTML += html;
var THIS = $('#' + x + 'ChatDialog');
$(function() {
THIS.dialog({
stack: false
});
});
link.click();
input.trigger(e);
}
}
}
else
{
//alert("Error during AJAX call. Please try again #003");
}
}
};
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("user=" + window.user);
} ,5000);

How to fit a longtext data type in a HTML table [duplicate]

I'm creating list dynamically in javascript. I want to break the long word in as dot dot dot(.....). For example, if the word is "Software life cycle development" I want to change it as "Software life cycl....".
And I used "WORD-BREAK:BREAK-ALL;white-space:normal;"
My current output is:
Software life cycle
development.
Can anyone tell, how to fix this? thanks in advance.
var parent = document.getElementById('searchlistview');
var listItem = document.createElement('li');
listItem.setAttribute('id', 'listitem_' + listId);
listItem.setAttribute('data-icon', 'false');
listItem.innerHTML = "<img src=" + imagesrc + " class='ui-li-icon ui-li-has-icon'></img>
<a target='_black' data-role='button' href='#' id=" + listId + " name= " + url + " data-theme ='c' rel='external'
data-inline='true' style='margin-left:0em; WORD-BREAK:BREAK-ALL;white-space:normal; ' >" + searchName + "<p style='margin-top:1px;margin-left:1px;'>
File size: " + fileSize + "</p></a>";
parent.appendChild(listItem);
You can try this css
text-overflow:ellipsis;
It would put ... when the text overflow. see this page for your reference.
see if css ellipsis can help you. You can find more details at
http://www.w3schools.com/cssref/css3_pr_text-overflow.asp
http://mattsnider.com/css/css-string-truncation-with-ellipsis/
style="text-overflow: ellipsis;"
will solve the problem.
Try:
function wbr(str, num) {
return str.replace(RegExp("(\\w{" + num + "})(\\w)", "g"), function(all,text,char){
return text + "<wbr>" + char;
});
}
Source: http://ejohn.org/blog/injecting-word-breaks-with-javascript/

Adding multiple variables in the page URL using javascript

Since I'm relativly new to the use of php and javascript I ran into this problem while trying to add multiple variables in a URL
I use the following script:
<script>
function refresh() {
var PCWDE = document.getElementById("PC");
var NMWDE = document.getElementById("naam");
var VNMWDE = document.getElementById("voornaam");
var ONDWDE = document.getElementById("onderneming");
var BTWWDE = document.getElementById("btwnummer");
var LNDWDE = document.getElementById("land");
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value "&nm=" + NMWDE.value "&vnm=" + VNMWDE.value "&ond=" + ONDWDE.value "&btw=" + BTWWDE.value "&lnd=" + LNDWDE.value;
}
</script>
That's beeing activated trough the following html code:
<?php
$pc = $_GET['PCS'];
echo '<input type="text" name="pc" id="PC" onblur="refresh()" value="'.$pc.'">'
?>
The main reason for the use of this html code was that I needed to execute a query without submitting the form, while still beeing able to hold the value of the text box even when the page would refresh. The above html code is used multiple times with the use of different ID's.
The problem I face while trying to do this is that my code only works when only adding 1 variable to the URL like so:
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value;
Otherwise it does not work. Either the 'onblur' event fails to work, or the script fails to run.
Is there a way to add the multiple variables to the URL in a similiar way to what i'm doing now?
You forgot plus signs. That's a syntax error and you should see the error message if you open the error console. (on firefox you press control-shift-j)
Shoule be:
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value + "&nm=" + NMWDE.value + "&vnm=" + VNMWDE.value + "&ond=" + ONDWDE.value + "&btw=" + BTWWDE.value + "&lnd=" + LNDWDE.value;

Categories