cordova save contact if not exist by phone number - javascript

I'm trying to save phonebook (with phone number as primary index) contact when it doesn't exist.
I have tried to check the contact with navigator. contacts. finds ()`, and check length is 0 (if not in contact, save contact) but seems it does not work.
sometime my ionic app will save double (or more than 2) contact in the phonebook, and it will like, 103 same phone numbers in my phonebook.
code :
var app = {
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
this.receivedEvent('deviceready');
document.getElementById("call").addEventListener("click", ayam);
cordova.plugins.backgroundMode.enable();
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
app.initialize();
function dialogAlert() {
var message = "Sync Android Contact has been activated!";
var title = "Info";
var buttonName = "Close";
navigator.notification.alert(message, alertCallback, title, buttonName);
function alertCallback() {
console.log("Alert is Dismissed!");
}
}
function ayam() {
if($(".aba").val().length > 3) {
setInterval(function(){
kambing();
}, 5000); // recheck server every 5 second
dialogAlert();
}
else {
alert("Write your API Url !");
}
}
function kambing(){
var url = $(".aba").val();
$.ajax({
type : "GET",
url : url + "/save",
dataType : 'html',
success: function(response){
var hp = response
, anu = hp.split(",");
anu.forEach(function(v){
save_contact(v);
})
},
error : function() {
alert("Failed to fetch url");
}
});
}
function save_contact(xs){
var pn = xs.replace(/\D/g,'');
if(pn.length > 3) {
var options = new ContactFindOptions();
options.filter = xs;
options.multiple = true;
options.desiredFields = [navigator.contacts.fieldType.id];
options.hasPhoneNumber = true;
var fields = [navigator.contacts.fieldType.phoneNumbers];
navigator.contacts.find(fields, onSuccess, onError, options);
function onSuccess(contacts) {
if(contacts.length < 1) {
var myContact = navigator.contacts.create({"displayName": "The New Contact"});
var name = new ContactName();
name.givenName = xs;
myContact.name = name;
var phoneNumbers = [];
//phoneNumbers[0] = new ContactField('work', '212-555-1234', false);
phoneNumbers[0] = new ContactField('mobile', pn, true); // preferred number
//phoneNumbers[2] = new ContactField('home', '203-555-7890', false);
myContact.phoneNumbers = phoneNumbers;
myContact.note = "Helo";
myContact.save(sukses, elor);
function sukses(contact) {
//alert("saved")
$.ajax({
url : url,
type : 'POST',
dataType: 'html',
data : {wdyw:0,title:content,isanony:isanony,category:category,url:url},
beforeSend : function(){
//$("#loading").show();
},
success : function(result){
$('[name="content"]').val('');
$('[name="content"]').val('Pertanyaan anda telah terkirim :)');
setTimeout(function(){$('[name="content"]').val('');},500);
}
});
};
function elor(contactError) {};
}
};
function onError(contactError) {
return false;
};
}
}

Rewrite to ionic, (because more stable)

Related

Assign jquery plugin to dropdown not working

I am creating an audio player that have 4 dropdown lists each depends on each other to get the right mp3 file, the jquery code works fine until i assign a plugin to the dropdown called (fancyspinbox) to look better.
The problem is the dropdown dont update its value though its triggered successfully.
Kindly find my code below
<script>
$(document).ready(function () {
$('#ddbibletype').fancyspinbox();
$('#ddtestament').fancyspinbox();
$("#booksdd").fancyspinbox();
$("#chapterdd").fancyspinbox();
});
$("#ddtestament").change(function () {
var options = {};
options.url = '#Url.Action("GetBooks", "Home")';
options.type = "POST";
if ($("#ddtestament option:selected").index() == 0)
options.data = JSON.stringify({ testament: 'OT' });
else
options.data = JSON.stringify({ testament: 'NT' });
options.dataType = "json";
options.contentType = "application/json; charset=utf-8";
options.success = function (jsonResult) {
$("#booksdd").empty();
$("#chapterdd").empty();
var jb = $(jsonResult.jbooks);
var jc = $(jsonResult.jchapters);
for (var i = 0; i < jb.length; i++) {
$("#booksdd").append("<option>" + jb[i] + "</option>");
}
for (var i = 0; i < jc.length; i++) {
$("#chapterdd").append("<option>" + jc[i] + "</option>");
}
$("#booksdd").change();
};
options.error = function () { alert("Error retrieving Books!"); };
$.ajax(options);
});
$("#booksdd").change(function () {
var options = {};
options.url = '#Url.Action("GetChapters", "Home")';
options.type = "POST";
if ($("#ddtestament option:selected").index() == 0)
options.data = JSON.stringify({ bookID: $("#booksdd option:selected").index() });
else
options.data = JSON.stringify({ bookID: ($("#booksdd option:selected").index() + 39) });
options.dataType = "json";
options.contentType = "application/json; charset=utf-8";
options.success = function (chapters) {
$("#chapterdd").empty();
for (var i = 0; i < chapters.length ; i++) {
$("#chapterdd").append("<option>" + chapters[i] + "</option>");
}
$("#chapterdd").prop("disabled", false);
$("#chapterdd").change();
};
options.error = function () { alert("Error retrieving chapters!"); };
$.ajax(options);
});
$("#chapterdd").change(function () {
var options = {};
options.url = '#Url.Action("GetTrackPath", "Home")';
options.type = "POST";
if ($("#ddtestament option:selected").index() == 0)
options.data = JSON.stringify({ bibleType: $("#ddbibletype option:selected").index(), bookID: $("#booksdd option:selected").index() + 1, chapterNum: $("#chapterdd option:selected").index() + 1 });
else
options.data = JSON.stringify({ bibleType: $("#ddbibletype option:selected").index(), bookID: ($("#booksdd option:selected").index() + 40), chapterNum: $("#chapterdd option:selected").index() + 1 });
options.dataType = "json";
options.contentType = "application/json; charset=utf-8";
options.success = function (trackpath) {
var audio = $('#bibleplayer');
$('#mpsource').attr('src', trackpath);
audio[0].pause();
audio[0].load();//suspends and restores all audio element
audio[0].oncanplaythrough = audio[0].play();
};
options.error = function () {
alert("Error retrieving Books!");
};
$.ajax(options);
});
I'm assuming you are using this fancyspingbox? https://github.com/mayakokits/jquery.fancyspinbox
There is no mention there of needing to add different event listeners, but they do mention "If you need to access the spinbox element, use the element object.". Possibly that is the solution
ie this line
$("#ddtestament").change(function () {
becomes
$("#ddtestament").element.change(function () {
or
$($("#ddtestament").element).change(function () {
as do the other similar lines.

Send object id from success function to another function in parse.com

I have a problem on parse.com in which i to take the id of an type and pass it to another function which uploads an image. Then take the type.id among with the image and post it to another function which saves the data to a class.
This is what i've tried until now without success.
--OnClick code
$('#submitId').on("click", function(e, f) {
e.preventDefault();
typeSave(typeid1);
//var objnew1 = typeSave();
console.log("inside onclick " + type2);
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
parseFile.save().then(
function() {
//typeSave();
type2 = typeid1;
saveJobApp(parseFile, type2);
console.log("inside save onclick " + type2);
},
function(error) {
alert("error");
}
);
});
-- Type Code
var type;
var typeid1;
var type2;
function typeSave() {
var type = new Parse.Object("type");
var user = new Parse.Object("magazia");
//var bID = objbID;
//user.id = bID;
var cafebar = document.getElementById('cafe_bar').checked;
if (cafebar) {
var valueCafebar = true;
} else {
var valueCafebar = false;
}
var club = document.getElementById('club').checked;
if (club) {
var valueClub = true;
} else {
var valueClub = false;
}
var restaurant = document.getElementById('restaurant').checked;
if (restaurant) {
var valueRestaurant = true;
} else {
var valueRestaurant = false;
}
var pistes = document.getElementById('pistes').checked;
if (pistes) {
var valuePistes = true;
} else {
var valuePistes = false;
}
type.set("cafebar", valueCafebar);
type.set("club", valueClub);
type.set("restaurant", valueRestaurant);
type.set("pistes", valuePistes);
type.save(null, {
success: function(type) {
//saveJobApp(type.id);
var typeid1 = type.id;
console.log("inside type save " + typeid1);
//return ;
},
error: function(type, error) {
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
-- Send Data to parse.com class code
function saveJobApp(objParseFile, type2) {
var jobApplication = new Parse.Object("magazia");
var email = document.getElementById('email').value;
var name = document.getElementById('name').value;
var description = document.getElementById('description').value;
var website = document.getElementById('website').value;
var phone = document.getElementById('phone').value;
var address = document.getElementById('address').value;
var latlon = document.getElementById('latlon').value;
var area = document.getElementById('area').value;
var value = latlon;
value = value.replace(/[\(\)]/g, '').split(', ');
console.log("inside saveJobApp " + type2);
var x = parseFloat(value[0]);
var y = parseFloat(value[1]);
var point = new Parse.GeoPoint(x, y);
jobApplication.set("image", objParseFile);
jobApplication.set("email", email);
jobApplication.set("phone", phone);
jobApplication.set("address", address);
jobApplication.set("name", name);
jobApplication.set("website", website);
jobApplication.set("description", description);
jobApplication.set("area", area);
jobApplication.set("latlon", point);
jobApplication.set("typeID", type2);
jobApplication.save(null, {
success: function(gameScore) {
// typeSave(jobApplication.id);
},
error: function(gameScore, error) {
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
So resuming i am trying when i click the button to first run the typesave() function, after when it posts the type on the type class in parse, to take to type.id from the success function and send it to the parseFile.save().then
and then to send the objectFile and the type2 (which is the type.id) it in saveJobApp and them to save it in class magazia
What i get from the console.logs is this
Which means that my code post to the type class and takes the type.id
but it doesnt send it to the magazia class via the parsefile save.
Any idea of what am i missing?
I noticed your mistake is not about the functions but about trying to pass the type.id as a string and not as a function in the saveJobApp function.
if you try making it like this
function saveJobApp(objParseFile , objtype) {
var jobApplication = new Parse.Object("magazia");
var type = new Parse.Object("type");
type.id = objtype;
jobApplication.set("typeID", type);
I think it will work.
And also update the onclick and the ParseFile save code to this
$('#submitId').on("click", function(e) {
typeSave();
});
function PhotoUpload(objtype){
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
parseFile.save().then(
function() {
saveJobApp(parseFile, objtype);
},
function(error) {
alert("error");
}
);
}
And the success function in typeSave()
should be something like this
type.save(null, {
success: function(type) {
PhotoUpload(type.id);
},
Hope this helps :)

Getting reference to object that run function in JavaScript

I'm trying to use jQuery extension to check if servers are alive or not.
Extension in here: https://gist.github.com/jerone/3487795
My code so far:
// Device scanner class
function deviceScanner(list){
this.list = list;
this.totalDevices = list.length;
this.scan = function () {
for(var i = 0; i < this.totalDevices; i++){
$.Ping(list[i],1000)
.done( function(success, url, time, on) {
found(url);
})
.fail( function(success, url, time, on) {
notFound(url);
});
}
}
this.found = function (address){
alert(address);
}
this.notFound = function (address){
alert(address);
}
}
var scanner = new deviceScanner([KVMRxDefaultIP, KVMTx1DefaultIP, KVMTx2DefaultIP]);
$("#bt1").click(function(){
scanner.scan();
});
How shall i make Ping done or fail store result in deviceScanner?
// Device scanner class
function deviceScanner(list){
var me = this; // HERE (1)
this.list = list;
this.totalDevices = list.length;
this.scan = function () {
for(var i = 0; i < this.totalDevices; i++){
$.Ping(list[i],1000)
.done( function(success, url, time, on) {
me.property_done = true; // HERE (2)
found(url);
})
.fail( function(success, url, time, on) {
me.property_failed = true; // HERE (3)
notFound(url);
});
}
}
this.found = function (address){
alert(address);
}
this.notFound = function (address){
alert(address);
}
}
var scanner = new deviceScanner([KVMRxDefaultIP, KVMTx1DefaultIP, KVMTx2DefaultIP]);
$("#bt1").click(function(){
scanner.scan();
});

Backbone trigger() returning typeError

I keep getting the following error from calling an event from my model:
window.Playlist = new PlaylistModel();
Playlist.trigger("playerPlaying");
`Uncaught TypeError: Cannot read property '0' of undefined`
My stack trace:
Uncaught TypeError: Cannot read property '0' of undefined
triggerEventsbackbone.js:206
Backbone.Events.triggerbackbone.js:148
onPlayerStateChangeplayer.js:101
g.Iwww-widgetapi-vfldqBTcy.js:13
g.kwww-widgetapi-vfldqBTcy.js:22
g.Jwww-widgetapi-vfldqBTcy.js:30
X.dwww-widgetapi-vfldqBTcy.js:29
Qa.fwww-widgetapi-vfldqBTcy.js:18
I dig in backbone source code and find the following
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
I printed the lines one by one after setting a breakpoint from chrome console.
arguments = ["playerPlaying"]
args = []
this._events = Object {change:currentSong: Array[3], change:loopActive: Array[3], playerPlaying: Array[3]}
events = [Object, Object, Object]
this = the Backbone model on which `trigger()` was called
I think the problem is that arguments should be [ModelThatTriggeredEvent, eventName] but I am only getting [eventName] so args becomes an empty array. Does anyone know why this is happening?
Update:
Here's the entire PlaylistModel with some parts deleted. Please understand the mess in the code as I am in the middle of refactoring it to abide by the Backbone way of doing things.
define([
// These are path alias that we configured in our bootstrap
'jquery', // lib/jquery/jquery
'backbone',
'../../common/models/song',
'../collections/songs'
], function($, Backbone, Song, Songs){
window.AVAILABLE_CHARTS = {
billboardChart: {
source: "billboard",
chart: [
{genre: chrome.i18n.getMessage("pop"), url: 'http://www.billboard.com/rss/charts/hot-100'},
{genre: chrome.i18n.getMessage("rock"), url: "http://www.billboard.com/rss/charts/rock-songs"},
]
}
};
var Playlist = Backbone.Model.extend({
defaults: {
currentSong: null,
nextSong: null,
prevSong: null,
genre: null, // initial genre
loopActive: false,
shuffleActive: false,
numSongs: 10, // initial number of songs loaded
musicChart: null
},
initialize: function() {
// Setting collections/songs as its attribute
var songs = new Songs();
this.set('songs', songs);
var userLocale = chrome.i18n.getMessage("##ui_locale");
if (userLocale == "ko" || userLocale == 'ko-kr') {
this.set('musicChart', AVAILABLE_CHARTS.melonChart);
this.set('genre', this.get('musicChart').chart[0].genre);
} else {
this.set('musicChart', AVAILABLE_CHARTS.billboardChart);
this.set('genre', this.get('musicChart').chart[0].genre);
}
},
// If loop is active, getNextSong repeats the current song
// If shuffle is active, getNextSong plays a random song from Songs
getNextSong: function() {
//var idx = this.indexOf(this.getCurrentSong());
var songs = this.get('songs');
var idx = songs.indexOf(songs.findWhere({ title: this.get('currentSong').get('title') }));
if (this.get('loopActive')) {
return songs.at(idx);
}
if (this.get('shuffleActive')) {
var randomIndex = Math.floor((Math.random()*songs.length));
return songs.at(randomIndex);
}
if (idx != songs.length-1) return songs.at(idx+1);
else return songs.at(0);
},
getPrevSong: function() {
var songs = this.get('songs');
var idx = songs.indexOf(songs.findWhere({ title: this.get('currentSong').get('title') }));
if (idx != 0) return songs.at(idx-1);
else return songs.at(songs.length-1);
},
// Get new songs from Billboard Chart
// First parse the top <numSongs> from the selected <genre>
// from Billboard, and then use YouTube gdata api to fetch
// the songs.
getNewSongs: function (callback, genre, numSongs) {
// FIXME: just trigger progress
var popupWindow = chrome.extension.getViews({ type: "popup" })[0];
if (popupWindow && popupWindow.popupView) popupWindow.popupView.setProgress(10);
var playlist = this;
playlist.get('songs').reset();
// Inspect Billboard Chart to find pop songs
$.get(url+numSongs+'/explicit=true/xml', function (data) {
var popupWindow = chrome.extension.getViews({ type: "popup" })[0];
if (popupWindow && popupWindow.popupView) popupWindow.popupView.setProgress(30);
var $feed = $(data).find('feed')
var $entries = $feed.find('entry')
var numAvailableSongs = $entries.length;
$entries.each(function (idx, entry) {
var title_artist_pair = $(entry).find('title')[0].innerHTML;
var title = $.trim(title_artist_pair.split(' - ')[0]);
var artist = $.trim(title_artist_pair.split(' - ')[1]);
var rank = idx+1;
var query = title + " " + artist;
_searchYouTube(title, artist, rank, query, numAvailableSongs);
});
return;
});
}
function _searchYouTube (title, artist, rank, query, numAvailableSongs) {
var songs = playlist.get('songs');
$.ajax({
url: searchUrl,
type: "GET",
data: 'q='+encodeURIComponent(query),
success: function (result) {
//console.log("\n**** 검색: "+query);
ajaxCount += 1;
if (result.items.length)
var videoId = result.items[0].id.videoId;
else
var videoId = null; // Cannot find the song on YouTube
var song = new Song({
title: title,
artist: artist,
rank: parseInt(rank),
query: query,
videoId: videoId
});
// Insert songs into the playlist in the order of their ranks
// *Note: Songs that do not exist on YouTube are ignored
if (videoId) songs.add(song, { silent: true });
// All the ajax calls are finished
if (ajaxCount == numAvailableSongs) {
var popupWindow = chrome.extension.getViews({ type: "popup" })[0];
if (popupWindow && popupWindow.popupView) popupWindow.popupView.setProgress(70);
songs.comparator = 'rank'
songs.sort();
// Remove useless playlsit methods
if (!playlist.get('currentSong')) {
playlist.set('currentSong', songs.at(0));
}
callback();
}
},
error: function (error) {
ajaxCount += 1;
if (ajaxCount == numAvailableSongs) {
var popupWindow = chrome.extension.getViews({ type: "popup" })[0];
if (popupWindow) popupWindow.popupView.setProgress(70);
if (!playlist.get('currentSong')) {
playlist.set('currentSong', songs.at(0));
}
callback();
}
} // end of error
}); // end of second ajax
} // end of _searchYouTube()
},
lookUpAndAddSingleSong: function (query) {
var playlist = this;
var youtubeAPIKey = "fdf";
var initialSearchURL = "df";
var searchUrl = initialSearchURL + "&key=" + youtubeAPIKey;
$.ajax({
url: searchUrl,
type: "GET",
data: 'q='+encodeURIComponent(query),
success: function (result) {
if (result.items.length) {
var videoId = result.items[0].id.videoId;
var song = new Song({
title: result.items[0].snippet.title,
query: query,
videoId: videoId
});
} else var videoId = null; // Cannot find the song on YouTube
if (videoId) {
playlist.get('songs').add(song);
song.save(); // save to localStorage
}
}, error: function (xhr, status, errorThrown) {
var errorMessage = "lookUpAndAddSingleSong error: check http://instantmusicapp.com";
var popupWindow = chrome.extension.getViews({ type: "popup" })[0];
if (popupWindow && popupWindow.popupView) popupWindow.showErrorMessage(errorMessage);
return;
}
});
},
setMusicChart: function (chartName) {
// if the chart is provided, we pick from Melon, Billboard, iTunes
if (chartName) {
if (chartName == chrome.i18n.getMessage("melonChart"))
this.set('musicChart', AVAILABLE_CHARTS.melonChart);
else if (chartName == chrome.i18n.getMessage("billboardChart"))
this.set('musicChart', AVAILABLE_CHARTS.billboardChart);
else
this.set('musicChart', AVAILABLE_CHARTS.itunesChart);
// else, the user is looking for a personal favorite chart
} else {
this.set('musicChart', AVAILABLE_CHARTS.myChart);
}
},
});
return Playlist;
});
There are quite a few syntax errors in your model which is probably why you are being prevented from issuing a trigger with or even anything else from your bb model.
line 14 has a dangling comma (,) for instance.
try running your model through JSLint or JSHint and fixing the errors. will probably fix your issue
Dangling comma is acceptable in most of the browsers, but actual error was an extra } after getNewSongs function. I suggest using some IDE/Editor which supports JSHint integration. You can try webstorm. Here is the updated code.
define([
// These are path alias that we configured in our bootstrap
'jquery', // lib/jquery/jquery
'backbone',
'../../common/models/song',
'../collections/songs'
], function ($, Backbone, Song, Songs) {
window.AVAILABLE_CHARTS = {
billboardChart: {
source: "billboard",
chart: [
{genre: chrome.i18n.getMessage("pop"), url: 'http://www.billboard.com/rss/charts/hot-100'},
{genre: chrome.i18n.getMessage("rock"), url: "http://www.billboard.com/rss/charts/rock-songs"},
]
}
};
var Playlist = Backbone.Model.extend({
defaults: {
currentSong: null,
nextSong: null,
prevSong: null,
genre: null, // initial genre
loopActive: false,
shuffleActive: false,
numSongs: 10, // initial number of songs loaded
musicChart: null
},
initialize: function () {
// Setting collections/songs as its attribute
var songs = new Songs();
this.set('songs', songs);
var userLocale = chrome.i18n.getMessage("##ui_locale");
if (userLocale == "ko" || userLocale == 'ko-kr') {
this.set('musicChart', AVAILABLE_CHARTS.melonChart);
this.set('genre', this.get('musicChart').chart[0].genre);
} else {
this.set('musicChart', AVAILABLE_CHARTS.billboardChart);
this.set('genre', this.get('musicChart').chart[0].genre);
}
},
// If loop is active, getNextSong repeats the current song
// If shuffle is active, getNextSong plays a random song from Songs
getNextSong: function () {
//var idx = this.indexOf(this.getCurrentSong());
var songs = this.get('songs');
var idx = songs.indexOf(songs.findWhere({ title: this.get('currentSong').get('title') }));
if (this.get('loopActive')) {
return songs.at(idx);
}
if (this.get('shuffleActive')) {
var randomIndex = Math.floor((Math.random() * songs.length));
return songs.at(randomIndex);
}
if (idx != songs.length - 1) return songs.at(idx + 1);
else return songs.at(0);
},
getPrevSong: function () {
var songs = this.get('songs');
var idx = songs.indexOf(songs.findWhere({ title: this.get('currentSong').get('title') }));
if (idx != 0) return songs.at(idx - 1);
else return songs.at(songs.length - 1);
},
// Get new songs from Billboard Chart
// First parse the top <numSongs> from the selected <genre>
// from Billboard, and then use YouTube gdata api to fetch
// the songs.
getNewSongs: function (callback, genre, numSongs) {
// FIXME: just trigger progress
var popupWindow = chrome.extension.getViews({ type: "popup" })[0];
if (popupWindow && popupWindow.popupView) popupWindow.popupView.setProgress(10);
var playlist = this;
playlist.get('songs').reset();
// Inspect Billboard Chart to find pop songs
$.get(url + numSongs + '/explicit=true/xml', function (data) {
var popupWindow = chrome.extension.getViews({ type: "popup" })[0];
if (popupWindow && popupWindow.popupView) popupWindow.popupView.setProgress(30);
var $feed = $(data).find('feed')
var $entries = $feed.find('entry')
var numAvailableSongs = $entries.length;
$entries.each(function (idx, entry) {
var title_artist_pair = $(entry).find('title')[0].innerHTML;
var title = $.trim(title_artist_pair.split(' - ')[0]);
var artist = $.trim(title_artist_pair.split(' - ')[1]);
var rank = idx + 1;
var query = title + " " + artist;
_searchYouTube(title, artist, rank, query, numAvailableSongs);
});
return;
});
function _searchYouTube(title, artist, rank, query, numAvailableSongs) {
var songs = playlist.get('songs');
$.ajax({
url: searchUrl,
type: "GET",
data: 'q=' + encodeURIComponent(query),
success: function (result) {
//console.log("\n**** 검색: "+query);
ajaxCount += 1;
if (result.items.length)
var videoId = result.items[0].id.videoId;
else
var videoId = null; // Cannot find the song on YouTube
var song = new Song({
title: title,
artist: artist,
rank: parseInt(rank),
query: query,
videoId: videoId
});
// Insert songs into the playlist in the order of their ranks
// *Note: Songs that do not exist on YouTube are ignored
if (videoId) songs.add(song, { silent: true });
// All the ajax calls are finished
if (ajaxCount == numAvailableSongs) {
var popupWindow = chrome.extension.getViews({ type: "popup" })[0];
if (popupWindow && popupWindow.popupView) popupWindow.popupView.setProgress(70);
songs.comparator = 'rank'
songs.sort();
// Remove useless playlsit methods
if (!playlist.get('currentSong')) {
playlist.set('currentSong', songs.at(0));
}
callback();
}
},
error: function (error) {
ajaxCount += 1;
if (ajaxCount == numAvailableSongs) {
var popupWindow = chrome.extension.getViews({ type: "popup" })[0];
if (popupWindow) popupWindow.popupView.setProgress(70);
if (!playlist.get('currentSong')) {
playlist.set('currentSong', songs.at(0));
}
callback();
}
} // end of error
}); // end of second ajax
} // end of _searchYouTube()
},
lookUpAndAddSingleSong: function (query) {
var playlist = this;
var youtubeAPIKey = "fdf";
var initialSearchURL = "df";
var searchUrl = initialSearchURL + "&key=" + youtubeAPIKey;
$.ajax({
url: searchUrl,
type: "GET",
data: 'q=' + encodeURIComponent(query),
success: function (result) {
if (result.items.length) {
var videoId = result.items[0].id.videoId;
var song = new Song({
title: result.items[0].snippet.title,
query: query,
videoId: videoId
});
} else var videoId = null; // Cannot find the song on YouTube
if (videoId) {
playlist.get('songs').add(song);
song.save(); // save to localStorage
}
}, error: function (xhr, status, errorThrown) {
var errorMessage = "lookUpAndAddSingleSong error: check http://instantmusicapp.com";
var popupWindow = chrome.extension.getViews({ type: "popup" })[0];
if (popupWindow && popupWindow.popupView) popupWindow.showErrorMessage(errorMessage);
return;
}
});
},
setMusicChart: function (chartName) {
// if the chart is provided, we pick from Melon, Billboard, iTunes
if (chartName) {
if (chartName == chrome.i18n.getMessage("melonChart"))
this.set('musicChart', AVAILABLE_CHARTS.melonChart);
else if (chartName == chrome.i18n.getMessage("billboardChart"))
this.set('musicChart', AVAILABLE_CHARTS.billboardChart);
else
this.set('musicChart', AVAILABLE_CHARTS.itunesChart);
// else, the user is looking for a personal favorite chart
} else {
this.set('musicChart', AVAILABLE_CHARTS.myChart);
}
}
});
return Playlist;
});

json response is not open in new window

I want to open the json response in to the new window, i tried a lot but didn't get ant success, if any one can helps me, it will be appreciated.
this is my app.js code
Titanium.UI.setBackgroundColor('#fff');
var tabGroup = Titanium.UI.createTabGroup();
var login = Titanium.UI.createWindow({
title:'User Authentication Demo',
tabBarHidden:true,
url:'main_windows/login.js'
});
var loginTab = Titanium.UI.createTab({
title:"Login",
window:login
});
tabGroup.addTab(loginTab);
tabGroup.open();
and this is my login.js code
var win = Titanium.UI.currentWindow;
var UserLogin = Titanium.UI.createTextField({
color:'#336699',
top:10,
left:10,
width:300,
height:40,
hintText:'UserLogin',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(UserLogin);
var UserPassword = Titanium.UI.createTextField({
color:'#336699',
top:60,
left:10,
width:300,
height:40,
hintText:'UserPassword',
passwordMask:true,
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(UserPassword);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:110,
width:90,
height:35,
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
win.add(loginBtn);
/*
* Login Event Handling
*/
var loginReq = Titanium.Network.createHTTPClient();
var data, User, UserName, UserEmail, UserFirstName, UserLastName, UserAvatar, BioGraphyNative,BioGraphyEnglish,UserPhone,CreatedOn;
loginReq.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
var message = response.message;
var code = response.code;
if (response.data == null) {
alert("Message " + message + "code " + code);
} else {
var win1 = Titanium.UI.createWindow();
win1.open();
User = response.data.User;
UserName = User.UserLogin;
UserEmail = User.UserEmail;
UserFirstName = User.UserFirstName;
UserLastName = User.UserLastName;
UserAvatar = User.UserAvatar;
BioGraphyNative = User.BioGraphyNative;
BioGraphyEnglish = User.BioGraphyEnglish;
UserPhone = User.UserPhone;
CreatedOn = User.CreatedOn;
alert("UserName " + UserName + "UserEmail " + UserEmail);
}
};
loginReq.onerror = function() {
alert("Network error");
};
/*
* Login Button Click Event
*/
loginBtn.addEventListener('click',function(e) {
if (UserLogin.value !== '' && UserPassword.value !== '') {
var win1 = Titanium.UI.createWindow();
loginReq.open("POST", "url");
var params = {
UserLogin: UserLogin.value,
UserPassword: UserPassword.value
};
loginReq.send(params);
} else {
alert("Username/Password are required");
}
});
I am new in titanium, i f any body can helps me it will be very appreciated, and million ton thanks in advance.
Your window object is created but it's empty and has transparent background, so you don't see it on the screen.
You can change your onload to this:
loginReq.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
var message = response.message;
var code = response.code;
if (response.data == null) {
alert("Message " + message + "code " + code);
} else {
var win1 = Titanium.UI.createWindow({
backgroundColor: 'white',
layout: 'vertical',
});
var User = response.data.User;
for (var i in User) {
win1.add(Ti.UI.createLabel({ text: User[i] });
}
win1.open();
}
};
Also look out for JavaScript issues like declaring variable without var statement. Always use and try put all declaration at the beginning of function. To keep it monitored it's good have JSHint or JSLint installed and checking your code on every save.

Categories

Resources