I have a grid which looks like this:
status createdBy
+-+-----------+ +-+--------+
|1|running | |1|84, 77 |
|2|running | |2|22 |
|3|not running| |3| |
+-+-----------+ +-+--------+
In my store, I defined
sorters: [{
property: 'status',
direction: 'DESC'
}
In my controller, I get this data:
Ext.Ajax.request({
url: 'api/user.php',
root: 'username',
success: function(response) {
Ext.getCmp('viewport').initComps();
var _username = response.responseText;
_username = _username.replace(/\D/g, '');
return _username;
},
});
The grid is sorted by status -so far so good- but I want the row where _username === createdBy.value to be shown on top,
followed by the rest of the grid, still ordered by status, but I just can't get my code working...
Any help would be appreciated.
Like existdissolve pointed out, you may need to use sorter function.,
check this fiddle: https://fiddle.sencha.com/#fiddle/143 ('admin' users are listed first in the fiddle)
Related
I have three parameters startdate, enddate and name which I have to send to the server to get back Json response. I am displaying the response in a GridPanel.
My Ajax Request looks like this:
FilterOperSet: function(button){
var win = button.up('window');
var form = win.down('form');
var start = form.getForm().findField('startDate').getSubmitValue();
var end = form.getForm().findField('endDate').getSubmitValue();
var act = form.getForm().findField('actor').getSubmitValue();
Ext.Ajax.request({
url: 'ListData',
params: { type: 'recordedRequest', startDate: start,
endDate: end, actor: act, start:0,limit:10 },
success: function(response) {
var json = Ext.decode(response.responseText);
var mystore = Ext.data.StoreManager.lookup('RecordedRequestStore');
mystore.loadData(json.recordedRequests);
},
scope: this});
}
I have a button, when user enters values for startdate, enddate and name and clicks on the button the above listener sends them as parameters along with start and limit for paging and response is captured and stored in gridpanel.
My issue with paging toolbar is: I could see the following as response
recordedRequests
// has some meta data here
success
true
total
1339
But my paging tool bar show only one page and at bottom says 0 of 0 and to the right nothing to display. Infact it should say 1 of 14 and should allow me to go through next pages.
2) Also when I click on refresh button it calls my store and calls server, but i want to make a ajax request with startdate, enddate and name as parameters(which would be exactly what my button above listerner does)
My Store looks like this:
autoLoad: false,
remoteFilter: true,
buffered: false,
pageSize: 10,
//leadingBufferZone: 1000,
fields:['start', 'end', 'actor','serviceOp'],
proxy: {
type: 'ajax',
url: 'ListData',
store: 'RecordedRequestStore',
startParam:'start',
limitParam:'limit',
pageParam:'page',
reader: {
type: 'json',
root: 'recordedRequests',
successProperty: 'success',
totalProperty: 'total'
},
extraParams: {
'type': 'recordedRequest',
},
//sends single sort as multi parameter
simpleSortMode: true,
// Parameter name to send filtering information in
filterParam: 'query',
// The PHP script just use query=<whatever>
encodeFilters: function(filters) {
return filters[0].value;
}
},
listeners: {
filterchange: function(store, filters, options){
console.log( filters )
},
totalcountchange: function() {
console.log('update count: ')
//this.down('#status').update({count: store.getTotalCount()});
}
}
Any sort of help will of great value for me. Thanks in Advance.
Instead of Ajax Request. I should use
store.load(params{your params})
For nextpage and previouspage I used beforeload listener for custom parameters.
I am updating my Model through a resource controller via jQuery Ajax Put. No problems at all the first time. This works fine:
$(".addNest").click(function() {
var nid = msg; //once the LI is added, we grab the return value which is the nest ID
var name = $('.nestIn').val();
if(name == '') {
$("textarea").css("border", "1px solid red");
}else {
$.ajax({
type: 'PUT', // we update the default value
url: 'nests/' + nid,
data: {
'name': name
},
success: function(msg) {
alert(msg)
window.location.replace('nests/' + nid ); //redirect to the show view
}
});
}
});
Later in a separate code block, I try to call the PUT again like this:
$(".nestEdit").click(function() {
$(".nestEdit").hide();
var name = $('.nestName').data("name");
var nid = $('.nestName').data("id");
$(".nestName").html("<textarea class='updateNest'>"+ name +"</textarea> <span><a href='#' class='btn btn-mini nestUpdate'><i class='icon-plus'></i> Update</a></span>");
$(".nestUpdate").click(function() {
var updatedName = $('.updateNest').val();
$.ajax({
type: 'PUT', // we update the default value
url: 'nests/' + nid,
data: {
'name': updatedName
},
success: function(msg) {
alert(msg) // showing the error here
location.reload( ); //refresh the show view
}
});
});
The 'updatedName' values and the 'nid' values are passing fine when I 'alert' them. When I view the return for the first PUT it comes back fine. However, when I view the return for the second PUT I get this:
{"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException","message":"","file":"\/Applications\/MAMP\/htdocs\/n4\/bootstrap\/compiled.php","line":8643}}
Anyone have some insights here? As you can tell, I am trying to do an inline edit. I have tried to wrap everything into a function but still not helping...
Laravel does not use PUT and DELETE natively since it is not supported in all browsers, you need to send a POST request with '_method' set to either put or delete.
$.ajax({
type: 'POST',
url: 'nests/' + nid,
data: {
'name': updatedName,
'_method': update
},
success: function(msg) {
alert(msg) // showing the error here
location.reload( ); //refresh the show view
}
EDIT: Ajax request do support PUT AND DELETE.
In your JavaScript code, for the inline editing, you are not making proper use of $.
If you click on .nestEdit, it's inner function should not be calling it by name, provided you have multiple objects of the same class on that page. This is why you get the error. Instead of sending the nest ID, it's sending an array object, which your Laravel Router will not pick up, because it is more than likely not defined.
Simply put, you should not be doing this:
$(".nestEdit").click(function() {
$(".nestEdit").hide();
...
You should be making a call to this:
$(".nestEdit").click(function() {
$(this).hide();
...
So, for every .nestEdit within the inner function, you need to call for this instead.
I'm searching for a knockout validation plugin and I stumbled upon knockout.validation which looks very promising, however, it has a fatal flaw..
Once you have created a ko.validatedObservable({ name: foo }) you are not able to assign a new object to that observable.
For Example: In my view model I instantiate a validated observable.
var item = new ko.validatedObservable(new Tag({}));
I am then able to call:
item().isValid(); //Returns false in this case because Tag is empty
Tag looks like this
Model.Tag = function (data) {
var
Id = ko.observable(data.Id),
Name = ko.observable(data.Name).extend({ required: true, maxLength: 64 }),
Description = ko.observable(data.Description).extend({ required: true, maxLength: 512 });
return {
Id: Id,
Name: Name,
Description: Description
};
};
The issue is if I wanted to get a new tag from the server and then modify that tag..
$.ajax({
url: API + "/" + id,
type: 'GET',
dataType: 'json',
timeout: Timeout,
statusCode: {
200: function(response) { item(response); }, //Here is where the bug is!
404: ItemNotFound
},
error: function () {
Item(new Type({}));
}
});
item now contains the value from the server, however, when I run
item().isValid(); //False is returned
This is listed as bug #209 on the GitHub project https://github.com/ericmbarnard/Knockout-Validation/issues?state=open.
Does anyone know of an elegant work around? Or of another plugin that will accomplish this goal?
I don't know how elegant it is, and maybe this is not the best solution (or not a solution at all) so use it at your own risk.
But you can override the ko.validatedObservable with a "fixed" version:
ko.validatedObservable = function (initialValue) {
if (!ko.validation.utils.isObject(initialValue)) {
return ko.observable(initialValue).extend({ validatable: true });
}
var obsv = ko.observable(initialValue);
obsv.lastErrors = ko.observable(ko.validation.group(initialValue));
obsv.subscribe(function(newValue){
obsv.lastErrors(ko.validation.group(newValue));
});
obsv.errors = function() {
return obsv.lastErrors()();
};
obsv.isValid = ko.computed(function () {
return obsv.errors().length === 0;
});
return obsv;
};
My fix stores the result of the ko.validation.group call and recalculates it when the underlying obsv observable changes and I've also changed the original errors property to use the lastErrors property.
I've update the sample from the github issue you check in this demo JSFiddle.
I keep getting a 500 error when submitting an ajax request. If I turn off the CSRF in config then the posting works. Once I turn it on, though, then I get the 500 error again.
In config.php I have the following values set:
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
I do have jquery cookie being loaded and in my jquery file I have the following code:
$('#reorder').sortable({
opacity: '0.5',
update: function(e, ui){
newOrder = $( "#reorder" ).sortable('serialize');
csrf_cookie_name = $.cookie('csrf_cookie_name')
console.log(newOrder);
console.log(csrf_cookie_name);
$.ajax({
csrf_cookie_name: $.cookie('csrf_cookie_name'),
url: "/client/saveOrder",
type: "POST",
data: newOrder,
// complete: function(){},
success: function(feedback){
console.log('success');
$("#feedback").html(feedback);
//$.jGrowl(feedback, { theme: 'success' });
}
});
}
});
console.log of csrf_cookie_name right now is: cd660b153522bef89dc53f7f95cd6b1d so I am getting the value it seems?
And finally a really simple function in client that does the data handling. Normally I would separate some of this out into the model but I was trying to keep it simple until I got it working.
function saveOrder()
{
$items = $this->input->post('item');
echo '<br/>Items2:' . var_dump($items);
$total_items = count($this->input->post('item'));
for($item = 0; $item < $total_items; $item++ )
{
$data = array(
'pageid' => $items[$item],
'rank' => $item
);
$this->db->where('pageid', $data['pageid']);
$this->db->update('pages', $data);
// echo '<br />'.$this->db->last_query();
}
There's no form being used in the view. It's just an UL with a collection of LI's that I'm dragging around to sort.
There are two solutions. Both work. Check these posts - has ALL the information you need
a-simple-solution-to-codeigniter-csrf-protection-and-ajax
ajax-csrf-protection-codeigniter-2.0
I've had problems in the past when inadvertently using a <form> tag instead of using CI's native form helper form_open(). This needs to be present in order to create the hidden token field. There are also some good suggestions here: csrf-token-problem.
I had this problem few days ago, the solution is simple(at least for me).
change:
$.ajax({
csrf_cookie_name: $.cookie('csrf_cookie_name')
to
$.ajax({
csrf_test_name: $.cookie('csrf_cookie_name')
I got it to work finally. Here's the jquery I used to make it happen:
You have to use both the name of the token and the name of the cookie and make it part of the post object. So token name = cookie name and be sure to add a & at the end.
$('#reorder').sortable({
opacity: '0.5',
update: function(e, ui){
newOrder = 'csrf_test_name=' + $.cookie('csrf_cookie_name') + '&';
newOrder += $( "#reorder" ).sortable('serialize');
console.log(newOrder);
$.ajax({
url: "/client/saveOrder",
type: "POST",
data: newOrder,
csrf_test_name: $.cookie('csrf_cookie_name'),
// complete: function(){},
success: function(feedback){
console.log('success');
$("#feedback").html(feedback);
//$.jGrowl(feedback, { theme: 'success' });
}
});
}
});
I have a view(MVC3) that users place orders from. The view is bound to a model that i use to display modelitems from. There are two functionalities on this view. First you enter the customers details and then you choose the items the user has ordered. This is the code i´m using to build another model to be sent back to serverside:
var modelItems = {
ModelID: [],
Amount: []
};
var serviceModel = {
Name: $.trim($('#name').val()),
Customernumber: $.trim($('#customernumber').val()),
Address1: $.trim($('#address1').val()),
Address2: $.trim($('#address2').val()),
Zipcode: $.trim($('#zipcode').val()),
City: $.trim($('#city').val()),
Country: $.trim($('#country').val()),
Phone: $.trim($('#phone').val()),
Mobile: $.trim($('#mobile').val()),
Email: $.trim($('#email').val())
};
$('div.modelSpan').each(function (i) {
var textBox = $(this).children();
var value = $(textBox).val();
if (value != '0' && value != '') {
var modelID = $(textBox).attr('name');
modelItems.ModelID.push(modelID);
modelItems.Amount.push(value);
}
});
var accessory = {
ModelItems: modelItems,
ServiceModel: serviceModel
};
$.ajax({
url: '/Site/Order', //Renamed sec reasons
type: "POST",
data: JSON.stringify(accessory),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (ordernumber) {
window.location.href = "/Site/OrderInfo/" + businessAB + "/" + ordernumber;
},
error: function () {
alert('error');
}
});
Cool thing in MVC3 is that my accessory automatically binds to my model on serverside called AccessoriesModel. On callback success i´m setting new href to a receipt site to show user what has been created. This all works but my issue is that i would like the receipt view(OrderInfo) to be returned from my controller that receives the [httppost] and not setting new href. Is there a way to do this? This is easy when using regular form submit but because the values for my model dont come from one form it complicates things. Maybe I shouldn´t use AJAX?
You could use knockout JS with Ajax and render your pages with a mixture of JavaScript objects and regular html.