getJSON in phonegap application not working - json

I have looked through the older posts regarding this problem but did not find the solution to my problem.
I have 2 REST services on my computer, 1 for login and 2nd for sending a list items.
I am able to connect and login using the login webservice .
My second webservice is called after the login and it provides JSON data in following form..
[{"oid":101,"summary":"this is my first order"},{"oid":102,"summary":"this is second order"}]
I want to parse this JSON string and create a list of "oid" and then if I click on 1st item i should see the "summary" on a new page. When i hit the back button i want to call the service again so the list refreshes.
here is the code i tried.
<script>
$.getJSON('http://192.168.2.36:8080/phoneservlet/getOrders', function(data){
var output = '';
$.each(data, function(index, value){
//add each value to the output buffer (we also have access to the other properties of this object: id, start, and end)
output += '<li>'+ value.oid +'</li>';
});
//now append the buffered output to the listview and either refresh the listview or create it (meaning have jQuery Mobile style the list)
$('#your-orders').append(output).listview('refresh');//or if the listview has yet to be initialized, use `.trigger('create');` instead of `.listview('refresh');`
});
</script>
And this is the for list
<div data-role="page" id="currentorders">
<div data-role="content" id="data">
<ul data-role="listview" id="your-orders" data-divider-theme="b" data-inset="true">List of Orders</ul>
</div>
The problem is that my list does not get populated. I see an empty List with just the title of my list which is "List of Orders"
I am new to jquery so i still have not figured out how i can show the summary on a new page..

I think that you might missed the following access rule in config.xml file:
<access origin="*" />

1) For first issue you need to check get json url
2) Second issue show the summary on a new page
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<div data-role="page" id="currentorders">
<div data-role="header">
<h1>Orders</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="your-orders" data-divider-theme="b" data-inset="true"></ul>
</div>
</div>
<div data-role="page" id="summary">
<div data-role="header">
Back
<h1>Summary</h1>
</div>
<div data-role="content" id="content">
</div>
</div>
</body>
<script>
$('#currentorders').live("pageshow", function(){
// Here obj get using $.getJSON function, I have done direct using your json object only for example
var obj = [{"oid":101,"summary":"this is my first order"},{"oid":102,"summary":"this is second order"}];
var list = "";
$.each(obj, function(key, value){
list += '<li class="row">'+value.oid+'</li>';
})
$('#your-orders').html(list).trigger('create');
$('#your-orders').listview('refresh')
})
$('#currentorders li a').live("click",function(){
var content = $(this).attr("data-title");
$("#summary #content").html(content);
$.mobile.changePage( "#summary", { transition: "slide", changeHash: false });
})
$('#summary #back').live("click",function(){
$.mobile.changePage( "#currentorders", { transition: "slide", reverse: true, changeHash: false });
})
</script>
</html>

You cannot connect to an IP address through a PhoneGap Application as these cannot be whitelisted, you can only make CORS requests to domains whitelisted in your config: http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html

Related

How to Display Records in HTML from Angular having Data in Array Json format ? MVC My code attached

I am trying to display data i have in json format in array to html but it is not showing any result.
Code of my HTML page is,
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing</title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyChildApp', [])
app.controller('MyChildController', function ($scope, $window) {
$scope.data = $window.data;
console.log($scope.data);
});
</script>
<div ng-app="MyChildApp" ng-controller="MyChildController">
Data: <span ng-bind="data.visitNumber"></span>
<div ng-repeat="o in data">o.visitNumber</div>
<div ng-repeat="o in data.data">{{o.visitNumber}}</div>
<div ng-repeat="o in data[0]">{{o.visitNumber}}</div>
</div>
</body>
</html>
Inside div i have been trying to display data some how but i am only getting this result,
Data:
o.visitNumber
o.visitNumber
o.visitNumber
o.visitNumber
o.visitNumber
I want to show that i have in console.log ,
"[{"areaNameEn":"malibu","buildingEnglishName":"national Hospital","visitNumber":"Visit_U_1"},
{"areaNameEn":"jordan","buildingEnglishName":"kateer Hospital"},"visitNumber":"Visit_U_2"]”
How can i display all this data in div or HTML with headers
Thanks
I belive that your variable data is malformed. I think it should be
[{"areaNameEn":"malibu","buildingEnglishName":"national Hospital","visitNumber":"Visit_U_1"},
{"areaNameEn":"jordan","buildingEnglishName":"kateer Hospital","visitNumber":"Visit_U_2"}];
After that, the div should be like this
<div ng-app="MyChildApp" ng-controller="MyChildController">
Data:
<div ng-repeat="o in data">{{o.visitNumber}}</div>
</div>
Hope it helps

NicEditor doesnot work properly in mvc

I have got a problem when using nicEditor for my textarea editors in mvc project.
Here is the 2 view pages that I have created.From the First View I pass route values to the Second view
<ul class="mar">
#foreach (var item in Model)
{
<li class="mar" style="list-style-type:none">
<div style="display:inline-block;font-size:small">
<a id="arrow_#item.thread.MessageID" class="glyphicon glyphicon-triangle-right" style="text-decoration:none;cursor:pointer;color:dimgray" onclick="toggle(#item.thread.MessageID)"></a>
<h3 class="mar" style="display:inline-block;">#item.thread.Title</h3>
</div>
<li>
</ul>
Second View
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript" src="~/Scripts/nicEdit.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
</script>
<h2>GetMessage</h2>
<textarea style="width:900px"></textarea>
Here second view displays the niceditor(textarea) without its images inbuild with the nicEditor
When I remove the passing parameters from the First View,then it works Fine..
I need to know Why it happens like that???
Use the developer tools of your browser and watch the network view, why the nicEditoricons.gif not loaded, is a path problem. Use the option iconsPath to set the right one.
And please, take a look in the manual of nicedit.
var NicEditconfig = {
iconsPath : '/img/nicEditorIcons.gif',
buttonList : ['bold','italic','underline','ol','ul']
};
You need to configure the path manually
First, check the console to find the current request path. If the request path is wrong, then configure it
HTML
<textarea id="textAreaNiceEditor" style="width: 100%;">
Some Initial Content was in this textarea
</textarea>
JS Code
<script src="~/Content/NiceEditor/nicEdit.js"></script>
<script type="text/javascript">
//<![CDATA[
bkLib.onDomLoaded(function () {
new nicEditor({ iconsPath: '../../../Content/NiceEditor/nicEditorIcons.gif' }).panelInstance('textAreaNiceEditor');
});
//]]>
</script>
'../../../Content/NiceEditor/nicEditorIcons.gif'
Change this path value based on your gif location.
Make sure that you use are using same textarea id in JS code. Above case the id value is textAreaNiceEditor

Unable to pull one item of data from the Open Weather Map api using JSON

all.
This is a test to see if I can connect to the Open Weather Map api and successfully display an item of data from it (for now I am just trying to get the city name for a given latitude and longitude).
I am doing this inside a CodePen pen, by the way.
The problem is that nothing appears on the page - I get no city name at all.
What is this missing? (I have obscured my api key)
<html><body>
<div class="Text-center">
<h1> Local Weather</h1>
<h3>Front End Dev Project</h3>
<ul class ="list-unstyled">
<li class="btn btn-default" id="city"></li>
</ul>
<div>
</body></html>
<script>
$(document).ready(function(){
var long= -77.0506895;
var lat = 38.8925157;
var api = 'http://api.openweathermap.org/data/2.5/weatherlat='+lat+'&lon'+long+'=&appid=(HIDDEN)';
$.getJSON(api, function(data){
var city = data.name;
$("#city").html(city);
});
});
</script>
This is the correct url, please correct your url
http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid={AppKey}
and the response below
{
"coord":{
"lon":138.93,
"lat":34.97
},
"weather":[
{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"01n"
}
],
"base":"cmc stations",
"main":{
"temp":297.374,
"pressure":1018.36,
"humidity":93,
"temp_min":297.374,
"temp_max":297.374,
"sea_level":1027.9,
"grnd_level":1018.36
},
"wind":{
"speed":7.46,
"deg":243.504
},
"clouds":{
"all":0
},
"dt":1467816873,
"sys":{
"message":0.0045,
"country":"JP",
"sunrise":1467747404,
"sunset":1467799281
},
"id":1851632,
"name":"Shuzenji",
"cod":200
}
OK, the following works OUTSIDE of CodePen. If I use it inside CodePen, it is blocking the JSON call somehow. If I run this however in Chrome from a version written in NotePad, it returns "Shuzenji" just fine.
But that is an issue for another thread.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
var api = 'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=52481ca8a499564783f5f082863acac1';
$.getJSON(api, function(data){
var city = data.name;
$("#city").html(city);
});
});
</script>
</head>
<body>
<div class="Text-center">
<h1> Local Weather</h1>
<h3>Front End Dev Project</h3>
<ul class ="list-unstyled">
<li class="btn btn-default" id="city"></li>
</ul>
<div>
</body>
</html>

angularjs directive displays json during page load

I'm building my first AngularJS dynamic form, built based on information received from a JSON file using AngularJS directive.
Everything works, my issue is that the JSON code is getting displayed while the page is loaded - once the page is loaded the JSON code disappears.
Am I doing something wrong?
Check http://plnkr.co/edit/v4jOwuF6jmZfORlNbvIB?p=preview to see the behavior, click on "Stop"/"Start" multiple times to see the behavior.
HTML code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.2" src="https://code.angularjs.org/1.4.0-beta.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="ViewCtrl">
<div ng-repeat="page in form.form_pages">
<div ng-repeat="field in page.page_fields" class="form-group">
<field-directive field="field" ng-form="subForm"></field-directive>
</div>
</div>
</body>
js code:
'use strict';
angular.module('myApp',[])
.controller('ViewCtrl', ['$scope', function($scope) {
var jsonStr='{"form_id":"1","form_name":"My Test Form","form_pages":{"1":{"page_id":1,"page_title":"My First Tab","page_hide":false,"page_fields":{"1":{"field_id":1,"field_title":"First Name","field_type":"textfield","field_value":"","field_required":true,"field_disabled":false},"2":{"field_id":2,"field_title":"Last Name","field_type":"textfield","field_value":"","field_required":true,"field_disabled":false},"3":{"field_id":3,"field_title":"Gender","field_type":"textfield","field_value":"0","field_required":true,"field_disabled":false},"4":{"field_id":4,"field_title":"Email Address","field_type":"textfield","field_value":"","field_required":true,"field_disabled":false},"5":{"field_id":5,"field_title":"Password","field_type":"textfield","field_value":"","field_required":true,"field_disabled":false},"6":{"field_id":6,"field_title":"Birth Date","field_type":"textfield","field_value":"1981-01-10T06:00:00.000Z","field_required":true,"field_disabled":false},"7":{"field_id":7,"field_title":"Your browser","field_type":"textfield","field_value":"2","field_required":false,"field_disabled":false},"8":{"field_id":8,"field_title":"Additional Comments","field_type":"textarea","field_value":"","field_required":true,"field_disabled":false},"9":{"field_id":9,"field_title":"I accept the terms and conditions.","field_type":"textfield","field_value":"0","field_required":true,"field_disabled":false}}}}}';
$scope.form = JSON.parse(jsonStr);
}])
.directive('fieldDirective',function($http, $compile) {
var linker = function(scope, element) {
// GET template content from path
var templateUrl = "textfield.html";
$http.get(templateUrl).success(function(data) {
element.html(data);
$compile(element.contents())(scope);
});
}
return {
template: '<div>{{field}}</div>',
restrict: 'E',
scope: {
field: '='
},
link: linker
};
})
textfield.html - the html template:
<div class="row" ng-form="subForm" ng-class="{'has-success': subForm[field.field_id].$invalid}">
<div class="col-sm-5">{{field.field_title}}:</div>
<div class="col-sm-7">
<input type="text"
placeholder="{{field.field_title}}"
ng-model="field.field_value"
value="{{field.field_value}}"
ng-required="field.field_required"
ng-disabled="field.field_disabled"
class="form-control"
id = "{{field.field_id}}"
name = "{{field.field_id}}" >
<div ng-show="subForm[field.field_id].$touched && subForm[field.field_id].$error && subForm[field.field_id].$invalid">Field '{{field.field_title}}'
<span ng-show="subForm[field.field_id].$error.required"> is required.</span>
</div>
</div>
</div>
Thank you.
http://plnkr.co/edit/YC9p0UluhHyEgAjA4D8R?p=preview
Basically instead of adding the loaded template into the element then compiling it in place I just compile the string then insert the compiled element directly
element.append($compile(data)(scope));
Seems you can still see a delay but this might be the async loading of the template causing that, would need to debug in the network panel and do some profiling or logging to see exactly what's going on.
Edit
Made a fork of the plnkr to show one with the template inlined so there's no delay fetching it with $http http://plnkr.co/edit/Tnc3VOeI8cELDJDHYPTO?p=preview instead just grabbing it synchronously from the template cache and using ng-template in a script block to have it loaded in advance.

Populating listview with jQuery Mobile on a multi-page template

I am trying to render a listview on a second page using jquery.mobile.
I am using a single HTML with multiple "pages".
<div data-role="page" id="foo">
List
</div>
<div data-role="page" id="bar">
<div id="ListDiv">
<ul id="listview" data-role="listview" data-inset="true">
</ul>
</div>
</div>
<!--application UI goes here-->
<script type="text/javascript">
$("#loadList").click(function(){
$.getJSON(
"http://localhost/index.php/api/list",{format: "json"},
function(data){
var output = '';
$.each(data, function(key, val) {
output += '<li>' + val +'</li>';
});
$('#listview').append(output).listview('refresh');
});
});
But the problem now is when I click the #loadList button, it does take me to the #bar page, however, it doesn't seem $("#loadList").click() gets executed, because the list doesn't show up on the #bar page. Namely, nothing gets appended to #listView.
Any thoughts?
First there's a problem in this code, $.getJSON loading logic is false. Change page can not be used in a same time with $.getJSON.
There are 2 ways you can make this work:
Remove onclick event and load your data during second page initialization:
$(document).on('pagebeforeshow', '#bar', function(){
$.getJSON(
"http://localhost/index.php/api/list",{format: "json"},
function(data){
var output = '';
$.each(data, function(key, val) {
output += '<li>' + val +'</li>';
});
$('#listview').append(output).listview('refresh');
});
});
});
Unfortunately there's a problem with this solution. Used page event is not going to wait for $.getJSON, so in some cases your listview will be empty when page loads and content will suddenly appear. So this solution is not that great.
Second solution is remove href="#bar" attribute from the button but leave a click event. When $.getJSON action is successful the use changePage function and load next page. In case there's a problem with accessing second page listview store your result (In this ARTICLE you will find how, or HERE) and append it again during a pagebeforeshow event of a #bar page.
I made you a working jsFiddle example: http://jsfiddle.net/Gajotres/GnB3t/
HTML :
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3>
First Page
</h3>
</div>
<div data-role="content">
Load JSON data
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3>
Second Page
</h3>
Back
</div>
<div data-role="content">
<h2>Simple list</h2>
<ul data-role="listview" data-inset="true" id="movie-data" data-theme="a">
</ul>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
</body>
</html>
JS :
$(document).on('pagebeforeshow', '#index', function(){
$('#populate-button').on('click',function(e,data){
$.ajax({url: "http://api.themoviedb.org/2.1/Movie.search/en/json/23afca60ebf72f8d88cdcae2c4f31866/The Goonies",
dataType: "jsonp",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
success: function (result) {
ajax.jsonResult = result;
$.mobile.changePage("#second");
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
});
});
$(document).on('pagebeforeshow', '#second', function(){
ajax.parseJSONP(ajax.jsonResult);
});
var ajax = {
jsonResult : null,
parseJSONP:function(result){
$('#movie-data').empty();
$('#movie-data').append('<li>Movie name:<span> ' + result[0].original_name+ '</span></li>');
$('#movie-data').append('<li>Popularity:<span> ' + result[0].popularity + '</span></li>');
$('#movie-data').append('<li>Rating:<span> ' + result[0].rating+ '</span></li>');
$('#movie-data').append('<li>Overview:<span> ' + result[0].overview+ '</span></li>');
$('#movie-data').append('<li>Released:<span> ' + result[0].released+ '</span></li>');
$('#movie-data').listview('refresh');
}
}
You have id="loadList)", that is, with a closing parenthesis in
List
Maybe this is causing your problem?