Use HTTP POST for loading content via Kendo tabstrip - kendo-ui

Kendo tabstrip accepts content loading ContentUrl as ajax via HTTP GET, is there a way to load this content via POST?
A kendo tabstrip accepts a kendo.data.Datasource for loading content
See http://dojo.telerik.com/EmECoy
$("#tabstrip").kendoTabStrip({
dataTextField: "Name",
dataContentUrlField: "ContentUrl",
dataSource: [
{ Name: "Tab1", ContentUrl: "http://demos.telerik.com/kendo-ui/content/web/tabstrip/ajax/ajaxContent1.html" },
{ Name: "Tab2", ContentUrl: "http://demos.telerik.com/kendo-ui/content/web/tabstrip/ajax/ajaxContent2.html" }
]
});
kendo.data.DataSource has an available READ type of "POST" but i cannot grasp if it is possible to plug this mechanism into the content loading of the tabstrip.. or am i stuck with an AJAX GET call to retrieve this ?

Here is my solution to bypass the built in tab mechanisms for loading content: http://dojo.telerik.com/omOre
Empty content urls in the tab definition:
jQuery(function(){jQuery("#tabstrip").kendoTabStrip({"select":onselect,"activate":onactivate,"contentLoad":onContentLoad,"animation":false,"contentUrls":["","","",""]});});
//Track our content
var tabcontent = [{"contentloaded":true},{"url":"http://demos.telerik.com/kendo-ui/content/web/tabstrip/ajax/ajaxContent1.html"},{"url":"http://demos.telerik.com/kendo-ui/content/web/tabstrip/ajax/ajaxContent2.html"},{"url":"http://demos.telerik.com/kendo-ui/content/web/tabstrip/ajax/ajaxContent3.html"} ];
Implement the "select" event
- Determine if we should load the tab via AJAX (post)
- Track if tab already loaded
//When selected, if ajax and not not loaded - load the content
function onselect(e) {
console.log("select");
var index = $(e.item).index();
var taburl = tabcontent[index].url;
var contentloaded = tabcontent[index].contentloaded;
if(taburl !== "" && contentloaded !== true)
{
//get reference to the TabStrip widget
var ts = $("#tabstrip").data("kendoTabStrip");
//get the tab content
var item = ts.contentElement(index);
$.ajax({
type: "get",//simple change! "post",
url: taburl,
success: function (response) {
$(item).html(response);
tabcontent[index].contentloaded = true;
console.log("Tab Index: " + index + ", Url: " + taburl + " [[ajax success]]");
}
});
}
}

Related

How to update content of a Bootstrap modal loaded using Ajax?

I've a bootstrap Modal with users list, inside which I'm displaying another modal for adding a new user. The Add new User Modal is fetched using Ajax. When I add a new user using Ajax, I want to update the div with Ajax response message(.alert-success or .alert-danger in bootstrap).
Right Now the user is loaded but I can't show the message as the modal itself is loaded using Ajax.
$('body').on("click", "#createGroupUserModual .submit", function (e) {
var alertContainer = $(document).find('#groupUserFormCreate').find("#alerts");
$.ajax({
url: $('#groupUserFormCreate').attr('action'),
type: 'POST',
dataType: "json",
cache: false,
data: $('#groupUserFormCreate').serialize(),
success: function(response) {
console.log("success " + response.message);
var returnMessage = "<div class='alert alert-success'>"+response.message+"</div>";
//this below line is not updating the contents with the message.
alertContainer.html(returnMessage);
},
error: function(response) {
console.log("failure is here " + response.message);
var returnMessage = "<div class='alert alert-danger'>"+response.message+"</div>";
alertContainer.html(returnMessage);
}
});
});
I see that not same code for redraw de alertContent, it only exists when response is success but not in errro, under $.ajax query
So:
error: function(response) {
console.log("failure is here " + response.message);
var returnMessage = "<div class='alert alert-danger'>"+response.message+"</div>";
alertContainer.html(returnMessage);
}
Try this code, added the redraw html in error.
Expect will be.

Ajax loaded content div class is not applied

I have a page that has a few divs connected in a flowchart via JS-Graph.It. When you click one of the divs, I want it to 1) generate text in a special div 2) generate a popup via click functions attached to the two classes "block" and "channel" in each div. This works when the page is static.
When I add ajax so on click of a button and add more divs, only one of the two classes appears in the HTML source. "Channel" is no longer visible and the function to generate a pop-up on click of a channel class div does not work anymore...
AJAX call:
$("#trace").bind('click', $.proxy(function(event) {
var button2 = $('#combo').val();
if(button2 == 'default') {
var trans = 'Default View';
}
if(button2 == 'abc') {
var trans = 'abc';
}
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button2=' + $('#combo').val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
success: function(data) // Variable data constains the data we get from serverside
{
JSGraphIt.delCanvas('mainCanvas');
$('.test').html('<h1>' + trans + '</h1>'); // Clear #content div
$('#mainCanvas').html(''); // Clear #content div
$('#mainCanvas').append(data);
JSGraphIt.initPageObjects();
}
});
return false; // keeps the page from not refreshing
}, this));
DIV class: (works in index.php but not transactions.php)
// Boxes
while($row = sqlsrv_fetch_array($result))
{
echo '<div id="'.$row['id'].'_block" class="block channel" style="background:';
Functions:
$(document).on('click', '.block', $.proxy(function(event) {
var input = $(event.target).attr('id');
var lines = input.split('_');
var button = lines[0];
$.ajax({
url: 'srv.php',
data: 'button=' + button,
dataType: 'json',
success: function(data)
{
$('#content').html('');
$('#content').append(data);
}
});
return false;
}, this)); // End Application Details
$(".channel").click(function () {
alert('channel');
});
Something about registering with pages, I'm not sure exactly how it works. The fix should be to change your channel click function to be the same as your first and use the .on('click') option.
found some related reading material. https://learn.jquery.com/events/event-delegation/

Updating a dropdown via knockout and ajax

I am trying to update a dropdown using knockout and data retrieved via an ajax call. The ajax call is triggered by clicking on a refresh link.
The dropdown is successfully populated when the page is first rendered. However, clicking refresh results in clearing the dropdown instead of repopulating with new data.
Html:
<select data-bind="options: pages, optionsText: 'Name', optionsCaption: 'Select a page...'"></select>
<a id="refreshpage">Refresh</a>
Script:
var initialData = "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]";
var viewModel = {
pages : ko.mapping.fromJS(initialData)
};
ko.applyBindings(viewModel);
$('#refreshpage').click(function() {
$.ajax({
url: "#Url.Action("GetPageList", "FbWizard")",
type: "GET",
dataType: "json",
contentType: "application/json charset=utf-8",
processData: false,
success: function(data) {
if (data.Success) {
ko.mapping.updateFromJS(data.Data);
} else {
displayErrors(form, data.Errors);
}
}
});
});
Data from ajax call:
{
"Success": true,
"Data": "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]"
}
What am I doing wrong?
The problem you have is that you are not telling the mapping plugin what to target. How is it suppose to know that the data you are passing is supposed to be mapped to the pages collection.
Here is a simplified version of your code that tells the mapping what target.
BTW The initialData and ajax result were the same so you wouldn't have noticed a change if it had worked.
http://jsfiddle.net/madcapnmckay/gkLgZ/
var initialData = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}];
var json = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"}];
var viewModel = function() {
var self = this;
this.pages = ko.mapping.fromJS(initialData);
this.refresh = function () {
ko.mapping.fromJS(json, self.pages);
};
};
ko.applyBindings(new viewModel());
I removed the jquery click binding. Is there any reason you need to use a jquery click bind instead of a Knockout binding? It's not recommended to mix the two if possible, it dilutes the separation of concerns that KO is so good at enforcing.
Hope this helps.

Render 'like' button after ajax call

there were a few question similar to mine on the stack but none that answered my question, so...
An ajax call returns the standard html code for creating the like button:
<div class="fb-like" data-href="http://www.website.com" data-send="true" data-width="450" data-show-faces="true"></div>
This html does show up in the source when looked at with 'inspect element', but it is not rendered, i.e. the space where the button should be is blank. Is there some rendering function that I should be using?
Any hints would be greatly appreciated!
EDIT: Here's the ajax request and parseing - the 'like' button is put in '#thequestion' along with some other text (it is echoed from question.php).
$("#thequestion").load("/thought/question.php", { ans: choice, id: questionId } );
$("#graph").load("/thought/graph.php", { id: questionId } );
$("#fbCommentsPlaceholder").html("<div class='fb-comments' data-href='http://qanai.com/thought/#" + questionId + "' data-num-posts='2' data-width='470'></div>");
FB.XFBML.parse();
eval(document.getElementById('thequestion').innerHTML);
eval(document.getElementById('graph').innerHTML);
(I know eval is evil)
EDIT 2: The like button appears if FB.XFBML.parse(); is executed manually (in the console) after the ajax call.
Thanks
You have to call FB.XFBML.parse(); after the ajax call.
Documentation: https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse/
Edit: now I see that you're trying to load content into $('#thequestion'). .load takes a callback that runs after the request completes. You should do something like:
$('#thequestion').load('/my/url', { my: 'params' }, function() {
FB.XFBML.parse();
});
Documentation: http://api.jquery.com/load/
Not sure anyone needs it, but my complete code looks like this now and renders both FB page and Like button appropriatelly (LikeLink button created with material icon):
<i id="LikeLink" class="material-icons actionButton"></i>
var fbloaded = false; // if SDK is loaded, no need to do it again (though cache should do this?
var fbpageid = "myPageId"; // FB page id
// ajax call to FB SDK script
if (!fbloaded) {
$.ajax({
type: "GET",
url: "//connect.facebook.net/en_US/sdk.js",
dataType: "script",
cache: true,
success: function () {
fbloaded = true;
FB.init({
appId: '{myAppId}',
version: 'v2.3' // or v2.0, v2.1, v2.0
});
// parse button after success
FB.XFBML.parse();
}
});
}
var FBDivAppended = false; // if already done, do not call and render again
PostUrl = window.location.href; // like button needs this... or not :)
// when LikeLink is clicked, add the divs needed and at the end fire the FB script ajax call (resetFB)
$("#LikeLink").click(function () {
if (!FBDivAppended) {
var $pagediv = $("<div class=\"fb-page\" data-href=\"https://www.facebook.com/" + fbpageid + "\" />");
var $fblikediv = $("<div class=\"fb-like\" data-href=\"" + PostUrl + "\" />");
var $fbdiv = $("<div id=\"fbDiv\" />");
var $fbroot = $("<div id=\"fb-root\" />");
$fbdiv.append($pagediv).append($fblikediv);
$(".Header").append($fbdiv).append($fbroot);
FBDivAppended = true;
}
resetFB();
}

how to show filtered jqgrid with search toolbar prefilled using single call to retrieve data

I'm looking for a way to show jqgrid with search toolbar pre-filled and data filtered by this toolbar. I tried code below but this makes two requests to retrieve data. First request retrieves
unfiltered data and only second request retrieves proper data.
How to eliminate first request so that filtered data is retrieved and search toolbar is pre-filled immediately ?
var grid = $("#grid"),
notLoaded= true;
grid.jqGrid({
datatype: "json",
mtype: 'POST',
loadComplete: function() {
$("#gs_Name").val('<%= Request.QueryString["Name"] %>');
if (notLoaded) {
setTimeout( function() {
$("#grid")[0].triggerToolbar();
}, 100 );
notLoaded = false;
}
}
});
Update
I tried to fill search toolbar using search criteria passed from query string
$(function () {
var grid = $("#grid"),
urlFilters;
var namedParameters = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'),
parameters = {},
nameAndValue,
i;
for (i = 0; i < namedParameters.length; i += 1) {
nameAndValue = namedParameters[i].split('=');
parameters[nameAndValue[0]] = decodeURIComponent(nameAndValue[1]);
if (nameAndValue[0] === "filters") {
urlFilters= decodeURIComponent(nameAndValue[1]);
}
}
grid.jqGrid({
postData: { filters: urlFilters },
search:true,
loadComplete: function() {
refreshSearchingToolbar( $(this), 'eq');
}
...
Search toolbar is empty if grid is loaded but grid is filtered and find dialog is filled properly.
Search toolbar is also filled if find dialog is opened.
Debugger shows that in refreshSearchingToolbar condition
if (typeof (postData.filters) === "string" &&
typeof ($grid[0].ftoolbar) === "boolean" && $grid[0].ftoolbar) {
if not satisfied: ftoolbar is undefined.
I removed this check but after that got error at line tagName = control[0].tagName.toUpperCase(); about undefined tagName
How to fix this ?
You should create jqGrid with search: true and postData: {filters: theFilterAsJSON} parameters. Look the answer, this one of this one for details.
UPDATED: The answer shows how to parse postData.filters and fill the fields of the searching toolbar (whenever it's possible) the the corresponding filters.

Resources