display data in bootstrap card from web service call - javascript

I'm interested in dsiplaying data from web service call in the bootstrap card. Most of the example i see are using hard coded data, I have a simple UI to display web service data using bootstrapTable and bootstrap card.
<div class="card" id="card-data">
<div class="front">
<h1 id="front-label">{data.number}</h1>
<p>
<span ><span class="card-front">Name :</span> {data.name}</span><br/>
<span ><span class="card-front">Type :</span> {data.type} </span><br/>
<span ><span class="card-front">Updated :</span> {data.date} </span><br/>
<p>
</div>
</div>
script logic
var data;
$(function () {
$.getJSON("http://localhost:8080/xxxxxx/getData", function(json){
data = json;
/*perhaps load data by id */
.......
});
});
I could have done this in angular or react by expressions on $scope or 'props` but we are not using any framework for this UI.

Not the cleanest way but I was able to retrieve the JSON data and display it on the card.
<div class="card" id="card-data">
<div class="front">
<h1 id="data_number"></h1>
</div>
</div>
empty value will be replaced with value in <h1 id="data_number"></h1>
script
$(document).ready( function () {
var data = $.getJSON("http://localhost:8080/xxxxxxx/getData", function(data) {
$("#data_number").html(data[0].number);
});
});

Related

Use JsonResponse variable from Django in Html via ajax

I am returning JsonResponse with the required hash from Django view on a ajax call.
How to use the Json object inside html via {{}} (jinja templating). Below is my ajax call:
$(function () {
$('#getData').submit(function (e) {
e.preventDefault();
$.ajax({
url: "/Report",
type: 'get',
data: {
'date1': $('#d1').val(),
'date2': $('#d2').val(),
},
success: function (data) {
alert("Success");
// How to pass the data here to use it in html
}
});
});
});
My sample html :
<div id="maindiv" class="col col-5 col-sm-10" style="display: none;">
<div>
<h3> Showing Results for {{info.fromDate}} to {{info.toDate}}</h3>
</div>
<br><br>
<div id="summary">
<div class="card-deck">
<div class="card mx-auto">
<div class="card-body text-center">
<p style="text-align: center;vertical-align: middle;padding: 20px;" class="card-text">
<h1><b><span style="font-size:80px;">{{info.total}}</span></b></h1>
<h6> Total </h6>
</p>
</div>
</div>
<div class="card" id='chart1' style="width: 100%; height: 500px;">
<div class="card-body text-center">
<script>
Info = {{ info.marks| safe }}
createpiechart("marks", 'chart1', Info); <!-- This creates an amchart -->
</script>
</div>
</div>
</div>
</div>
This is just a sample. I have many more charts and processing for which I used the jsonresponse variable via {{}} inside html. What is the correct way to get the data from ajax to html?
Initially I used render to return response to html. But I see that the data I capture in ajax has the entire html replaced with the {{}} variable's value
return render(request=request, template_name='home/home.html', context={"info": InfoArray})
How to use the hash/context I pass from Django view inside html via a ajax ?
App\home.urls file:
urlpatterns = [
#path('', views.index, name = "index"),
path('', views.homepage, name="homepage"),
]
App\urls file:
urlpatterns = [
path('Report/', include('home.urls')),
path('admin/', admin.site.urls),
]

AngularJs Filter: Generating notArray errors

I'm having an issue with a filter in my angularJS project.
We have a simple draft feature that allows users to save the contents of a large form as a JSON string in our database. They then can go to a section of the site to display and continue working on these forms. I want to provide them a filter on that page to filter by the date they saved the draft on.
Here is my markup:
<div ng-controller="savedFormCtrl" ng-cloak id="saved-form-wrapper"
class="border border-dark border-top-0 border-right-1 border-bottom-1
border-left-1 px-0" ng-init="getSavedForms()"
>
<!-- Search filters -->
<form name="savedFormsFilterWrapper" layout="row" flex="35" layout-align="end center" class="toolbar-search">
<!-- Date filter -->
<md-input-container flex="80">
<div class="text-light font-weight-bold float-left">Filter by saved date:</div>
<md-tooltip style="font-size:1em;">Filter your saved HRTF's</md-tooltip>
<md-datepicker name="dateFilter" class="hrtf-date savedFilterDatepicker"
md-date-locale="myLocale" data-ng-model="savedFormFilters" ng-blur="setFilterDate()"
md-placeholder="" md-open-on-focus
aria-label="Saved forms date filter">
</md-datepicker>
</md-input-container>
</form>
<!-- Saved forms body -->
<div id="savedFormAcc" class="accordion col-md-12 pt-3">
<!-- Accordion item Header -->
<div class="card" ng-repeat="item in savedForms | filter:savedFormFilters">
<div class="card-header savedFormItem" id="savedForm{{$index}}" data-toggle="collapse" data-target="#collapse{{$index}}">
<md-button class="md-raised md-primary" data-toggle="collapse"
data-target="#collapse{{$index}}" aria-expanded="false"
aria-controls="collapse{{index}}"
>
Form Saved on {{ item.savedOn }} - Click to expand
</md-button>
</div>
<!-- Accordion body continues on below -->
</div>
</div>
And my JS:
(function () {
'use strict';
angular.module('hrtf')
.controller('savedFormCtrl', ['$scope', '$window', 'formService',
function savedFormCtrl($scope, $window, formService) {
$scope.savedFormFilters = '';
//Get users's saved forms
$scope.savedForms = {};
$scope.getSavedForms = function(){
formService.getSavedForms()
.then(saved => {
saved.forEach( item =>{
item.data_json = JSON.parse(item.data_json);
});
$scope.savedForms = saved;
return $scope.savedForms;
};
}
]);
})();
Now, the filter works. But whenever The page is loaded, anywhere from 20-50 errors appear, all with the contents Error: [filter:notarray] Expected array but received: {}
All I need to do here is provide a simple filter on a string value to the parent objects savedOn: xxData Herexx value.
What am I doing wrong?
Turns out, I had a similar issue to this post
Basically, my ng-repeat and filter were initializing before the associated model could load. Initializing the model as a blank array and then creating the filter as part of the promise chain did the trick:
//Get users's saved forms
$scope.savedForms = [];
$scope.getSavedForms = function(){
formService.getSavedForms()
.then(saved => {
//Convert and format items here
$scope.savedForms = saved;
$scope.savedFormFilters = { savedOn: ''};
return $scope.savedForms;
}).catch(e => { console.error(e);
});
};
Pretty basic, but I'll leave it here in case it helps someone in the future :)

Form modal binding in laravel with vue js

I have 2 models Tour.php
public function Itinerary()
{
return $this->hasMany('App\Itinerary', 'tour_id');
}
and Itinerary.php
public function tour()
{
return $this->belongsTo('App\Tour', 'tour_id');
}
tours table:
id|title|content
itineraries table:
id|tour_id|day|itinerary
In tour-edit.blade.php view I have used vue js to create or add and remove input field for day and plan dynamically.
Code in tour-create.blade.php
<div class="row input-margin" id="repeat">
<div class="col-md-12">
<div class="row" v-for="row in rows">
<div class="row">
<div class="col-md-2">
<label >Day:</label>
<input type="text" name="day[]"
class="form-control">
</div>
<div class="col-md-8">
{{ Form::label('itinerary', " Tour itinerary:", ['class' => 'form-label-margin'])}}
{{ Form::textarea('itinerary[]',null, ['class' => 'form-control','id' => 'itinerary']) }}
</div>
<div class="col-md-2">
<button class="btn btn-danger" #click.prevent="deleteOption(row)">
<i class="fa fa-trash"></i></button>
</div>
</div>
</div>
<div class="row">
<button class="btn btn-primary add" #click.prevent="addNewOption" >
<i class="fa fa-plus"></i> Add Field</button>
</div>
</div>
</div>
I want to populate these fields with their respective data. But all data i.e itinerary belonging to a tour are being displayed in itinerary textbox in JSON format.
My vue js sript is:
<script>
var App = new Vue({
el: '#repeat',
data: {
day:1 ,
rows:[
#foreach ($tour->itinerary as $element)
{day: '{{$element->day}}', plan: '{{$element->plan}}'},
#endforeach
]
},
methods: {
addNewOption: function() {
var self = this;
self.rows.push({"day": "","itinerary":""});
},
deleteOption: function(row) {
var self = this;
self.rows.splice(row,1);
},
}
});
</script>
I would avoid mixing blade into JavaScript, instead the best option is to make an ajax call to an api route which returns your data in json, which can then be processed by Vue:
methods:{
getItinerary(){
axios.get('api/itinerary').then(response => {
this.itinerary = response.data;
})
}
}
However, with this approach you will likely need to use vue-router rather than laravel web routes, which puts us into SPA territory.
If that's not an option (i.e. you still want to use blade templates), you should take a look at this answer I gave the other day which shows you how to init data from your blade templates.
What you seem to be doing is using laravel's form model binding to populate your forms, not Vue, so your model data is not bound to the view. So, you will need to decide which one you want to use. If it's vue you just want to use a normal form and bind the underlying data to it using v-model:
Now any updates in the view will automatically be updated by Vue. I've put together a JSFiddle that assumes you will want to continue using Laravel web routes and blade templates to show you one approach to this problem: https://jsfiddle.net/w6qhLtnh/

How to pass the values to the other html page and redirect the to that page for onclick thumbnail using jquery?

Here I need to click on a thumbnail, so that it will show the details on other page, it should show the details of that particular thumb only. I used xml file here to fetch the data and display thumbnail. I am unable to pass the values to other page and open it at the same time onclick event. pls help
<div class="container-page">
<div class="row" id="portfolio">
<div class="col-md-2">
<nav>
<ul class="nav nav-pills nav-stacked" id="test">
<li role="presentation" class="active">Services</li>
<li role="presentation">Desktop</li>
<li role="presentation">Web</li>
<li role="presentation">Mobile</li>
<li role="presentation">Design</li>
</ul>
</nav>
</div>
<div class="col-md-10">
<div class="row" id="thumb">
</div>
</div>
</div>
</div>
<!-- js -->
$.ajax({
type:"GET",
url:"portfolio.xml",
dataType:"xml",
success:function(xml)
{
$(xml).find('thumbnail').each(function()
{
var $thumbnail=$(this);
var type=$thumbnail.find('type').text();
var descr=$thumbnail.find('description').text();
var title=$thumbnail.attr('title');
var imageurl=$thumbnail.attr('imageurl');
var thum='<div class="col-xs-6 col-md-3"> </div>';
thum=$(thum).appendTo("#thumb");
thum = $('').appendTo(thum);
var thumName = $('<div class="thumTitle"></div>').appendTo(thum);
$('<h2>'+title+'</h2>').appendTo(thumName);
$('<p>'+type+'</p>').appendTo(thumName)
thum = $('<img src="'+imageurl+'" alt="image" class="thumbImgSize imgSlide">').appendTo(thum);
$(".forHove").mouseup(function()
{
//here is the redirection code, and want to pass $thumbnail to testxml.html page
window.location="http://www.bookmane.in/skillworks/testxml.html";
$(thum).appendTo(".s");
});
});
}
});
Well, one of the alternative is using Web Storage API.
Just store img html and use it.
// use 'click' instead of 'mouseup'
$(".forHove").click(function()
{
// store image html to sessionStorage
window.sessionStorage.image_data = $thumbnail.clone().wrapAll("<div>").parent().html();
window.location="http://www.bookmane.in/skillworks/testxml.html";
$(thum).appendTo(".s");
});
// in http://www.bookmane.in/skillworks/testxml.html
// You have data sotred and insert it somewhere
$(document.body).append(window.sessionStorage.image_data);
You can achieve this thing using the following steps:
Add a form tag like
<form action="YOUR_PATH" method="GET">
<a class="thubnailClick" href="#" >
<html_of_your_thumbnail>
<input type="text" name="NAME_OF_PARAMETER" />
</a>
</form>
Now override the click event of <a> tag with
$(document).ready(function() {
$(".thubnailClick").on('click', function(event) {
// to override the default behavior of <a> tag.
preventDefault();
// Find the form element using closest() of jQuery.
// Call submit event of that form using $(form_element).submit();
});
})
Now on the other page you can get parameter from URL using location.search or follow:
Getting Query params using JavaScript
Now use these Params according to your needs.

How to do a foreach binding using KnockoutJS in Bootstrap-themed dropdown

I'm developing a small notifications-like module, where the user can see his 5 latest activities that are logged in the DB (MSSQL). The values that I need are all there, but for some reason knockout binding is not working. Here are code snippets:
<div class="dropdown-menu toolbar pull-right" data-bind="with: layoutLogsModel">
<h3 style="border: none;">Recent activities:</h3>
<!-- "mailbox-slimscroll-js" identifier is used with Slimscroll.js plugin -->
<ul id="mailbox-slimscroll-js" class="mailbox" data-bind="foreach: layoutLogsModel.notification">
<div class="alert inbox">
<a href="javascript:void(0)">
<i class="icon-book" style="color: orange;"></i>
Some text
</a>
<br>
Some text #2
</div>
</ul>
</div>
For now, I only want to display random text for every item that is in the observableArray.
ViewModel is the following:
var layoutLogsModel = {
notification: ko.observableArray()
};
function getLastFiveActivities() {
get(apiUrl + "Logs/GetLastFiveActivities", { ClientUserID: loggedUserID }, function (data) {
layoutLogsModel.notification(data);
});
}
And every time I call this function, the list is empty (IMAGE)
(the function is called on click, and absolutely no errors are shown in the console).
What is it that I am doing wrong?
EDIT:
The thing was, I forgot to execute ko.applyBindings for that viewModel. Then, I changed the HTML to look like this:
<ul id="mailbox-slimscroll-js" class="mailbox" data-bind="foreach: notification">
<div class="alert inbox">
<a href="javascript:void(0)">
<i class="icon-user" style="color: green;"></i>
<span data-bind="text: $data"></span>
</a>
</div>
</ul>
Aslo, I modified the get function slightly, like this:
function getLastFiveActivities() {
get(apiUrl + "Logs/GetLastFiveActivities", { ClientUserID: loggedUserID }, function (data) {
layoutLogsModel.notification(data.Notification);
});
}
(changed data to data.Notification based on the MVC model property that contains the array)
After all that, the data was available immediately.
try removing the layoutLogsModel from the foreach, you are already using it with the binding "with", so eveything in that div will be part of layoutLogsModel.
<div class="dropdown-menu toolbar pull-right" data-bind="with: layoutLogsModel">
<h3 style="border: none;">Recent activities:</h3>
<!-- "mailbox-slimscroll-js" identifier is used with Slimscroll.js plugin -->
<ul id="mailbox-slimscroll-js" class="mailbox" data-bind="foreach: notification">
<div class="alert inbox">
<a href="javascript:void(0)">
<i class="icon-book" style="color: orange;"></i>
Some text
</a>
<br>
Some text #2
</div>
</ul>
</div>

Categories

Resources