I have an MVC4 Web API application where i have my Api Controller and Code-First EF5 database and some JavaScript functions for the functionality of my app including my Ajax Calls for my Web Api Service.I did the project on MVC because i was having trouble installing Cordova in VS2012, so i have decided to use Eclipse/Android Phonegap platform.Is there a way where i can call my web api service and be able to retrieve my database data designed EF5(MVC4) in my Android Phonegap application without having to start from the beginning the same thing again.I know phonegap is basically Html(JavaScript and Css) but i am having trouble calling my service using the same HTML markup that i used MVC4.I am a beginner please let me know if what i am doing is possible and if not please do show me the light of how i can go about this. T*his is my Html code*
<script type="text/javascript" charset="utf-8" src="phonegap-2.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="barcodescanner.js"></script>
<script type="text/javascript" language="javascript" src="http://api.afrigis.co.za/loadjsapi/?key=...&version=2.6">
</script>
<script type="text/javascript" language="javascript">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
//initialize watchID Variable
var watchID = null;
// device APIs are available
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = { timeout: 30000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
//declare a global map object
var agmap = null;
// declare zoom control of map
var zoomCtrl = null;
function initAGMap() {
agmap = new AGMap(document.getElementById("MapPanel"));
//TODO: must retrieve coords by device location not hard corded.
agmap.centreAndScale(new AGCoord(-25.7482681540537, 28.225935184269), 5); // zoom level 5 heres
// making zoom controls for map
var ctrlPos = new AGControlPosition(new AGPoint(10, 10), AGAnchor.TOP_LEFT);
zoomCtrl = new AGZoomControl(1);
agmap.addControl(zoomCtrl, ctrlPos);
}
function removeZoomCtrl()
{
zoomCtrl.remove();
}
//function search() {
// var lat = $('#latitude').val();
// var long = $('#longitude').val();
// $.ajax({
// url: "api/Attractions/?longitude=" + long + "&latitude=" + lat,
// type: "GET",
// success: function (data) {
// if (data == null) {
// $('#attractionName').html("No attractions to search");
// }
// else {
// $('#attractionName').html("You should visit " + data.Name);
// displayMap(data.Location.Geography.WellKnownText, data.Name);
// }
// }
// });
//}
//function GetCoordinate() {
//todo: get details from cordova, currently mocking up results
//return { latitude: -25.5, longitude: 28.5 };
}
function ShowCoordinate(coords) {
agmap.centreAndScale(new AGCoord(coords.latitude, coords.longitude), 5); // zoom level 5 here
var coord = new AGCoord(coords.latitude, coords.longitude);
var oMarker = new AGMarker(coord);
agmap.addOverlay(oMarker);
oMarker.show();
//todo: create a list of places found and display with marker on AfriGIS Map.
}
function ScanProduct()
{
//todo retrieve id from cordova as mockup
//This is mockup barcode
//return "1234";
//sample code using cordova barcodescanner plugin
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
//Callback function if barcodedont exist
function (error) {
alert("Scanning failed: " + error);
});
}
//Function to display Success or error in encoding.
function encode(type, data) {
window.plugins.barcodeScanner.encode(type, data, function(result) {
alert("encode success: " + result);
}, function(error) {
alert("encoding failed: " + error);
});}
function GetProductDetails(barcodeId,coords)
{
//Ajax Call to my web Api service
$.getJSON("api/products/?barcodeId=" + barcodeId + "&latitude=" + coords.latitude + "&longitude=" + coords.longitude)
.done(function (data) {
$('#result').append(data.message)
console.log(data)
var list = $("#result").append('<ul></ul>').find('ul');
$.each(data.results, function (i, item)
{
if (data.results == null) {
$('#result').append(data.message)
}
else {
list.append('<li>ShopName :' + item.retailerName + '</li>');
list.append('<li>Name : ' + item.productName + '</li>');
list.append('<li>Rand :' + item.price + '</li>');
list.append('<li>Distance in Km :' + item.Distance + '</li>');
//Another Solution
//var ul = $("<ul></ul>")
//ul.append("<li> Rand" + data.results.productName + "</li>");
//ul.append("<li> Rand" + data.results.Retailer.Name + "</li>");
//ul.append("<li> Rand" + data.results.price + "</li>");
//ul.append("<li> Rand" + data.results.Distance + "</li>");
//$("#result").append(ul);
}
});
$("#result").append(ul);
});
}
function ShowProductDetails()
{
//todo: display product details
//return productdetails.barcodeId + productdetails.retailerName + ': R' + productdetails.Price + productdetails.Distance;
}
//loading javascript api
$(function () {
initAGMap();
var coord = GetCoordinate();
ShowCoordinate(coord);
var barcodeId = ScanProduct();
var productdetails = GetProductDetails(barcodeId, coord);
ShowProductDetails(productdetails);
});
</script>
It looks like you're on the right track. The obvious error right now is that it's using a relative URL (api/products/?barcodeId=) to call the Web API. Because the HTML is no longer hosted on the same server as the Web API (even though you might be running them both on your local machine still), this won't work anymore. You need to call the service with an absolute URL (for example, http://localhost:8888/api/products/?barcodeId=).
Where is your Web API hosted right now and how are you running the Cordova code? If the Web API is up and running on your local machine and your Cordova app is running on an emulator on the same machine, you should be able to call the service by supplying its full localhost path.
If it still doesn't work, you'll need to somehow debug the code and see what the errors are.
Related
This is My Pubnub Chat Code
var pubnub = PUBNUB.init({
publish_key : 'my_key',
subscribe_key : 'sub-key'
});
pubnub.subscribe({
channel : "{{$channel}}",
message : function(m){
$(".conversation-list").append(
'<li class="clearfix '+ m.clearifix +' ">' +
'<div class="chat-avatar">' +
'<img src="' + m.image + '">'+
'<i> {{date('h:i')}} </i>' +
'</div>' +
'<div class="conversation-text">' +
'<div class="ctext-wrap">' +
'<i> '+ m.name + '</i>' +
'<p>' + m.message + '</p>' +
'</div>' +
'</div>' +
'</li>'
).animate({scrollTop: $(".conversation-list")[0].scrollHeight}, 0);
$('.reply-text').val('');
},
//connect : publish
});
$('.send-reply-to-user').on('click', function (e) {
e.preventDefault();
if ($('.reply-text').val()== '')
return false;
else
console.log(pubnub.publish);
// console.log(this);
var user_to_id = $(".send-reply-to-user").attr('user_to_id');
var message = $('.reply-text').val();
var name = $('#user_name').val();
var image = document.getElementById("user_image").getAttribute("src");
var clearifix = $('#user_clearifx').val();
pubnub.publish({
channel : "{{$channel}}",
message: { name : name, message : message, image : image, clearifix : clearifix }
});
if ($.trim(message).length != 0) {
$.ajax({
url: '{{route('send:user:chat:message')}}',
cache: false,
method: 'POST',
data: {user_to_id: user_to_id, message: message, _token: '{{csrf_token()}}'},
beforeSend: function () {
},
success: function (result) {
}
})
}
});
This code is Working perfectly only problem is that messages are going to all users, I want to send msg to one to one user.
Example: User one: John send a message to User two Deo,
Example 2: John sends a message to Marry
and so on. Using Pubnub JS API, Backend as Laravel 5.6
I recommend using PubNub's opinionated JavaScript framework called ChatEngine. It takes away a lot of the heavy lifting involved with making chat with PubNub. Here is some example code to get you started making 1:1 private chats. Make sure you use the setup button to prepare the backend on your account.
<script src="https://cdn.jsdelivr.net/npm/chat-engine#0.9.5/dist/chat-engine.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Init ChatEngine with PubNub
const publishKey = '__Your_PubNub_Publish_Key__';
const subscribeKey = '__Your_PubNub_Subscribe_Key__';
const ChatEngine = ChatEngineCore.create({
publishKey,
subscribeKey,
}, {
globalChannel: 'global',
});
const user = {
uuid: 'randomstringofchars',
name: 'John Smith'
}
const chats = {};
ChatEngine.connect(user.uuid, user);
ChatEngine.on('$.ready', function(data) {
// store my new user as `me`
let me = data.me;
// returns a ChatEngine chat object
function makePrivateChat(theirUserId) {
const chatKey = [theirUserId, me.uuid].sort().join('-');
// Don't make the same 1:1 chat if it already exists
if (chats[chatKey]) {
return;
}
// true for private chat
const chat = new ChatEngine.Chat(chatKey, true);
chats[chatKey] = chat;
}
// Auto add a 1:1 chat to UI when invited by someone
me.direct.on('$.invite', makePrivateChat);
// Define a button for making new 1:1 chats in your UI
newOneToOneChatButton.on('click', function (event, theirUserId) {
someChatObject.invite(theirUserId);
});
});
</script>
Finally Fixed My issue, the private Channels working good , Actually problem was with my back-end. It was returning data from all the users i have fixed now its working fine.
i am developing an application and loading an hosted application using the inapp browser plugin cordova-plugin-inappbrowser
I have gotten most of the functionalities to work but i am unable to get the part of loading an error message when he url does not load, it dosent just work and shows me an error message of the url where i have hosted my application instead.
Which could be embarrassing.
please i need help on this
This is what am working with below thanks for ur potential responses
// my child browser code, the main source of my app content
function fire(){
var ref = cordova.InAppBrowser.open('http://####################', '_blank', 'location=no,zoom=no,hardwareback=yes,clearsessioncache=yes,clearcache=no');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', inAppBrowserbLoadStart);
ref.addEventListener('loadstop', inAppBrowserbLoadStop);
ref.addEventListener('loaderror', loadErrorCallBack);
ref.addEventListener('exit', inAppBrowserbClose);
}
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage =
"alert('Sorry we cannot open that page. Message from the server is : "
+ params.message + "');"
inAppBrowserRef.executeScript({ code: scriptErrorMesssage }, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function executeScriptCallBack(params) {
if (params[0] == null) {
$('#status-message').text(
"Sorry we couldn't open that page. Message from the server is : '"
+ params.message + "'");
}
}
Your code is generally fine, but you have no control over the title of the alert() function. You can use some other techniques to display the error message. For example, you can use a div:
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage = createMsg('Sorry we cannot open that page. Message from the server is: '
+ params.message);
inAppBrowserRef.executeScript({
code: scriptErrorMesssage
}, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function createMsg(msg) {
return 'var div = document.createElement("div");'
+ 'div.style.position = "absolute";'
+ 'div.style.top = "50%";'
+ 'div.style.left = "50%";'
+ 'div.style.width = "100px";'
+ 'div.style.height = "100px";'
+ 'div.style.color = "#f00";'
+ 'div.innerHTML = "' + msg + '";'
+ 'document.appendChild(div);'
}
I currently have a Rails application that uses Turbolinks. In this app, I am trying to track the amount of time spent on a specific view. I have looked at countless questions and gone through multiple variations of called window.onbeforeunload, window.beforeunload, window.on('beforeunload')... My current attempt is this:
$(document).ready(function() {
var start = Date.now();
var id = gon.subjId;
var rand_index = gon.randIndex;
var index = gon.index;
console.log('showing article ' + index + ' at index ' + rand_index + ' for ' + id);
$(document).on('turbolinks:before-change', function() {
$.post('/log', {subj_id: id, article: {index: index, rand_index: rand_index, time_spent: Date.now()-start}},
function(response) {
});
})
});
I know that the function using the AJAX request works; however, it is not called. How can I get this function to call when the back button is pressed?
I'm still not sure what the underlying error was but I changed the script to this and works like a charm:
$(document).ready(function() {
var start = Date.now();
var id = gon.subjId;
var rand_index = gon.randIndex;
var index = gon.index;
console.log('showing article ' + index + ' at index ' + rand_index + ' for ' + id);
function logVisit() {
console.log('logging visit');
$.post('/log', {subj_id: id, article: {index: index, rand_index: rand_index, time_spent: Date.now()-start}},
function(response) {
});
document.removeEventListener('turbolinks:before-cache', logVisit);
}
document.addEventListener('turbolinks:before-cache', logVisit);
});
The live example is here
http://kenziejoy.github.io/frontend-nanodegree-map/
I'm trying to pull data about locations that I have hard coded in an array - either by their foursquare id (didn't seem to be working) or their lat and lng. (client ID and secret are variables I just haven't shown them here)
I don't need any other functionality than just pulling data from their database to display on a map so I thought it would fall under the userless access but it is giving me an error that the request are bad because I don't have the proper authentication.
Thanks in advance
From the foursquare site
"Userless access
Some of our endpoints that don’t pertain to specific user information, such as venues search are enabled for userless access (meaning you don’t need to have a user auth your app for access). To make a userless request, specify your consumer key's Client ID and Secret instead of an auth token in the request URL.
https://api.foursquare.com/v2/venues/search?ll=40.7,-74&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=YYYYMMDD
To see what level of permissions each endpoint needs, check out the filters at the top of our endpoints page."
/**********FourSquare***************/
$.ajax({
url:'https://api.foursquare.com/v2/venues/search',
dataType: 'json',
data: 'limit=1' +
'&ll='+ placeItem.lat() +','+ placeItem.lng() +
'&?client_id='+ CLIENT_ID +
'&client_secret='+ CLIENT_SECRET +
'&v=20140806' +
'&m=foursquare',
async: true,
success: function (data) {
var result = data.response.venue;
var contact = result.hasOwnProperty('contact') ? result.contact : '';
if (contact.hasOwnProperty('formattedPhone')) {
placeItem.phone(contact.formattedPhone || '');
}
var location = result.hasOwnProperty('location') ? result.location : '';
if (location.hasOwnProperty('address')) {
placeItem.address(location.address || '');
}
var bestPhoto = result.hasOwnProperty('bestPhoto') ? result.bestPhoto : '';
if (bestPhoto.hasOwnProperty('prefix')) {
placeItem.photoPrefix(bestPhoto.prefix || '');
}
if (bestPhoto.hasOwnProperty('suffix')) {
placeItem.photoSuffix(bestPhoto.suffix || '');
}
var description = result.hasOwnProperty('description') ? result.description : '';
placeItem.description(description || '');
var rating = result.hasOwnProperty('rating') ? result.rating : '';
placeItem.rating(rating || 'none');
var url = result.hasOwnProperty('url') ? result.url : '';
placeItem.url(url || '');
placeItem.canonicalUrl(result.canonicalUrl);
// Infowindow code is in the success function so that the error message
// Content of the infowindow
var contentString = '<div id="iWindow"><h4>' + placeItem.name() + '</h4><div id="pic"><img src="' +
placeItem.photoPrefix() + '110x110' + placeItem.photoSuffix() +
'" alt="Image Location"></div><p>Information from Foursquare:</p><p>' +
placeItem.phone() + '</p><p>' + placeItem.address() + '</p><p>' +
placeItem.description() + '</p><p>Rating: ' + placeItem.rating() +
'</p><p><a href=' + placeItem.url() + '>' + placeItem.url() +
'</a></p><p><a target="_blank" href=' + placeItem.canonicalUrl() +
'>Foursquare Page</a></p><p><a target="_blank" href=https://www.google.com/maps/dir/Current+Location/' +
placeItem.lat() + ',' + placeItem.lng() + '>Directions</a></p></div>';
// Add infowindows
google.maps.event.addListener(placeItem.marker, 'click', function () {
infowindow.open(map, this);
// Bounce animation
placeItem.marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
placeItem.marker.setAnimation(null);
}, 800);
infowindow.setContent(contentString);
});
},
// Alert the user on error.
error: function (e) {
infowindow.setContent('<h5>Foursquare data is unavailable.</h5>');
document.getElementById("error").innerHTML = "<h4>Foursquare data is unavailable. Please try refreshing.</h4>";
}
});
I took a look at the live example URL and you were getting a lot of bad request errors in the JavaScript console in Chrome.
Looking at these, you had a bad URL, you were using:
https://api.foursquare.com/v2/venues/search?limit=1&ll=45.5589522,-122.6517163&?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&v=20140806&m=foursquare
The problem seems to be that you have:
&?client_id
which makes the URL invalid.
Changing this to
&client_id
fixes this and I then see data coming back from Foursquare.
I'm using the linkedin JS API
I'm trying to perform people search, It's not returning anything
Code :
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: --my api key--
onLoad: onLinkedInLoad
authorize: true
</script>
<script type="text/javascript">
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
function onLinkedInAuth() {
IN.API.PeopleSearch()
.fields("firstName", "lastName", "distance")
.params({"company-name":"infosys"})
.result(displayPeopleSearch)
.error(displayPeopleSearchError);
}
function displayPeopleSearch(){
var peopleSearchDiv = document.getElementById("peoplesearch");
var members = peopleSearch.people.values;
for (var member in members) {
// but inside the loop, everything is the same
// extract the title from the members first position
peopleSearchDiv.innerHTML += "<p>" + members[member].firstName + " " + members[member].lastName + " is a " + members[member].positions.values[0].title + ".</p>";
}
}
Any help, anything I'm doing wrong?
I'm following this tutorial
On this line you are using a variable peopleSearch that is not declared anywhere:
var members = peopleSearch.people.values;
You must add a parameter to the function function displayPeopleSearch()
function displayPeopleSearch(peopleSearch){
var peopleSearchDiv = document.getElementById("peoplesearch");
var members = peopleSearch.people.values;
for (var member in members) {
// but inside the loop, everything is the same
// extract the title from the members first position
peopleSearchDiv.innerHTML += "<p>" + members[member].firstName + " " + members[member].lastName + " is a " + members[member].positions.values[0].title + ".</p>";
}
}
d.