How to make Ext.Ajax.request only after form fields are loaded completely - ajax

I have a function which uses following code to fetch form values-
var formValues = this.myForm.getForm().getValues();
MyForm contains a combobox which loads with form. (There are two separate requests for combo load and form load)
As these two requests are loading at the same time, above code do not return combo values as they are still loading.
Is there any way to check whether combo values are loaded and then only send ajax request for form load so that above code will have all form values?
Edited:
LoadComboBox function just fills the data with some store.
Following is the code for form load-
loadFormGrid: function (){
var allValues = this.myForm.getForm().getValues(); // this do not consider combobox values
Ext.Ajax.request({
params: {action: 'getList', data : allValues },
// ... some code
});
}

I would do something like:
On the success event of the combo box load, call the load method of the form/make your ajax request to populate the fields of the form.
EDIT:
Here is what I mean:
The place where you instantiate your ComboBox probably looks like:
var combo = new Ext.form.ComboBox({
store : new someStoreType({
//add to catch the loaded event
listeners : {
'load' : function(store, recs, options){
loadFormGrid();
}
}
})
});
The store listener above ('load') will catch when the combo box is loaded and will call the function to populate/load the form.

Related

Show Command Buttons Conditionally on hierarchy telerik grid

I want to show a custom command button in a telerik grid hierachy depending on the master-row data
Hi, I have a telerik hierarchy grid data, and I want to show a custom command button in the detail row, depending on the master-row data.
in the detail template grid, i call the ShowIfSubmitted() method.
command.Custom("Void").Text("Void").Click("VoidDeal").Visible("ShowIfSubmitted");
In the function:
function ShowIfSubmitted(dataItem) {
}
I only can access to the model data in the detail row.
But I want to access de master-row data, to check if the value of the property in the model meets the criteria to hide the button in the detail row.
My workaround was to extract the parent row instance model in order to get its id, with this field I created and ajax call to the DB to get all the info that I needed. Actually, with the "arguments" object, I could have extracted the id value.
Basically I just did this:
function ShowIfSubmitted(dataItem) {
var deal_status_id = 0;
$.ajax({
async: false,
data: { dealId: dataItem.Deal_Number },
url: '#Url.Action("action", "controller")',
success: function (data) {
deal_status_id = data;
}
})
return deal_status_id == submitted_status;
}
In the controller action is where I call the service.

Filling MVC DropdownList with AJAX source and bind selected value

I have view for showing Member details. Inside there is an EditorFor element which represents subjects taken by the member.
#Html.EditorFor(m => m.Subject)
Inside the editor template there is a Html.DropDownListFor() which shows the selected subject and button to delete that subject
I am using an Html.DropDownListFor element as :
#Html.DropDownListFor(m => m.SubjectID, Enumerable.Empty<SelectListItem>(), "Select Subject",
new { #class = "form-control subjects" })
The second parameter(source) is set empty since I want to load the source from an AJAX request; like below:
$.getJSON(url, function (response) {
$.each(response.Subjects, function (index, item) {
$('.subjects').append($('<option></option>').text(item.Text).val(item.ID));
});
// code to fill other dropdowns
});
Currently the html loads before the dropdowns are filled. So the values of all subject dropdowns are set to the default "Select Subject". Is there a way around this or is it the wrong approach?
Note: There are a number of dropdowns in this page. That's why I would prefer to load them an AJAX request and cache it instead of putting in viewModel and filling it for each request.
** EDIT **
In AJAX call, the action returns a json object containing dropdowns used across all pages. This action is decorated with [Output Cache] to avoid frequent trips to server. Changed the code in $.each to reflect this.
You can initially assign the value of the property to a javascript variable, and use that to set the value of the selected option in the ajax callback after the options have been appended.
// Store initial value
var selectedId = #Html.Raw(Json.Encode(Model.Subject.SubjectID))
var subjects = $('.subjects'); // cache it
$.getJSON(url, function (response) {
$.each(response, function (index, item) {
subjects.append($('<option></option>').text(item.Text).val(item.ID));
});
// Set selected option
subjects.val(selectedId);
});
However its not clear why you are making an ajax call, unless you are generating cascading dropdownlists which does not appear to be the case. What you doing is basically saying to the client - here is some data, but I forgot to send what you need, so waste some more time and resources establishing another connection to get the rest of the data. And you are not caching anything despite what you think.
If on the other hand your Subject property is actually a collection of objects (in which case, it should be Subjects - plural), then the correct approach using an EditorTemplate is explained in Option 1 of this answer.
Note also if Subject is a collection, then the var selectedId = .. code above would need to be modified to generate an array of the SubjectID values, for example
var selectedIds = #Html.Raw(Json.Encode(Model.Subject.Select(x => x.SubjectID)))
and then the each dropdownlist value will need to be set in a loop
$.each(subjects, function(index, item) {
$(this).val(selectedIds[index]);
});
If your JSON tells you what option they have selected you can simply do the following after you have populated your dropdown:
$('.form-control.subjects').get(0).selectedIndex = [SELECTED_INDEX];
Where [SELECTED_INDEX] is the index of the element you want to select inside the dropdown.

passing data to jquery modal aside from adding parameters to url?

On click of a #dtDelete button I am opening an ajax modal in bootstrap 3. I am also passing a parameter, selected, along with it and using $_GET on the php page to retrieve it.
As the value of selected may or may not be extremely large I think I should avoid passing the value this way / using $_GET.
How the heck can I pass values other than this method? Due to the nature of opening the modal (loading it then showing it) I am stuck on any other ways.
$('#dtDelete').on('click', function () {
//open the modal with selected parameter attached
$('#modal-ajax').load('/modals/m_keystroke_delete.php?selected='+selected);
$('#modal-ajax').modal('show');
});
Pass a data object as a second param to load for it to make a POST request.
$('#dtDelete').on('click', function () {
var data = { 'propertyA': 'extremely large data' };
//open the modal with selected parameter attached
$('#modal-ajax').load(
'/modals/m_keystroke_delete.php?selected=' + selected, // url
data, // data
function(responseText, textStatus, XMLHttpRequest) { } // complete callback
);
$('#modal-ajax').modal('show');
});
You can even pass your "selected" param through the POST request and use $_POST or even $_REQUEST to retrieve the data. Also notice that the modal now shows once the request has completed.
$('#dtDelete').on('click', function () {
var data = {
'selected': selected
'largeData': '...'
};
$('#modal-ajax').load(
'/modals/m_keystroke_delete.php',
data,
function() {
// Invoke the delete-function
deleteComp();
// Show the modal
$(this).modal('show');
}
);
});

How to bind events to element generated by ajax

I am using RenderPartial to generate CListView and all the contents generated properly and good pagination is working fine too. But when I added my custom JS to elements generated by the CListview it works fine for the the fist page content but when i use pagination and click to page 2 then the JS binding fails.
Is there any other way to bind custom event to elements generated in YII CListview I had tried using live, and on nothing work for me here is my js file.
I think I have to call my function on every ajax load in but how can I achieve in yii
This is the script I am using to update ratings on server with button click and this the element for which these forms and buttons are defined are generated by CListview in yii
$(document).ready(function(){
$('form[id^="rating_formup_"]').each(function() {
$(this).live('click', function() {
alert("hi");
var profileid= $(this).find('#profile_id').attr('value');
var userid= $(this).find('#user_id').attr('value');
console.log(userid);
var data = new Object();
data.profile_id=profileid;
data.user_id=userid;
data.liked="Liked";
$.post('profile_rating_ajax.php', data, handleAjaxResponse);
return false;
});
});
});
You can also try CGridView.afterAjaxUpdate:
'afterAjaxUpdate' => 'js:applyEventHandlers'
The $.each method will loop only on existing elements, so the live binder will never see the ajax-generated content.
Why don't you try it like this:
$(document).ready(function(){
$('form[id^="rating_formup_"]').live('click', function() {
alert("hi");
var profileid= $(this).find('#profile_id').attr('value');
var userid= $(this).find('#user_id').attr('value');
console.log(userid);
var data = new Object();
data.profile_id=profileid;
data.user_id=userid;
data.liked="Liked";
$.post('profile_rating_ajax.php', data, handleAjaxResponse);
return false;
});
});
This problem can be solved by two ways:
Use 'onclick' html definitions for every item that is going to receive that event, and when generating the element, pass the id of the $data to the js function. For example, inside the 'view' page:
echo CHtml::htmlButton('click me', array('onclick'=>'myFunction('.$data->id.')');
Bind event handlers to 'body' as the framework does. They'll survive after ajax updates:
$('body').on('click','#myUniqueId',funcion(){...});

Auto Complete for Generic list MVC 3

I have a Generic list in my Model class. I want to have a textbox with autocomplete in my view which fills data from the generic list. How can I do this?.
For this you will need
Function on server side which will return list of matching data and will accept string entered by the user.
Something like this
public JsonResult AutoComplete(string input)
{
//Your code goes here
}
In the View, for the text box you need to bind KeyDown event. You can take help of jQuery for this. On key down handler you will make an Ajax call to the function you have defined in the Controller. Some thing like this:
$.ajax({
url: '#Url.Action("AutoComplete", "ControllerName")',
data: 'input=' + sampleInput,
success: function (data) {
//Show the UL drop down
},
error: function (data) {
// Show Error
}
});
In response you will get list of strings, which you will need to bind to some html element like "UI". Once done, display this UI with proper CSS below the text box. Using jQuery, you can retrieve the pixel location of text box too.
You can not use Asp.Net Auto Complete box in your project as you are developing app in MVC (no viewstate). I hope you get the idea.
You can use JQuery Autocomplate.
To fill the list, you can populate the data from you object.
I can't remember the exact Razor syntax, but you can refer to this:
//data is your Model object of type List<String>
var listString = [#foreach(x in data) { '#x',}];
$( "#dataList" ).autocomplete({
source: listString
});
<input id="dataList">
JQuery Autocomplte
http://jqueryui.com/demos/autocomplete/
This is client side auto complete, I can provide server side if you need.

Resources