I have created an HTML5 application which uses knockoutjs to make call to a restful service and get/post JSON messages.
This is my first application using HTML5 so I am not sure how to implement a URL redirect.
In the application I have two html pages, one is a DataGrid page which shows all the data received by doing a get rest call. I have added a hyperlink to one the field in the display which I would like to use to redirect to the details page and make the rest call to get data for that particular id and display it in the editable page later would like to save the changes.
UserGridPage.html
<tbody data-bind="foreach:userList">
<tr>
<td><a data-bind="attr:{href: userInfoUrl()}, text:userInfoId"></a></td>
<td data-bind="text: UserName" ></td>
</tr>
UserGridPage.js
MyUserInfoViewModel = function () {
var self = this;
self.userList = ko.observableArray();
$.getJSON("http://localhost:8080/user/webresources/userinfo/").
then(function (userinfos) {
$.each(userinfos, function () {
self.userList.push({
userInfoUrl:ko.observable('/USERUI/UserEntry.html#'+this.userInfoId),
userInfoId:ko.observable(this.userInfoId),
policyHolderEmail: ko.observable(this.policyHolderEmail),
});
});
});
I would like to know how can UserEntry page would know which Id is getting passed to its page and also how would I make the rest call to have the Id passed to the restful URL.
Appreciate any help with code samples, links etc..
Thanks
You should be trying like this
View :
<ul data-bind="foreach: items">
<li>
<a data-bind="attr: { href: id }, text: name,click:function(){alert(id)}"></a>
</li>
</ul>
ViewModel :
var viewModel = {
items: [{'id':1,'name':"one"},{'id':2,'name':"two"},{'id':3,'name':"three"}]
};
ko.applyBindings(viewModel);
Sample working fiddle here
In your userEntry.html, if you want to get the id value passed:
<script>
var id = window.location.hash;
</script>
I remember firefox has a slightly different behaviour in that it decodes URL encoded characters in the fragment, so if you want the raw content, you can also consider using:
<script>
var id = window.location.href.split("#")[1];
</script>
Not sure how you can get the parameter from the URL with javascript, but if you are willing to use PHP you could get the Id parameter with $_REQUEST['Id'] an use it to generate your new REST call.
So your href would be something like "/USERUI/UserEntry.php?Id=5"
To use that variable in javascript on your UserEntry page you can do something like:
<script>
var id = <?php $_REQUEST['Id']; ?>
//generate your restful query here.
</script>
Related
I have a dropdownlist like
#Html.DropDownList("ProjectsList")
and a link is near it
#Html.ActionLink("Change Project", "ChangeProject", new { code = param }, new { id = "myLink2" })
and also a dropdown list for DB names which is accordingly changing to the previous list
#Html.DropDownList("Databaselist")
What I want is when I click the Change Project link it will work the ChangeProject function on c# with selected dropdownlist parameter(I used select2 dd list) and run the "GetDbList" function on c#
Its difficult to manage from server side rendering because if some how you got your dropdownlist value inside actionlink that will be only the value that selected on page load.
So the best ways to get dynamics values like you are looking for is to use script.
<a class="ChangeProject" href="#">Change Project</a>
$('.ChangeProject').on('click', function(){
var url = '#Url.Action("project", "GetDbList", new { id= "----" })';
url = url.replace("----", $('#ProjectsList').val()); //here you will get selected id from dropwon
window.location = url;
});
I think u can use javascript for this (this code can inspire you to solve):
<ul>
<li><a onClick="myTestFunction(this)">ID1</a></li>
<li><a onClick="myTestFunction(this)">ID2</a></li>
<li><a onClick="myTestFunction(this)">ID3</a></li>
<li><a onClick="myTestFunction(this)">ID4</a></li>
</ul>
<script>
function myTestFunction(e)
{
///THERE U CAN IMPLEMENT CODE wich must update link for a tag or do some redirect
///alert(e.textContent);
var getAtagContent=e.textContent;
window.location = "/ChangeProject?id="+getAtagContent;
}
</script>
He is currently working on code that has to filter the data in the table. Ajax will call the link and gets the response (json) results with answer. However, I came across a problem. I have to somehow render tables and I do not want to do this by append etc.
Can I somehow again generate views or blade file?
The default view is DefController#index but ajax use url which controller is DefController#gettabledata.
public function gettabledata($id){
return response()->json(Def::find($id)->getallmy->all());
}
You can put the part in your template corresponding to the table in a separate .blade.php file, and #include that in your main layout.
main.blade.php :
<html>
...
<body>
<div class="table-container">
#include('table')
</div>
</body>
...
And
table.blade.php:
<table>
#foreach($rows as $row)
<tr>
<td> $row->title ... </td>
</tr>
#endforeach
</table>
In this way you can use a simple jQuery $('div.table-container').load(url) and on your server just render and respond that part as an html string. return view('table', $data)
Javascript:
function refreshTable() {
$('div.table-container').fadeOut();
$('div.table-container').load(url, function() {
$('div.table-container').fadeIn();
});
}
The answer is yes, you can. Webinan certainly pointed you in the right direction. This approach is slightly different.
First things first, you need a seperate view for the table. A very basic example for the HTML markup:
<div class="table-container">
#include('partials.table') // this view will be async loaded
</div>
We start by making a call to the server with jQuery (can be done with Javascript too) using the shorthand ajax function: var $request = $.get('www.app.com/endpoint');. You can also pass along any data to your controller on the backend.
Now on the serverside, within your controller, render and return the table view:
class EndpointController extends Controller
{
/**
* Returns a rendered table view in JSON format.
*
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function ajax(Request $request)
{
$html = view('partials.table', compact('view'))->render();
return response()->json(compact('html'));
}
}
If everything worked out, the done callback will be triggered. Simply grab the html variable and set it as the content of the table's container.
function renderTable() {
var $request = $.get('www.app.com/endpoint'); // make request
var $container = $('.table-container');
$container.addClass('loading'); // add loading class (optional)
$request.done(function(data) { // success
$container.html(data.html);
});
$request.always(function() {
$container.removeClass('loading');
});
}
Hope this helps!
To update and change page content without reloading the page in Laravel 5.4 i do the following:
First create the blade view in the "views" folder called "container.blade.php" it will contain the following code (in this case a select box that is rendering a list of abilities from the package Bouncer (but you can use the #foreach on any Laravel collection you like):
<select>
{{ $abilityList = Bouncer::role()::where('name','admin')->first()->getAbilities()->pluck('name') }}
#foreach ( $abilityList as $ab )
<option value="{{ $ab }}">{{ $ab }}</option>
#endforeach
</select>
Add this to you main blade file (e.g. home.blade.php) making sure to use a div with an id you can reference:
<div id="abilityListContainer">
#include('container')
</div>
Now on your main blade file (e.g. home.blade.php) add a button that will trigger the function that will communicate with the Laravel controller:
<input type="button" value="reload abilities" onClick="reloadAbilities()"></input>
Then add the javascript for this function, this loads the generated html into your div container (note the "/updateAbility" route next to ".get" - this is a Laravel route which we will set up in the next step):
var reloadAbilities = function()
{
var $request = $.get('/updateAbility', {value: "optional_variable"}, function(result)
{
//callback function once server has complete request
$('#abilityListContainer').html(result.html);
});
}
Now we set up the Laravel route for this action, this references our controller and calls the function "updateAbilityContainer". So edit your /routes/web/php file to have the following route:
Route::get('updateAbility', array('as'=> 'updateAbility', 'uses'=>'AbilityController#updateAbilityContainer'));
Finally in app/Http/Controllers make the file "abilityController.php" (you can also use "php artisan make:controller abilityController"). Now add this function to process the changes, generate the html and return it to the javascript function (note you may also have to use the namespaces as well):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class AbilityController extends Controller
{
public function updateAbilityContainer()
{
// use this if you need to retrieve your variable
$request = Input::get('value');
//render and return the 'container' blade view
$html = view('container', compact('view'))->render();
return response()->json(compact('html'));
}
}
Thats it, your blade "container" will now reload when you click the button and any changes to the collection you are rendering should update without reloading the page.
Hopefully this fills in some blanks left in the other answers. I hope it works for you.
I am using the Ember Timetree code (Timetree) and I think it is great. I am a newbie to Ember and D3 so jumping into the Timetree code made my head hurt.
I am trying to add functionality so that if a user clicks a button on the page, the timetree will reload with different data. I have been trying for a while but nothing seems to work.
Here is what I have:
Ember template for the timetree:
<script type="text/x-handlebars" data-template-name="index">
<div class="example">
{{view Ember.Timetree.TimetreeView contentBinding="App.ApiData" selectionBinding="selectedEvents" rangeBinding="eventsRange_example2"}}
</div>
</script>
HTML that defines the timetree div:
<div id="app"></div>
HTML for the button the user clicks:
<button type="button" onclick="loadNewTimetree()">Reload</button>
Javascript for the function to reload the timetree:
function loadNewTimetree() {
var newJsonData = .... Get the JSON data
// Replace the existing JSON data with the newJsonData and re-draw the timeline - how?
}
What is the piece I am missing that links the updated JSON to timetree?
Thanks.
Marshall
I found the answer.
First, I added a viewName="mmView" tag to my Template:
<script type="text/x-handlebars" data-template-name="index">
<div class="example">
{{view Custom.Timetree.TimetreeView viewName="mmView" contentBinding="App.ApiData" selectionBinding="selectedEvents" rangeBinding="eventsRange_example2"}}
</div>
</script>
I found the core of the answer here. So I updated my javascript function:
function loadNewTimetree() {
var newJsonData = .... Get the JSON data
// View.views returns a hashtable. Key is the id, value if the View.
var views = Ember.View.views;
for (var nextKey in views) {
var nextView = views[nextKey];
// The 'viewName' is set in the template and needs to be unique for each timeline.
if (nextView.viewName && nextView.viewName == 'mmView')
{
nextView.reloadWithNewData(newJsonData );
}
}
}
Then I added a function in my View to handle the updated JSON:
Custom.Timetree.TimetreeView = Ember.Timetree.TimetreeView.extend(
{
... Other attributes,
reloadWithNewData:function (newTimelineJson)
{
// Need to clear out the svg contents before adding the new content
// or else you get strange behavior.
var thisSvg = this.get('svg');
thisSvg.text('');
this.set('content', newTimelineJson);
this.didInsertElement();
}
});
So when I call the loadNewTimetree() function, it updates the timeline with the new JSON.
The issue may be that you are not doing things the Ember way - which is very different but awesome. In Ember the button would typically be defined as
<button {{action 'loadNewTimeTree'}}>Reload</button>
and then in your view or controller one would have an action handler that would loadNewTimeTree. Typically by loading the data into an ember model.
App.IndexView = Ember.View.extend({
actions: {
loadNewTimeTree: function () {
var newJsonData = .... //Get the JSON data or more typical
this.get('controller.model').reload(); //typically JSON handled by RESTAdapter
}
}
});
If you want to learn the ember way which may be challenging I recommend studying their website
Hello I've been searching the internet for about a couple of days now but I only get lost in the deepness of the subject.
What my aim is to get the json data from this URL: https://www.btcturk.com/api/ticker which is something like this;
{"high":1565.01,"last":1536.90,"timestamp":1388632896.0,"bid":1540.0,"volume":50.76,"low":1534.00,"ask":1552.00}
And I want to print / display / visualize some of the values in html table format, something like this;
<table border="1">
<tr>
<td>Alış (Bid): </td>
<td>bid value from json</td>
</tr>
<tr>
<td>Satış (Ask): </td>
<td>ask value from json</td>
</tr>
</table>
Please notice that the column1 is custom text and column2 is the related jason data.
That's it, I just want to insert the needed code into the HTML (Text ) Widget in Wordpress.
I'm not even sure if I need a plugin to do this, or if I need to download jquery.js file to my server can read it externally...
Any help, suggestion, guidance or any kind of reply is greatly appreciated.
I thank you all in advance.
if your current page where you want to put the widget is in the same domain, you can use the below snippet as text/html widget "assuming your page in the same domain https://www.btcturck.com"
<div class="result"></div>
<script type="text/javascript">
window.onload = function() {
jQuery.ajax( {
url: "https://www.btcturk.com/api/ticker",
}). done(
function( data ) {
var data = JSON.parse(data);
html = '<table><tr><td>BID</td><td>'+data.bid+'</td></table>';
$('.result').html(html);
});
};
</script>
I have used window onload because I don't know when your jquery library will be loaded.
I could use some advice please.
THE SCENARIO
I have a tabbed control on the page.
There an update panel on each tab.
Inside each update panel is an instance of a custom Web part (asp.net)
I need to get the parameter value of the report viewer embedded in a user control in the Web part.
I need to retrieve this value using java script on the client side.
To be clear, I don't want to pass up variables using hidden controls or similar methods.
Can I reference the property of the bottom most object, a report viewer?
THE UPDATE PANEL CODE
<td><table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr class="ms-WPHeader">
<td align="left" class="ms-wpTdSpace"> </td><td title="Graduation Rates - My Visual WebPart" id="WebPartTitlectl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7" class="ms-WPHeaderTd"><h3 style="text-align:justify;" class="ms-standardheader ms-WPTitle"><nobr><span>Graduation Rates</span><span id="WebPartCaptionctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7"></span></nobr></h3></td><td align="right" class="ms-WPHeaderTdMenu" onclick="OpenWebPartMenu('MSOMenu_WebPartMenu', this, 'WebPartctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7','False'); TrapMenuClick(event); return false;"><span style="display:none;"></span><div class="ms-WPMenuDiv" onmouseout="this.className='ms-WPMenuDiv'" onmouseover="this.className='ms-WPMenuDivHover'"><a onclick="OpenWebPartMenuFromLink('MSOMenu_WebPartMenu', this, 'WebPartctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7','False'); return false;" id="WebPartctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7_MenuLink" onkeydown="WebPartMenuKeyboardClick(document.getElementById('WebPartctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7_MenuLink'), 13, 40, event)" href="#" title="Graduation Rates Web Part Menu" class="ms-wpselectlink" onblur="UpdateWebPartMenuFocus(this, 'ms-wpselectlink', 'ms-WPEditText');" onfocus="UpdateWebPartMenuFocus(this, 'ms-wpselectlinkfocus', 'ms-WPEditTextVisible');" menuid="MSOMenu_WebPartMenu"><img class="ms-WPHeaderMenuImg" src="/_layouts/images/wpmenuarrow.png" alt="Graduation Rates Web Part Menu" style="border-width:0px;" /></a></div></td><td class="ms-WPHeaderTdSelection"><span class="ms-WPHeaderTdSelSpan"><input type="checkbox" id="SelectionCbxWebPartctl00_m_g_08bc0677_b337_4b17_8729_6ca0b60b83e7" class="ms-WPHeaderCbxHidden" title="Select or deselect Graduation Rates Web Part" onblur="this.className='ms-WPHeaderCbxHidden'" onfocus="this.className='ms-WPHeaderCbxVisible'" onkeyup="WpCbxKeyHandler(event);" onmouseup="WpCbxSelect(event); return false;" onclick="TrapMenuClick(event); return false;" /></span></td><td align="left" class="ms-wpTdSpace"> </td>
</tr>
UPDATE- WORKING CODE BELOW
The key was creating a custom data attribute as #Fil indicated and passing from the code behind and then accessing the $.cache. And passing the clientID of the reportviewer into the javascript function to get to the current instance of the webpart child controls.
<input type="hidden" id="<%= ASP_SSRS.ClientID %>_myDataState"
onchange="compareUnitValues(this.id, this.parentNode.id, '<%= ReportViewer1.ClientID %>', '<%= ASP_SSRS.ClientID %>', '<%= btnSendHiddenField.ClientID %>');" />
<script type ="text/javascript">
function compareUnitValues(elemt, parent, reportviewerID, value1, value2) {
var myDataUnit = $("#" + elemt),
parentObject = $("#" + parent),
reportviewerObject = $("#" + reportviewerID),
ssrs = $("#" + value1),
btnSend = $("#" + value2);
var myDataUnitValue = myDataUnit.val();
var myDataUnitJSON = jQuery.parseJSON(myDataUnitValue);
var currentmyDataUnit = myDataUnitJSON.currentUnit.objectId;
var sessioncurrentObjectId = document.getElementById('<%= hiddenCurrentObjectId.ClientID %>').value;
ssrs.val(myDataUnitValue);
var currentReportViewerParam = $("#" + reportviewerID).attr("data-report-param");
if (currentmyDataUnit != currentReportViewerParam) {
btnSend.trigger("click");
}
}
FROM CODE BEHIND CREATE THE CUSTOM DATA ATTRIBUTE
ReportViewer1.Attributes.Add("data-report-param", parsedObjectId)
If you have that property visible when the html renders (see if it does by viewing source on your browser), then you would be able to fetch it on the client end using JS.
You could reference the report viewer control either by assigning it a unique class name, or by using jQuery's ends with or contains selector:
$("[id*='ReportViewer1']").attr("attributeName"); - this is the contains selector
http://api.jquery.com/attribute-contains-selector/
http://api.jquery.com/attribute-ends-with-selector/
Is this what you are looking for?
UPDATE on the HTML5 data attribute question:
Just a cleaner way to store arbitrary data in the html (for more convenient access to Javascript). Here is a good article that explains it here
So, what you would do in practice is this: Imagine you want to add the report viewer's parameter (which for the sake of argument has a value of "42") as an attribute to a Panel control you have with an ID="Panel1". In code behind you would do
Panel1.Attributes.Add("data-report-param", "42");.
Because the Panel control is rendered as a <div> element, you will see something like this:
<div id="Panel1" data-report-param="42">
Finally you would be able to grab it from Javascript using one of the following two ways:
$("#Panel1").data("report-param");
$("#Panel1").attr("data-report-param");
UPDATE on retrieving the attribute
If they are on the same node, try this:
$.each($("[id*='ReportViewer1']"), function(index, value) {
if ($(value).is("[data-report-param]"))
{
alert($(value).attr("data-report-param"));
}
});
This will go through each element that contains "ReportViewer1" in its ID. Then for each item it will check if that element contains the "data-report-param" attribute. If so, alert the value. Hope this finally helps :)