Passing response with coverage.js produces error - javascript

I am using coverage.js for displaying data.
When I pass my variable (in which I get coverage response) into html file as we do it for angular to display expression,i t gives syntax error:
<div class="container" style="margin-top: 40px">
<div id="jsonAnswer" class="jsonAnswer" style="display: none">
{{coveragedetailjson}}
</div>
</div>
where coveragedetailjson is my variable where I get my response as a json
var data = $.parseJSON($("#jsonAnswer").html());
var coverage = new Coverage(data);
buildCoverageHTML = function (coverage) {
$(".coverage-section").remove();
var plugin = new CoveragePlugin(coverage);
// Adds the demographic section
plugin.addEligibleMetadataSection();
plugin.addDemographicsSection();
plugin.addInsuranceSection1();
plugin.addInsuranceSection2();
plugin.addInsuranceSection3();
plugin.addPlanMaximumMinimumDeductibles();
plugin.addPlanCoinsurance();
plugin.addPlanCopayment();
plugin.addPlanDisclaimer();
plugin.addAdditionalInsurancePolicies();
plugin.addGenericServices();
$('body').append(plugin.coverageSection);
};
buildCoverageHTML(coverage);
The above code in script tag
The fiddle I am using :
https://jsfiddle.net/Eligible/pqspk8gf/?utm_source=website&utm_medium=embed&utm_campaign=pqspk8gf
SyntaxError : Unexpected token {

Try changing
var data = $.parseJSON($("#jsonAnswer").html());
to use
var data = coveragedetailjson
instead of accessing DOM for this value.
In your case the variable {{coveragedetailjson}} is not updated/replaced with your JSON data when running the code.

Related

Issues with getting object vars through a string

Not sure if the title makes sense but, I want to send data with an click event, this click event will get the data from a pre set var (in this case product101), as this var is formatted in JSON I cant seem to retrieve the data, it always returns a undefined. As the var is an object, but when I use the dataset var is an string right?
// inside a loop
<div class="container">
<script> var product<?=$id?> = {"category":"cars"}</script>
<div data-my-product="product<?=$id?>">
//all the product stuff
</div>
</div>
//located in the footer
$('[data-my-product]').click(function(){
//demo
var pro = $(this).data('my-product');
alert(pro.category);//returns undefined
})
When I click the product it returns a 'undefined' alert message.
Notice that the products are generated inside a loop.
Overview
Your best bet here is to create an object or Map with the things you want to look up this way, and then put them on it as properties or entries.
With an object:
var items = {
product101: {category: "cars"}
};
or if you want to be paranoid about the default inherited properties that exist on objects, you might use an object with no prototype:
var items = Object.create(null);
items.product101 = {category: "cars"};
then in your click handler:
alert(items[pro].category);
Live Example:
$('[data-my-product]').click(function() {
var pro = $(this).data('my-product');
alert(items[pro].category);
});
<div class="container">
<script>
var items = {
product101: {category: "cars"}
};
</script>
<div data-my-product="product101">
//all the product stuff
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
With a Map:
var items = new Map([
["product101", {category: "cars"}]
]);
then in your click handler:
alert(items.get(pro).category);
Live Example:
$('[data-my-product]').click(function() {
var pro = $(this).data('my-product');
alert(items.get(pro).category);
});
<div class="container">
<script>
var items = new Map([
["product101", {category: "cars"}]
]);
</script>
<div data-my-product="product101">
//all the product stuff
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Side note: Although you can access that data-* attribute's value (indirectly) using data, doing so sets up a data cache for the element and initializes that cache with the attribute's value. If you're just looking to get the string, .attr("data-my-product") is more direct. See this answer for more details.

Setting up AngularJS template with API javascript

I am new to AngularJS and want to convert my current website to AngularJS. Below is a section of my webpage that shows meetings pulled from Google calendar. I am using the API to do this. My questions is how would I convert the HTML/Javascript to an AngularJS template? Do I just use a controller and dump all the javascript in it?
Currently my HTML shows the first two results in my calendar list.
This is my HTML:
<section class="sub-box meetings-box">
<div class="meetings-section">
<span class="meeting-h1">NEXT MEETING</span>
<div class="next-meetings-section">
<div class="meeting-info meeting-time next-meeting-time-start"></div>
<div class="meeting-info meeting-time next-meeting-time-end"></div>
<div class="meeting-info next-meeting-title"></div>
<div class="meeting-info next-meeting-location"></div>
</div>
<span class="meeting-h2">UPCOMING MEETINGS</span>
<div class="upcoming-meetings-section">
<div class="meeting-info meeting-time second-meeting-time-start"></div>
<div class="meeting-info meeting-time second-meeting-time-end"></div>
<div class="meeting-info second-meeting-title"></div>
<div class="meeting-info second-meeting-location"></div>
</div>
</section>
This is part of my Javascript that shows the callback response API
request.then(function(callbackResponse) {
var entries = callbackResponse.result.items; //returns an array entries
//get meeting info
var nextMeeting = entries[0];
var nextMeetingTimeStart = nextMeeting.start;
var nextMeetingTimeEnd = nextMeeting.end;
var nextMeetingTitle = nextMeeting.summary;
var nextMeetingLocation = nextMeeting.location;
var secondMeeting = entries[1];
var secondMeetingTimeStart = secondMeeting.start;
var secondMeetingTimeEnd = secondMeeting.end;
var secondMeetingTitle = secondMeeting.summary;
var secondMeetingLocation = secondMeeting.location;
//formatting info
for (var x in nextMeetingTimeStart && nextMeetingTimeEnd &&
secondMeetingTimeStart && secondMeetingTimeEnd) {
var nextMeetingStart = nextMeetingTimeStart[x];
var nextMeetingEnd = nextMeetingTimeEnd[x];
var secondMeetingStart = secondMeetingTimeStart[x];
var secondMeetingEnd = secondMeetingTimeEnd[x];
var nextMeetingStartFormat = new Date(nextMeetingStart).toString('hh:mm tt');
var nextMeetingEndFormat = new Date(nextMeetingEnd).toString('hh:mm tt');
var secondMeetingStartFormat = new Date(secondMeetingStart).toString('hh:mm tt');
var secondMeetingEndFormat = new Date(secondMeetingEnd).toString('hh:mm tt');
$('.next-meetings-section').find('.next-meeting-time-start').text(nextMeetingStartFormat+'-');
$('.next-meetings-section').find('.next-meeting-time-end').text(nextMeetingEndFormat);
$('.upcoming-meetings-section').find('.second-meeting-time-start').text(secondMeetingStartFormat+'-');
$('.upcoming-meetings-section').find('.second-meeting-time-end').text(secondMeetingEndFormat);
}
$('.next-meetings-section').find('.next-meeting-title').text(nextMeetingTitle);
$('.next-meetings-section').find('.next-meeting-location').text(nextMeetingLocation);
$('.upcoming-meetings-section').find('.second-meeting-title').text(secondMeetingTitle);
$('.upcoming-meetings-section').find('.second-meeting-location').text(secondMeetingLocation);
With Angular you would want to use a directive for DOM Manipulation, a factory (there are other options but this is a good starting place) for http calls and to store data. The controller should be concerned with providing scope for the view.
Angular Documentation:
controllers
directives
providers - factories are included here.
You may want to spend a few hours going through a tutorial or two before refactoring into Angular. Code School has a good one for free.
Edit-
Looking at your code you would want to take care of the server response inside a factory - create properties on your factory for nextMeeting and secondMeeting, and have them set to your server response data each time you get a server response back with the data.
Inject your factory into a controller, then in your controller you can have properties your view will use like: nextMeetingStart, nextMeetingEnd, etc. The value of these properties can be functions that use the values on your factory's nextMeeting and secondMeeting properties to set their appropriate return values.
Then you can just reference those properties in your view. The values displayed in the view will update whenever the factory receives new data from the server.

Updating multi-model form from Angular to Sinatra

I'm currently having an issue with updating a form in Angular and pushing the update through to Sinatra.
It is supposed to:
When clicked, the form to edit the current item is shown (current data for each field is displayed from the item scope).
When submitted, it is attempting to update to a different scope (updateinfo). I am not sure but do I need a way of using multiscope or one scope to allow it to update?
At present the script sends the correct downloadID parameter, but the JSON from the scope submitted is as I believe, incorrect.
Also, I'm not sure whether the Sinatra app.rb syntax is correct, for someone new to these frameworks, it has been hard to find useful documentation online.
If anybody could help it would be very much appreciated.
downloads.html
<div ng-show="showEdit">
<form ng-submit="updateinfo(item.downloadID); showDetails = ! showDetails;">
<div class="input-group"><label name="title">Title</label><input type="text"
ng-model="item.title"
value="{{item.title}}"/></div>
<div class="input-group"><label name="caption">Download caption</label><input type="text"
ng-model="item.caption"
value="{{item.caption}}"/>
</div>
<div class="input-group"><label name="dlLink">Download link</label><input type="url"
ng-model="item.dlLink"
value="{{item.dlLink}}"/>
</div>
<div class="input-group"><label name="imgSrc">Image source</label><input type="url"
ng-model="item.imgSrc"
value="{{item.imgSrc}}"/>
</div>
<!-- download live input types need to be parsed as integers to avoid 500 internal server error -->
<div class="input-group"><label name="imgSrc">
<label name="dlLive">Download live</label><input type="radio" ng-model="download.dl_live"
value="1"/>
<label name="dlLive">Not live</label><input type="radio" ng-model="download.dl_live"
value="0"/></div>
<div class="input-group"><label name="imgSrc"><input type="submit"/></div>
</form>
controllers.js
$scope.loadData = function () {
$http.get('/view1/downloadData').success(function (data) {
$scope.items = data;
});
};
$scope.loadData();
$scope.updateinfo = function(downloadID) {
id = downloadID
var result = $scope.items.filter(function( items ) {
return items.downloadID == id;
});
console.log(result);
updatedata = $scope.items
$http({
method : 'PUT',
url : '/view1/downloadedit/:downloadID',
data : result
});
};
app.rb
#edit download
put '/view1/downloadedit' do
puts 'angular connection working'
ng_params = JSON.parse(request.body.read)
puts ng_params
#download = Download.update(ng_params)
end
The wrong scope was attempting to be used. Once the scope was corrected to items, the correct JSON was being routed:
$scope.updateinfo = function(downloadID) {
id = downloadID
var result = $scope.items.filter(function( items ) {
return items.downloadID == id;
});
console.log(result);
updatedata = $scope.items
$http({
method : 'PUT',
url : '/view1/downloadedit/:downloadID',
data : result
});

Unable to get object from Controller to JSP

I am trying to pass an object from Spring Controller to my JSP page and plan to iterate the object in JSP using JSTL. But I am unable to print the object in JSP. From the controller side, the value is sent successfully. I am thinking something is wrong in Javascript or JSP.
Request your valuable inputs. Pls find the code below,
Controller :
#RequestMapping("/changehistory/getSearchHistory.htm")
public ModelAndView getSearchHistory(#ModelAttribute(HISTORY_CRITERIA) HistoryCriteria historyCriteria,ModelMap model) {
ModelAndView mav = new ModelAndView("changehistory/changeHistory_new");
List<HistoryCriteriaResult> result=new ArrayList<HistoryCriteriaResult>();
result=changeHistoryService.getHistory(historyCriteria);
mav.addObject("historyCriteriaResult", result);
return mav;
}
JSP:
<div class="ItemListNavBoxLeft" style="margin-top: -2px; padding-left: 20px;"
id="accordianRefreshBtn">
<div class="OrangeFB" style="width: auto; " onclick="RP.getSearchHistory()">
<div class="Q2"><div class="Q8"><div class="Q4"><div class="Q6"><div class="Q1"><div
class="Q3"><div class="Q7"><div class="Q9"><div class="Q5">
<spring:message code='label.button.history'/>
</div></div></div></div></div></div></div></div></div>
</div>
</div>
<div id="changeHistorydiv" style="display:<c:choose><c:when
test='${fn:length(historyCriteriaResult) > }'>block</c:when>
<c:otherwise>none</c:otherwise></c:choose>;">
<ul class="FormBody" style="padding-left:150px;">
<li class="FormFieldTitle"></li>
id="RP.changeHist"
name="changeHist">
<c:forEach items="${historyCriteriaResult}"
var="HCList">
${HCList.code}
${HCList.name}
</c:forEach>
</ul>
</div>
JS :
RP.getSearchHistory = function() {
dojo.xhrPost({
url : "/RMT/rateplan/getSearchHistory.htm?",
timeout : 100000,
load : function(content) {
var iList = content['result'], i;
HCList.options.length = 0;
for (i = 0; i < iList.length; i++) {
HCList.options[HCList.options.length] = new Option(iList[i].name, iList[i].code);
}
},
error : function(error) {
rmt.ErrorMessage.show(error);
}
});
}
You cannot access Java variable HCList inside your JavaScript code, you have two options:
First you could return result in another JSP page and in this case you don't need to do getSearchHistory Ajax call, you can do this by defining another controller method in your controller class, check a form submission example here, check how the controller class is implemented with two methods each one corresponded to a unique JSP file
Second, If you want return historyCriteriaResult in an AJAX request, then you must convert it to JSON format, so you need to change your Java method to something like this:
#RequestMapping("/changehistory/getSearchHistory.htm")
public #ResponseBody List<HistoryCriteriaResult> getSearchHistory(#ModelAttribute(HISTORY_CRITERIA) HistoryCriteria historyCriteria) {
List<HistoryCriteriaResult> result=new ArrayList<HistoryCriteriaResult>();
result=changeHistoryService.getHistory(historyCriteria);
return result;
}
And in your JavaScript method you would parse the JSON response like this:
handleAs: "json", // This force the response to be treated as JSON
load : function(content) {
alert(content.HistoryCriteriaResultList[0].code);
alert(content.HistoryCriteriaResultList[0].name);
.
.
// or append it to any div you want
}
Note: If you are using Spring 3 or above, you need to add Jackson JSON Parser to you project classpath

Dijit.tree - how to update store URL

I have the following in my HTML file:
<div dojoType='dojox.data.XmlStore' id='navTreeStore' jsId='navTreeStore' url='' label='name'></div>
<div dojoType='dijit.tree.ForestStoreModel' jsId='navTreeModel' store='navTreeStore' query='{}' rootId='NavTree' rootLabel='NavTree' childrenAttrs='childNodes'></div>
<div dojoType='dijit.Tree' id='navTree' model='navTreeModel'></div>
I'd like to be able to alter the store's URL dynamically. I can't seem to be able to achieve that with the following:
var tree = dijit.byId('navTree');
tree.model.store.url = urlAddress; //new URL
tree.model.store.clearOnClose = true;
tree.model.store.close();
tree.model.store.fetch();
What am I missing?

Categories

Resources