Data returns as "undefined" in Titanium - php

I am working on a basic authentication mobile app for iPhone using:
Titanium v. 3.23
XAMPP as my local server and PHP
MySQL as local database
The app I am working on is based off the following tutorial:
http://code.tutsplus.com/tutorials/titanium-user-authentication-part-1--mobile-3728
I was able to get the code up and running from the tutorial with no problem, the app allowed me to post a username/password key to my local database, login with the key, and have the information displayed on my main window.
I began to manipulate the code to reflect more of what I am attempting to build, a single window based app (not tab based like in the tutorial) that would allow me to create a username/password key, login to a main window, and on that main window have my information displayed back to me.
I have successfully been able to modify the code to allow me to create a new username/password into my local database, as well as have the app verify if the username/password match upon login. However, when I login to my main screen, it shows that my username and password are "undefined". To check the error, I entered the same user/pass in the project currently holding the working code and it is visible. So I know my current PHP and database are all working correctly.
Currently, my app.js is:
setTimeout (function() {
var login;
login = require ('login');
login.LogIn();
var mainWin = Titanium.UI.createWindow();
Ti.App.addEventListener('grantEntrance', function(event){
mainWin.title = 'Welcome ' + event.name;
mainWin.url = 'main.js';
mainWin.name = event.name;
mainWin.email = event.email;
});
}, 2000);
The setTimeout function is to eventually be a splash screen which I added independent from the tutorial above. I also changed the "main" items to reflect my mainWin, rather than the "main" as indicated in the tutorial.
Currently, my login.js is:
function LogIn(){
var loginWin = Ti.UI.createWindow({
backgroundColor:'white'
});
var username = Titanium.UI.createTextField({
color:'#336699',
top:10,
left:10,
width:300,
height:40,
hintText:'Username',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
loginWin.add(username);
var password = Titanium.UI.createTextField({
color:'#336699',
top:60,
left:10,
width:300,
height:40,
hintText:'Password',
passwordMask:true,
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
loginWin.add(password);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:110,
width:90,
height:35,
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
loginWin.add(loginBtn);
var createLabel = Titanium.UI.createLabel({
text:'Create Profile',
bottom: 25,
left:25
});
loginWin.add(createLabel);
var indicatorWin = Ti.UI.createView({
width: 320,
height: 480,
backgroundColor: '#000000',
opacity: 0.5
});
var acctInd = Ti.UI.createActivityIndicator({
height:50,
width:50,
style: Titanium.UI.createActivityIndicatorStyle.Plain,
top:250,
left:130
});
var actLabel = Titanium.UI.createLabel({
text: 'Checking Login Details',
color: '#FFFFFF',
left:70,
top:200,
height:50
});
indicatorWin.hide();
acctInd.hide();
actLabel.hide():
loginWin.add(indicatorWin);
indicatorWin.add(acctInd);
indicatorWin.add(actLabel);
var loginReq = Titanium.Network.createHTTPClient();
loginReq.onload = function()
{
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == true)
{
username.blur();
password.blur();
Ti.App.fireEvent('grantEntrance', {
name:response.name,
email:response.email
});
loginWin.close();
var main;
main = require ('main');
main.MainM();
}
else
{
alert(response.message);
}
};
loginBtn.addEventListener('click',function(e)
{
if (username.value != '' && password.value != '')
{
loginReq.open("POST","http://localhost/Tuts/post_auth.php");
var params = {
username: username.value,
password: Ti.Utils.md5HexDigest(password.value)
};
loginReq.send(params);
indicatorWin.show();
acctInd.show();
actLabel.show();
}
else
{
alert("Username/Password are required");
}
});
createLabel.addEventListener('click', function(e) {
var ProfileWin, ProfileInc;
ProfileInc = require ('createProfile');
ProfileWin = new ProfileInc.CreateP();
ProfileWin.open();
});
loginWin.open();
return ;loginWin;
}
exports.LogIn=LogIn;
Currently, my main.js is:
function MainM(){
var mainWin = Ti.UI.createWindow({
backgroundColor:'white'
});
var msg = Titanium.UI.createLabel({
text:"\n\nYour email is:\n" + mainWin.email + "\n\nyour name is:\n" + mainWin.name,
top:10,
left:10,
width:300,
height:'auto'
});
mainWin.add(msg);
mainWin.open();
return ;mainWin;
}
exports.MainM=MainM;
As you can see I haven't changed much, if anything, to the actual database section of the app. Which is why I am confused that it isn't working. The only research I have found indicated that there might be a problem with an asynchronous request and heard that by using a setTimeout function i might be able to get around my error. I have attempted to insert the function in a few places however the error still persists.
Sorry so long, I have been working on this for a month and I wanted to be as detailed as possible.
Thanks for the help!

In your code, main screen is a new Window, which does not have access to the variables email and name.
What you can do to fetch the values in the min win is either Save them in Properties and use them, or modify your main.js .

Related

Unable to run jsvascript until page refresh

I've started using ajax requests recently. I am making a mobile web application where I am to the request for data on PHP side server script. The javascript function is to automatically execute when the user navigates to the page. But the script seems not to run until I refresh the page, here is my javascript code.
<script>
$( document ).ready(function(){
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
function requestContent() {
var date = new Date();
$.ajax({
type:'POST',
url:'php/app/adminTimeline.php',
data:{
date: date.yyyymmdd()
},
success: function(data) {
if (data == '') {
alert("No data found!");
} else {
// $("#loading_spinner").css({"display":"none"});
$('#timeline-content').prepend(data);
}
},
error: function(data) {
// $("#loading_spinner").css({"display":"none"});
alert("Something went Wrong!");
}
});
}
window.onload = requestContent();
});
</script>
The document.onready method and window.onload the method seems not to be working too.
Ps: I have the Jquery library linked in the header too.
Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
https://learn.jquery.com/using-jquery-core/document-ready/
Also you're calling requestContent()
window.onload must be function, not returning value.
$(document).ready(function(){
// here you ajax
}
https://jsfiddle.net/cqfq5on5/1/
The code window.onload=requestContent(); will execute when the window loads, not necessarily when the entire document has loaded.
However where you create the date object, uses this, which executes after the document is fully loaded
$(document).ready(function(){
//Code
});
This means, that the POST request will be made once the window loads, which is before the document is fully loaded, thus, that date object will not exist until the page is refreshed, at which point the Javascript was likely cached. Also another answer (#sagid) pointed out, window.onload cannot be a returning value but must be a function.
i.e.
window.onload=function(){
//Code
};
This means, your solution is to change window.onload=requestContent(); to
$(document).ready(function(){
requestContent();
});
Good luck!

trouble with private messaging

Kindly Note: I know this might be a possible duplicate of other questions but i'd like help with my code!!
I'm trying to build a chat feature for my social network..I've used node.js and socket.io ...The prob with this code is that, the message is being delivered to every connected user instead of just the targeted to_user...The source of this code is from thenewboston tutorials...
I've built it as of now like this:
client.php
<div class="chat" hidden>
<textarea class="chat-name"><?php echo escape($data->username); ?></textarea>
<div class="chat-messages">
<?php
$chtrndr = $cht->renderchats(escape($data->id));
foreach ($chtrndr as $chtrndrs) {
echo '<div>' . $chtrndrs['m_from'] . ': ' . $chtrndrs['m_text'] . '</div><br>';
}
?>
</div>
<textarea class="chat-textarea" placeholder="Type your message"></textarea>
<div class="chat-status">Status:<span>Idle</span></div>
</div>
<!-- <script src="/socket.io/socket.io.js"></script> -->
<script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>
<script src="server.js"></script>
<script>
(function(){
var getNode = function(s) {
return document.querySelector(s);
},
//get required nodes
status = getNode('.chat-status span'),
messages = getNode('.chat-messages'),
textarea = getNode('.chat-textarea'),
chatName = getNode('.chat-name'),
statusDefault = status.textContent,
setStatus = function(s) {
status.textContent = s;
if(s!==statusDefault)
{
var delay = setTimeout(function(){
setStatus(statusDefault);
clearInterval(delay);
},3000);
}
};
setStatus('testing');
try {
var socket = io.connect('http://127.0.0.1:8080');
}
catch(e)
{
//set status to warn user
}
if(socket!==undefined)
{
//listen for output
socket.on('output',function(data){
if(data.length)
{
//loop through results
for(var x=0;x<data.length;x=x+1)
{
var message = document.createElement('div');
message.setAttribute('class','chat-message');
message.textContent = data[x].m_from + ': ' + data[x].m_text;
//append
messages.appendChild(message);
messages.insertBefore(message, messages.firstChild);
}
}
});
//listen for a status
socket.on('status',function(data){
setStatus((typeof data === 'object') ? data.message : data);
if(data.clear === true)
{
textarea.value = '';
}
});
//listen for keydown
textarea.addEventListener('keydown',function(event){
var self = this,
fname = <?php echo escape($_SESSION['user']); ?>,
tname = <?php echo $data->id; ?>;
if(event.which === 13 && event.shiftKey === false) {
socket.emit('input', {m_from:fname, m_to:tname, m_text:self.value});
event.preventDefault();
}
});
}
})();
</script>
And this is the server file:
SERVER.js
var client = require('socket.io').listen(8080).sockets;
var express = require('express');
var app = express();
var mysql = require('mysql');
var path = require('path');
var dbconn = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
app.use(express.static(path.resolve(__dirname, './css/')));
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});
dbconn.connect(function(err){
if(err){
console.log('Database connection error');
}else{
console.log('Database connection successful');
}
client.on('connection',function(socket){
console.log('Data received from Db');
sendStatus = function(s){
socket.emit('status',s);
};
//wait for input
socket.on('input',function(data){
var fname = data.m_from,
tname = data.m_to,
m_text = data.m_text,
whitespacePattern = /^\s*$/;
if(whitespacePattern.test(m_text))
{
sendStatus('message is required');
}
else
{
var record = { m_from: fname, m_to:tname, m_text: m_text };
dbconn.query('INSERT INTO messages SET ?', record, function(err,res){
if(err) throw err;
client.emit('output',[data]);
sendStatus({
message: "message sent",
clear: true
});
});
}
});
});
});
i wud like to add the following functionality:
*(a)*Since it is a social network, it shud be capable of serving private chats, betn 2 logged in users...
(b) The messages shud be received by the receiver after he logs back in at a later time..
I've combed many pages on google n SO already and heard that rooms are my go-to. But being a noob in nodejs, idk how to implement the rooms to make private messaging possible...
If any1 cud help me code it or even set me on the right path, frm where i can learn to code in node.js with easy tutorials for beginners, it wud b a really gr8 help!! Thanx in advance!
Look it should be like every user in your application should have unique id
LOGIC
1.you have to emit the event from your backend(server side) on output_userId
Your frontEnd (client side) should listen to the socket event on output_userId
what this will do is like you are emitting the message for the specific user from server side and every user will be listening on output_userId which is their specific id. where userId is there unique id of the project.
example:
we have 3 users
1,2,3
now if user 1 is sending message to user 2
your events should be like
Server Side
Socket.emit(output_1)
client side
every client side user should listen to their output_userid
for user 1 it should be output_1
for user 2 it should be output_2
for user 3 it should be output_3

Too many connections to db error, after adding an ajax auto save

I have PHP site with MySql data base
I just added automatic save for a text area
and one of the users received the following error:
Too many connections in ...Unable to connect to database
maybe I have to change my ajax auto save:
bkLib.onDomLoaded(function(){
var myEditor = new nicEditor({iconsPath : 'include/nicEdit/nicEditorIcons.gif'}).panelInstance('area1');
auto_save_func(myEditor);
});
function auto_save_func(myEditor)
{
draft_content=myEditor.instanceById('area1').getContent();
int_id='<?=$_GET[interview_id]?>';
$.post("ajax_for_auto_save_interview.php", { interview_id: int_id,content:draft_content},
function(data){ });
setTimeout( function() { auto_sav_func(myEditor); }, 100);
}
in the page "ajax_for_auto_save_interview.php" I`m including the connection to the DB.
First thing is you should close your mysql connection every time you open it after your usage.
You can have a javascript variable to check whether an AJAX call is already issued and is it finished or not. Only if it is finished, you can re-issue new call
Like this:
var isAjaxStarted = 0;
bkLib.onDomLoaded(function(){
var myEditor = new nicEditor({iconsPath : 'include/nicEdit/nicEditorIcons.gif'}).panelInstance('area1');
if(isAjaxStarted == 0)
auto_save_func(myEditor);
});
function auto_save_func(myEditor)
{
isAjaxStarted = 1;
draft_content=myEditor.instanceById('area1').getContent();
int_id='<?=$_GET[interview_id]?>';
$.post("ajax_for_auto_save_interview.php", { interview_id: int_id,content:draft_content},
function(data){ isAjaxStarted = 0; });
setTimeout( function() { auto_sav_func(myEditor); }, 100);
}
maybe I am writing late you help in place it? thank you very much
<script type="text/javascript">
bkLib.onDomLoaded(function() {
var myNicEditor = new nicEditor({buttonList : ['bold','italic','underline','strikethrough','left','center','right','justify',/*'ol','ul',*/'forecolor',/*'fontSize','fontFamily',*//*'fontFormat',*//*'indent','outdent',*/'image','upload','link','unlink'/*,'bgcolor'*/,'hr','removeformat', 'youTube'/*,'subscript','superscript'*/],/*fullPanel : true,*/
iconsPath : '<? echo "".$IndirizzoPagina."".$IndirizzoCartella."";?>default/image/EditorDiTesto/nicEditorIcons.gif'});
myNicEditor.setPanel('myNicPanel'); //PANNELLO DI CONTROLLO
myNicEditor.addInstance('titolo'); //TITOLO
myNicEditor.addInstance('contenuto'); //CONTENUTO
});
<textarea name='contenuto' id='contenuto' class='box2'>".$ContenutoNotizia."</textarea>"
i used this code http://nicedit.com/

calling on a complex function with onClick (ajax)

So I have this chunk of code here (below). It waits for a video to finish playing and then it looks up a cookie, sends that info to a php script through ajax, gets back a url from json, and reloads an iframe with a new url.
So I think you'll agree, it's sorta a lot going on.
Its purpose is to advance ONE forward in a playlist of videos. I am trying to create a button area where a user can click a >> sort of button and go forward. Which is exactly what this function does.
Rather than starting from scratch with a new function, is there a way to activate all of the above function functionality (ajax and all) when the user clicks that button?
<script>
function ready(player_id)
{
$f('play').addEvent('ready', function()
{
$f('play').addEvent('finish', onFinish);
});
function onFinish(play)
{
var now_video_var = $.cookie('now_video');
console.log ('player ' + now_video_var + ' has left the building');
var intermediate_integer = parseInt(now_video_var);
var request2 = $.ajax({
url : "geturl.php",
data : {intermediate_integer : intermediate_integer},
type : 'post'
}).done(function(data) {
var gotfrom = jQuery.parseJSON(data);
var NEWURL = gotfrom[1] ;
console.log(gotfrom);
console.log(data);
console.log(gotfrom[1]);
var theiframeforrealyo = document.getElementById('play');
$(theiframeforrealyo).attr("src", "http://player.vimeo.com/video/" + gotfrom[1] +"?api=1&player_id=play&title=0&byline=0&portrait=0&autoplay=1");
var new_video_var = intermediate_integer +1;
$.cookie('now_video', new_video_var);
console.log ( 'cookie function ok: the cookie is....');
console.log ($.cookie('now_video'));
});
}
}
window.addEventListener('load', function() {
//Attach the ready event to the iframe
$f(document.getElementById('play')).addEvent('ready', ready);
});
</script>

Use Jquery to update a PHP session variable when a link is clicked

I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/

Categories