how use dynamic action in tabular form in oracle apex? - javascript

I have Oracle APEX 4. I created a tabular form manually (with the apex_item package). It contains three fields.
apex_application.g_f03: LOV (select name display, product_id return from products)
apex_application.g_f04: text field "price"
apex_application.g_f05: text field "quantity".
I would like to see the price of the product in f04 after choosing a product name (...f03). The SQL statement is like this:
select price from products where product_id = {..from f03}.
How to do it with dynamic action or javascript function?

OK, I will give you a hint how to implement your scenario.
Things you need are to make it work:
custom tabular for - you already have it
on demand process that fetchs price of the product from db
dynamic action to listen if value in f03 changed
on demand process
Create on demand process named getPrice with following code
declare
v_price number;
begin
select
price
into
v_price
from
products
where
product_id = apex_application.g_x01;
htp.p( v_price );
exception
when others then
htp.p(SQLERRM);
end;
dynamic action
You have to listen event change on jQuery selector :input[name=f03]. Create dynamic action with true action Execute JavaScript Code.
Within true action you have to do ajax call to on demand process. The example code (working) is below:
var
xhr2,
self = $(this.triggeringElement),
productId = self.val(),
row = self.closest('tr');
xhr = $.ajax({
url:'wwv_flow.show',
type:'post',
dataType: 'text',
traditional: true,
data: {
p_request: "APPLICATION_PROCESS=getPrice",
p_flow_id: $v('pFlowId'),
p_flow_step_id: $v('pFlowStepId'),
p_instance: $v('pInstance'),
//p_arg_names: [ item_id ],
//p_arg_values: [ itemValue ],
x01: productId
},
success: function( resultData, textStatus, ajaxObj ){
//do stuff after fetching product price
row.find( ':input[name=f04]' ).val( resultData )
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error occured while retrieving AJAX data: '+textStatus+"\n"+errorThrown);
}
});
Put the stuff together and you will have answer to your question.
Ps.
Don't forget to mark answer as helpfull if it is answer to your question.

Related

Ajax data manipulation when transmitting to Django CBV

I'm using django-autocomplete-light with the select2 "select multiple" widget for a M2M form.
I have it set up to enable "Create New" when the input is not found.
However, my model has additional required fields beyond the initial input of the "select multiple" widget.
I am trying to create a way to prompt the user for the additional fields when trying to create, and then sending that data through ajax to my django view.
Right now, if I pre-supply the other required fields within my view, the user can create a new object with the name that they've entered (and clicked "Create New") for, and the other fields will be determined in my view. This shows me that the code is working, but ideally I'd like to prompt the user for the additional data.
I have created a prompt, however I cannot the correct syntax for transmitting the data.
As an example, pretend I have a model with required fields "Name" and "Location".
On the Select2 widget, the user types a "Name" which doesn't exist as an object, and clicks "Create New". Now, I'd like the script to prompt them for the location, then transmit that in as a get_or_create parameter.
Code below:
**views.py**
class Videoautocomplete(autocomplete.Select2QuerySetView):
create_field = 'name'
def create_object(self, text):
"""Create an object given a text."""
object = Model.objects.all()[0]
return self.get_queryset().get_or_create(name=text, location=object.location)[0]
def get_queryset(self):
"""This is the code for the initial search within the select2 field"""
qs = Model.objects.order_by('name')
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
**select2.js**
$(this).on('select2:selecting', function (e) {
var data = e.params.args.data;
if (data.create_id !== true)
return;
e.preventDefault();
var select = $(this);
$.ajax({
url: $(this).attr('data-autocomplete-light-url'),
type: 'POST',
dataType: 'json',
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", document.csrftoken);
"""Below is prompting the user for the location, and assigning it to the variable location"""
var location = prompt("Please enter the location", "");
},
"""How do I add the contents of the variable Location into the data below?"""
data: {
text: data.id,
forward: yl.getForwards($(this))
},
success: function(data, textStatus, jqXHR ) {
select.append(
$('<option>', {value: data.id, text: data.text, selected: true})
);
select.trigger('change');
select.select2('close');
}
});
});
If I intercept the transmitted JSON object as a string (using "test" as the input), I get this:
{"id":"test","text":"Create \"test\"","create_id":true}
I need to figure out how to inject the Location variable into that object, but I can't figure out the syntax. Any help?

Yii array helper selecting already set value from database

Am using array helpers if data exists i want to select the value...here product category master id is a foreign key in product master table.
A modal gets called on edit button and it uses the same modal as create button
but the fields are populated using hidden input field.
I want to select the already set value from the database.
$("#productmaster-product_category_master_id").val(data.product_category_master_id);
The above code is not working.
<?= $product_form->field($form_product_model, 'product_category_master_id')->dropDownList(
ArrayHelper::map(ProductCategoryMaster::find()->all(),'id','category'),['prompt'=>'','class'=>'form-control select2','style' => 'width:100%;height:80% !important']
);?>
function editProduct(id) {
console.log(id);
$.ajax
({
type:"GET",
url: "<?= Yii::getAlias('#web')?>/product-category-master/product?id="+id,
cache: false,
dataType:"json",
success: function(data)
{
console.log(data);
$('#sourceproduct').click();
$("#newid").val(data.id);
$("#productmaster-product_category_master_id").val(data.product_category_master_id);
//document.getElementById("editbutton").showModal();
//var myArr = JSON.parse(data);
return false;
}
});
}
Found the solution i just had to put
$('#productmaster-product_category_master_id').val(data.product_category_master_id).trigger('change');
instead of
$('#productmaster-product_category_master_id').val(data.product_category_master_id);

display ajax called data in an UI

i have been able to fetch data with an ajax call from active directory .
the php file used to make the ajax call to active directory :http://pastebin.com/tSRxwQL8
The browser console shows that an ajax call returns this :
<p> sn: xxxxxx<br/>givenname: xxxxx<br/>
employeeID: 0050<br/
>distinguishedName: CN=xxxx xxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>
displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>
department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com
<br/>
mail: mhewettk#abc.com<br/>
title: xyz<br/>
I want to take only some attributes above like mail,displayname etc and display in my HTML :
<h2 class="profile__name" id="emailOfUser">Email : </h2>
Now the problem is the jquery that I have used here :
$('.leaderboard li').on('click', function() {
$.ajax({
url: "../popupData/activedirectory.php", // your script above a little adjusted
type: "POST",
data: {
id: $(this).find('.parent-div').data('name')
},
success: function(data) {
console.log(data);
$('#popup').fadeIn();
$('#emailOfUser').html(data); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
error: function() {
alert('failed, possible script does not exist');
}
});
});
problem is this :
$('#emailOfUser').html(data);
this line displays all data whereas I want to select only email,displayname from the above console data
kindly help me how to select only desired attribute data from the above browser console data.
Ideally you should return JSON from PHP file, however if it is not possible for you to make changes to PHP file then you can use split("mail:") and split("title:") to extract data
success: function(data) {
console.log(data);
$('#popup').fadeIn();
var email=(data.split("mail:")[1]).split("title:")[0];
$('#emailOfUser').html(email); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
You are getting response in HTML which makes difficult for you to extract mail, displayname, etc.
You should get the response in JSON which will make it easy for you to extract the required info.
Ask your back-end team to send response in JSON format.
Working Fiddle
Try :
var lines = 'sn: xxxxxx<br/>givenname: xxxxx<br/>employeeID: 0050<br/>distinguishedName: CN=xxxxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com<br/>mail:mhewettk#abc.com<br/>title:xyz<br/>'.split('<br/>');
jQuery.each(lines, function() {
var val = this;
if (val.indexOf('mail') > -1)
// alert(val.split(':')[1]); //Only for test
$('#emailOfUser').html(val.split(':')[1]);
});

jQuery - Add row to datatable without reloading/refreshing

I'm trying add data to DB and show these data in same page using ajax and jQuery datatable without reloading or refreshing page. My code is saving and retrieving data to/from database. But updated data list is not showing in datatable without typing in search box or clicking on table header. Facing same problem while loading page.
Here is my code
//show data page onload
$(document).ready(function() {
catTable = $('#cat_table').DataTable( {
columns: [
{ title: "Name" },
{ title: "Level" },
{ title: "Create Date" },
{ title: "Status" }
]
});
get_cat_list();
});
//save new entry and refresh data list
$.ajax({
url: 'category_save.php',
type: 'POST',
data:{name: name,level: level},
success: function (data) {
get_cat_list();
},
error: function (data) {
alert(data);
}
});
//function to retrieve data from database
function get_cat_list() {
catTable.clear();
$.ajax({
url: 'get_category_list.php',
dataType: 'JSON',
success: function (data) {
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
] );
});
}
});
}
The solution is here - for DataTable server side data source enabled
.draw() will cause your entire datatable to reload, say you set it to show 100 rows, after called .row().add().draw() > datatable will reload the 100 rows again from the server
I wasted an hour trying to find any solution for this very old question, even on DataTable official support there is no good solution suggested ...
My solution is
1- call .row().add()
2- do not call .draw()
3- your row must have an Id identifier to use it as a selector (check the rowId setting of the datatable)
4- after calling .row().add(), the datatable will have the row added to it's local data
5- we need to get this row from datatable object and transform it to HTML using the builtin method .node()
6- we gonna prepend the result HTML to the table :)
All that can be done in two lines of code
var rowData = someRowCreatedByAnAjaxRequest;
myDataTableObject.row.add(rowData);
$("#myTable-dt tbody").prepend(myDataTableObject.row(`tr#${rowData.Id}`).node().outerHTML)
Thanks ☺
From the documentation,
This method will add the data to the table internally, but does not
visually update the tables display to account for this new data.
In order to have the table's display updated, use the draw() method, which can be called simply as a chained method of the row.add() method's returned object.
So you success method would look something like this,
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
]).draw();
});

Add array of items into kendo ui multi select

please pardon my noobness, but I'm new to working with Telerik controls. I have seen many examples of this but they haven't been able to solve my problem. I have a Kendo UI multiselect widget which contains some items and a button which, on clicking, would fill the multiselect widget partially with some items. These items are obtained as JSON from a controller method (ASP.NET MVC). So, the button click actually fires an ajax request and on successfully firing up, it calls a javascript function to fill the multiselect widget up. As of now, the ajax gets fired successfully and the data that I want is coming back successfully, just that the multiselect is not displaying the values.
My javascript/AJAX methods:
function addItems(items) {
var values = new Array();
for (var i = 0; i < items.length; i++) {
values[i] = items[i].Item.ID;
// gets values back correctly
console.log(values[i]);
}
// print values
$('#items').data("kendoMultiSelect").value(['"' + values + '"']);
};
// success
$(document).on("click", "#add-items-button", function () {
var myUrl = $('#MyURL').val();
$.ajax({
url: myUrl, // get URL from view
method: 'GET',
dataType: 'json',
success: function (data) {
addItems(data);
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
My multiselect widget is a partial view so:
#using Kendo.Mvc.UI
#(Html.Kendo().MultiSelect()
.Name("items") // Name of the widget should be the same as the name of the property
.DataValueField("ID")
.DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["items"])
.Placeholder("Add Items")
)
Am I missing something very obvious? Am I writing the data back in an incorrect format to the multiselect widget? Please help.
You need to add items to the data source of the multiselect.
$('#items').data("kendoMultiSelect").dataSource.add( { ID: 1, Name: "Name" });
Here is a live demo: http://jsbin.com/eseYidIt/1/edit
It might help to others
var multiSelect = $('#mymultiSelect').data('kendoMultiSelect');
var val = multiSelect.value().slice();
$.merge(val, "anil.singh#hotmail.com");
multiSelect.value(val);
multiSelect.refresh();
OR
$('#mymultiSelect').data("kendoMultiSelect").dataSource.add({Id:"EMP100XYZ",
EmailId: "ayz#gmail.com" });

Categories