Updating multiple divs - cakephp

I am using the following code to update a div
echo $this->Js->link($station["Company"]["name"],
array('action' => 'station_users','company_id'=>$station["Company"]["id"]),
array('id'=>'team_member'.$x, 'update' => '#myDIV')
);
But now I have a need to update multiple divs. How do I go about it? I want to update multiple divs by clicking on that link.

You can directly use jQuery instead of JsHelper. JsHelper will also render it as jQuery script.
You can add the following type of code in your view in a script block.
jQuery("#id").bind('click', function(event) {
jQuery.ajax({
beforeSend : function(XMLHttpRequest) {
jQuery("#sending").show();
},
data : jQuery("#id").closest("form").serialize(),
dataType : "html",
success : function(data, textStatus) {
updateMultipleDivs(data, textStatus);
},
type : "post",
url : "\/AppName\/ControllerName\/Method"
});
return false;
});
function updateMultipleDivs(data, textStatus) {
jQuery('#Div1toUpdate').before(data);
jQuery("#Div2toUpdate").hide();
}

Related

AngularJS and DataTables refreshing data

My project outputs results to a DataTable from an AngularJS controller function, but I'm running into some strangeness when I try to modify my search params. The first rendering of the table works as expected. But when I select different options and run the search again, extra rows appear in the table, but the info section shows the previous search's row count, and changing the number of rows shown via the length menu causes the new rows to disappear. Here's my table declaration, using attributes to wire up DataTables:
<table ui-jq="dataTable" ui-options="dataTableOptions" id="search-results" class="display nowrap datatable cell-borders" style="width: 100%;">
And this is my AngularJS controller code:
$scope.dataTableOptions = {
dom: "lfBrtip",
lengthMenu: [[25, 50, -1], [25, 50, "All"]],
language: {
emptyTable: 'No items matched your search criteria'
},
buttons: [
{
text: 'Export',
className: 'button button:hover',
extend: 'csv'
}
]
};
$scope.getItemInfo = function (model) {
$http({
method: 'POST',
url: $scope.getUrl('/My/ServerSide/Url'),
data: { model: $scope.model }
}).then(function successCallBack(response) {
$scope.model.SearchResults = response.data;
}, function errorCallback(response) {
alert("There was an error gathering the entity information. Please try again");
});
};
I'm not sure why submitting new queries with different params doesn't simply update the data in the DataTables table. Any suggestions?
I ended up using a bit of an ugly hack to get this to work. Even DataTables author wasn't sure how to get around the issue of using AngularJS with DataTables, so I had to force a reinitialization every time the form posted. I persisted the search params to localStorage, and called location.reload(). Then when the page loads and the AngularJS init() function runs, I pick up the search params and call the search function from inside an Angular document ready function, like this:
$scope.init = function () {
$scope.ValidationErrors = [];
$scope.model = {};
$scope.model.SearchResults = [];
$scope.model.ItemNumber = localStorage.getItem("itemNumber");
$scope.model.StartDate = localStorage.getItem("startDate");
$scope.model.EndDate = localStorage.getItem("endDate");
angular.element(document).ready(function () {
if ($scope.model.ItemNumber) {
$scope.getItemRecords();
}
});
localStorage.clear();
};
And then of course I clear the localStorage after the query. Not terribly elegant, but it'll have to do for now.

ng-click doesn't work with external JavaScript

I am creating an ionic project and I am trying to integrate with Algolia autocomplete.js. I managed to make the search system work, however I added a ng-click on my search results and this function is not working as presented in this codepen that I did as example below:
http://codepen.io/marcos_arata/pen/VKVOky
Inside my algolia's result template:
<a ng-click="add_name({{{ name }}})">
Function that should be run when clicked:
$scope.add_name = function(name) {
alert('User added!');
console.log(name);
}
I tried to inject the results inside the scope but didn't work as well:
autocomplete('#search_name', { hint: false, debug: true, openOnFocus: true },[{
source: index.ttAdapter({ hitsPerPage: 15 }),
templates: {
header: '',
suggestion: function(hit) {
$scope.hit = hit;
return template.render(hit);
}
}
}]);
http://codepen.io/marcos_arata/pen/VKVOky
---- SOLVED ----
Instead of creating a ng-click function inside your templates, you can handle the event click of your search inside your "autocomplete:selected" function and use the dataset and suggestion results.
.on('autocomplete:selected', function(event, suggestion, dataset) {
$scope.name = suggestion.name;
console.log($scope.name);
## create any functions with the suggestion and dataset results inside
});
EDITING THE ANSWER:
Here is the codepen:
Apparently the suggestion keep the name clicked, so you dont need an extra function:
.on('autocomplete:selected', function(event, suggestion, dataset) {
$scope.name = suggestion.name;
console.log($scope.name);
});

Backbone.js Click event firing multiple times

Is there any forum/Issue tracking website for backbone.js ?
I have an Issue that click event triggers multiple times. I had found a work around using Underscore.js , debounce method.
Is the problem addressed in latest backbone.js ?
Please suggest me on this .
Raja K
define([
'jquery', 'underscore','backbone',], function($, _, Backbone,Marionette) {
var Sample = Backbone.Marionette.ItemView.extend({
template: 'sample/sample',
model : new Model(),
render: function() {
id = utils.getStorage('some_id');
if(parseInt(id) > 0 ) {
this.model.set({some_id:id});
this.rendersome(id);
} else {
data = new Model().toJSON();
this.renderdata(data);
}
},
events: {
"click #some" : "someinfo"
},
someinfo : function() {
var self = this;
$.ajax({
url: API_URL + "sample/sampleinfo",
type: 'POST',
crossDomain: true,
cache: true,
data: JSON.stringify({ 'code1': this.model.get('code1'),
'code2' : this.model.get('code2'),
"auth" : init.auth, "user_id" : init.user_id }),
contentType: 'application/json',
success: function(data,response,jqXHR) {
if('SUCCESS' == data._meta.status && data.records.message.me == 'positive') {
self.model.set(data.records);
self.renderdata(data.records);
} else {
console.log(data.records.message);
return false;
}
},
error: function (request, status, error) {
console.log(request);
}
});
},
change: function (event) {
var target = event.target;
var change = {};
change[target.name] = target.value;
this.model.set(change);
},
});
return Sample;
});
Router Init code below,
routeaction : function() {
var Header = new HeaderView({'el': '#header'});
Header.render();
var test = new Tview({'el': '#content'});
test.render();
}
UPDATE : I am using backbone.subroute and the view got destroyed but not rendering after that. Becuase both old and current object referring the same element. But why it is not rendering again ? Can you please suggest me what I am missing here ?
render: function () {
// remove the existing header object
if(typeof gheader == "object") gheader.close();
// render the object
self.$el.html(tmpl(data));
},
UPDATE : I guess view.remove() is working fine. I have reused the container at $el and view.remove() removed the container element and stopped rendering the other views. Should I recreate the container ?
I can use "tagName" but suggest me how do I apply the stylesheet ?
undelegateEvents() Removes all of the view's delegated events. Useful if you want to disable or remove a view from
the DOM temporarily.
http://backbonejs.org/#View-undelegateEvents

How to call refresh() on a kendo-grid from an Angular controller?

I'm attempting to follow several suggestions on refreshing a kendo-grid such as this.
The essential is that in the html I have:
<div kendo-grid="vm.webapiGrid" options="vm.mainGridOptions">
Then in the controller I have:
vm.webapiGrid.refresh();
Note: I'm using the ControllerAs syntax so I am using "vm" rather than $scope.
My problem is that "vm.webapiGrid" is undefined. This seems so straightforward, but I'm not sure why it is undefined.
Found the answer. One other method of refreshing the datasource I read about was to do something like:
vm.mainGridOptions.datasource.transport.read();
This wasn't working for me as "read" was undefined. Looking at my datasource definition, I saw the reason, read needs a parameter (in this case "e"):
vm.mainGridOptions = {
dataSource: {
transport: {
read: function (e) {
task.getAllTasks(vm.appContext.current.contextSetting).
then(function (data) {
e.success(data);
});
},
}
},
To solve, I saved "e" in my scope and then reused it when I wanted to refresh:
vm.mainGridOptions = {
dataSource: {
transport: {
read: function (e) {
task.getAllTasks(vm.appContext.current.contextSetting).
then(function (data) {
e.success(data);
vm.optionCallback = e;
});
},
}
},
and then:
if (vm.optionCallback !== undefined) {
vm.mainGridOptions.dataSource.transport.read(vm.optionCallback);
}
Problem solved (I hope).
it's because you are using the options object to trigger the read, you should use the grid reference instead:
<div kendo-grid="vm.webapiGrid" options="vm.mainGridOptions">
as in:
$scope.vm.webapiGrid.dataSource.transport.read();
hope that helps.
Add id to the grid and trying refreshing using it.
<div kendo-grid="vm.webapiGrid" options="vm.mainGridOptions" id="grid1">
In controller use this:
$("#grid1").data('kendoGrid').refresh();

pass value from jquery to Cakephp controller

I am beginner to CakePHP and trying the send the textbox value during change function to my controller action using ajax.
Can someone help to how to pass the value form jquery to cakephp controller. If there is example code could great.
Let's say you want to send your data to a method called 'ajax_process' in the users controller. Here's how I do it:
in your view .ctp (anywhere)
<?php
echo $this->Form->textarea('text_box',array(
'id' => 'my_text',
));
?>
<div id="ajax_output"></div>
In the same view file - the jquery function to call on an event trigger:
function process_ajax(){
var post_url = '<?php echo $this->Html->url(array('controller' => 'users', 'action' => 'ajax_process')); ?>';
var text_box_value = $('#my_text').val();
$.ajax({
type : 'POST',
url : post_url,
data: {
text : text_box_value
},
dataType : 'html',
async: true,
beforeSend:function(){
$('#ajax_output').html('sending');
},
success : function(data){
$('#ajax_output').html(data);
},
error : function() {
$('#ajax_output').html('<p class="error">Ajax error</p>');
}
});
}
In the UsersController.php
public function ajax_process(){
$this->autoRender = false; //as not to render the layout and view - you dont have to do this
$data = $this->request->data; //the posted data will come as $data['text']
pr($data); //Debugging - print to see the data - this value will be sent back as html to <div id="ajax_output"></div>
}
Disable cake's security for the ajax_process method, in AppController.php:
public function beforeFilter() {
$this->Security->unlockedActions = array('ajax_process');
}
I haven't tested any of this code but it should give you what you need

Resources