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?
Related
I have a KendoUI search bar that has a drop down of autocompleted items based on what I type. When I type into I get a drop down menu. When I click on an item in the drop downlist, I want two things to happen. One which works, and that is loading a partial view. But, the other thing deals with updating a div element that is also in that partial view.
The partial view
#{
ViewBag.Title = "Client";
}
<div id="update">#ViewBag.name</div>
<p id="ahhh"></p>
External Javascript function
function onSelect(e) {
$("#navResult").load('/Home/Client');
var value = e.item.text();
alert(value);
$.ajax({
type: "POST",
url: "Home/someStuf",
dataType: "json",
data: {n: value },
success: function (result) {
alert("IT WORKED");
},
error: function (result) {
alert("FAILED");
}
})
}
In the HomeController there is a method called someStuf. I am sending that item that is clicked on the event into the someStuf method.
Now here are the two controller methods that I'm working with.
Secretary s = new Secretary();
public ActionResult Client()
{
ViewBag.name = s.Client;
return PartialView();
}
[HttpPost]
public JsonResult someStuf(String n)
{
s.Client = n;
return Json(n, JsonRequestBehavior.AllowGet);
}
So then I update a class with that value that was passed from javascript. I then add that new value to the viewbag for the partial view Client.
Sorry for the misleading variables. Client is a type of model. Then I always have a partial view that is called client.
When I try this. The ViewBag is not showing the result that I would like. I can get the client side to send to the server. But I can't get the server to send to the client.... I bet it's something simple. But I'm trying to understand this step so I can use the same method to update id and class elements.
<p class="CompanySearchBar">
#(Html.Kendo().AutoComplete()
.Name("companyComplete") //The name of the AutoComplete is mandatory. It specifies the "id" attribute of the widget.
.DataTextField("company") //Specify which property of the Product to be used by the AutoComplete.
.BindTo(Model)
.Filter("contains")
.Placeholder("Company name")
.Events(e => { e.Select("onSelect"); })
)
</p>
The above code allows for a search bar with autocomplete. While typing for an item a drop down list shows up with results having the same substring. When clicking one of the results the onSelect method is activated.
you can give like this and on change event just assign a value using jquery like
function onSelect(e) {
$("#navResult").load('/Home/Client');
var value = e.item.text();
alert(value);
$.ajax({
type: "POST",
url: "Home/someStuf",
dataType: "json",
data: {n: value },
success: function (result) {
$('#ahhh').text(result.NAME); //the object which you returns from the controller
},
error: function (result) {
alert("FAILED");
}
})
}
<label id=ahhh></label>
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.
I want to know about how to retrieve data from map.
I have three button.
Register, Update and Delete from Jsp page.
There are two JSP. First.jsp and Second.jsp.
I included first.jsp in second.jsp.aaa
The buttons are in second.jsp.
At First.jsp.
I have combobox for language change. It must be change language only when click button.
There are two language English and Japanese.
I send API class using ajax according to language id. If id=1(Japanese) and id=2(English).
I Wrote ajax api inside of combobox change function. Below is my code.
$.ajax({
url : 'aa/idsend',
cache : false,
type : 'GET',
dataType : 'json',
contentType : 'application/json; charset=utf-8',
data : "lid="+select,
success: function(data) {
},
});
I receive data from server the following format.
{data = Object {1: "Would you like to register?", 2: "Would you like to update?", 3: "Would you like to delete?"}
Above data are come from database. If I add new data into database the id become 4:"something have".
I want to know how to retrieve these data according button click event.
If click register button I want to take register sentence only. The other is also like that.
It could be GET method also, but i prefer POST.
function ajaxRequest(dataObj, cbFunc) {
$.ajax({
method: 'POST',
url: 'aa/idsend',
data: dataObj
}).done(function(dataFromServer) {
cbFunc(dataFromServer);
});
}
function useData(dataFS) {
//do something with data from server dataFS
}
function getCurrentLanguage() {
var cL = 'en';//default language
//some code to get language from checkboxes
return cL
}
$('.button').on('click', function(e) {
var id = $(this).attr('id'),
jsonData = {},
curLang = getCurrentLanguage();
switch (id) {
case 'register' :
jsonData = {req: 'register', lang: curLang};
break;
case 'update' :
jsonData = {req: 'update', lang: curLang};
break;
case 'delete' :
jsonData = {req: 'delete', lang: curLang};
break;
default:
break;
}
ajaxRequest(jsonData, useData);
});
Then in the aa/idsend serverside script you can prepare data to send according to req POST variable received. Now you even don't need to send back questions like 'Would you like to register?'. Instead you can do action according to req value and send back information about the operation - Success! or Fail!
I want to pass list from jquery ajax to the particular view. In a view user select the type. If they select first type, then it will load two lists and pass to the particular view data. How to do this in Ajax Jquery?
<%:Html.RadioButtonFor(model=> model.Type, 1)%> Type 1
<%:Html.RadioButtonFor(model=> model.Type, 2)%> Type 2
$("#Type").change(function () {
var type = $("#Type");
if (type == 1) {
//*****The following things are added from controller. i want to pass the following lists from ajax*******/
List<SelectListItem> type= new List<SelectListItem>();
type.Add(new SelectListItem { Text = "one", Value = "14" });
type.Add(new SelectListItem { Text = "two", Value = "12" });
}
});
how to do this
I'm presuming that you want to submit the form to pass the value to the view?
If so, in the view with the form elements have the AJAX call:
<script>
$(document).ready(function() {
$("#the-form-id").on("submit", function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/your-controller-name/your-action-name,
data: $("#the-form-id").serialize(),
success: function(data) {
//do something with the View that is returned...
}
});
});
});
</script>
Then, you;'ll need an action in the controller the AJAX is calling that accepts the "data" being passed from the form. In ASP MVC, this will normally be a corresponding Model.
Said action will return a View set up however you want it to be. The original AJAX call will receive this so you can utilize it however you want to.
Hope that helps.
i have two forms on a page. 1st is shown and 2nd one is hidden.
1st form shows list of users and their emails in grid and pagination. when i select a multiple users from grid then a div shows up on the right side of the gird. which will be used to send email to selected user.
2nd form that shows up will input email subjects from users and then pass these whole data to django views.
i have user this ajax code to send whole data to the views function.
$("#_send").click(function(){
var frm = $('#messageform');
frm.submit(function () {
var selectedID = [];
$(':checkbox[name="selectedvalues[]"]:checked').each(function(){
selectedID.push($(this).data("email"));
});
$.ajax({
type: 'POST',
url: '/sendemail/',
processData: true,
data: {'frm':frm.serialize(),
'selectedID': selectedID},
success: function (data) {
alert(data);
},
error: function(data) {
alert("error");
}
});
return false;
});
});
and in django views i am catching like this;
def Send_Message(request):
checked_items = request.POST.getlist('selectedID[]')
Msg_Content = str(request.POST.get('content'))
frm = request.POST.get('frm')
print checked_items
print frm
print Msg_Content
it outputs like this;
abc#gmail.com,abc123#cogilent.comm
csrfmiddlewaretoken=dP7VkSQdWx0fXuX0kJC46arv6HFElvgz&subject=Hi+This+is+testing+message&content=ddddd
but i want these data seperately, message content and message subject.
When you serialize the data; you should be able to do request.POST.get('subject') etc