reinitialize datatables with external form data (server-side django app) - ajax

I am working on a django web app, and successfully implemented the fantastic jQuery datatables to present my data with server-side processing. I don't have access to the original files (this is a project for my workplace, they don't have internet access and I'm home now), but it looks something like this:
template:
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/user_table/"
} );
} );
</script>
<table id='example'>
<thead>
<th>name</th>
<th>state</th>
<th>email</th>
</thead>
<tbody>
<td colspan="3" class="dataTables_empty">Loading data from server</td>
</tbody>
</table>
server_side:
def main_view(request):
return render_to_response('index.html')
def datatables_view(request):
start = request.GET['iDisplayStart']
length = request.GET['iDisplayLength']
query = myUser.objects.all()
if request.GET.has_key('sSearch'):
# filtering...
query = query[start:start+length]
response = ["aaData": [(q.name, q.state, q.email) for q in query]]
# return serialized data
again, like I mentioned, I'm not having any trouble with this. The integration works fine. Even better than fine, really. I love it.
What I really need though, is little more complex filter than the default one that datatables comes with. There are very specific types of search relevent for my work that will be very useful. So I have a form that appears vertically above the table. Let's say it looks something like this:
<form>
<label for='name'>name:</label>
<input type='text' name='name'></input>
<label for'costumer'>costumer?</label>
<input type='checkbox' name='costumer'></input>
<select multiple="multiple">
<option id='regular'>regular</option>
<option id='new'>new</option>
</select>
<input type='submit' value='filter!'> </input>
</form>
I want that when a user clicks on the submit button it would send the form data and re-initialize the datatable with my costumized filtering. Then I want another button that would refresh and reload the datatable and cancel out any initial data it was sending (as if you refreshed the page, without actually).
I'm not very experienced with javascript, so simple solutions are the best, but any help would be very much appreciated.

I solved it! Finally...
I used the jquery-datatables-column-filter plugin. It's decent and simple to use, and they have an example on their site how to use an external form. It's true that I'm not actually filtering on specific columns, but since I'm using server-side it doesn't really matter.

Related

Can I access the same controller multiple times in one view without changing the view?

I am using Spring MVC. I have a view that dynamically populates 2 dropdown lists based on queries called from the controller. I want to dynamically run a query based on the first dropdown selection to change the second dropdown, which means access the controller again (I think). Can I access the controller multiple times from the same view without changing the view? So for example, say starting out the first dropdown was a list of US States and the second started out as a list of all US cities, if I selected NC from the first list I would want to change the second list to include only NC cities.
Here is an example of the first dropdown:
<select name = "states" onChange = "populateCityList(this.options[this.selectedIndex].value)">
<option value ="*">All States</option>
<c:forEach items="${states}" var ="state">
<option value ="${state}">${state}</option>
Pretty straightforward, but I don't really know where to go from there. I have it calling a Javascript function within the current view right now, but I don't know if that is correct or what to even do within that function.
The magic word is AJAX.
Your JavaScript function needs to make an AJAX request to your controller, which should ideally return a JSON data structure containing the values for the second drop down. Your JS function should then have a callback that catches the JSON from your controller and populates the drop down HTML by manipulating the DOM. JQuery is the way to go. There are lots of examples on the web, just search for it.
Hi #user2033734 you can do something like this:
JQuery code
$(document).ready(function() {
$("#id1").change(function () {
position = $(this).attr("name");
val = $(this).val()
if((position == 'id1') && (val == 0)) {
$("#id2").html('<option value="0" selected="selected">Select...</option>')
} else {
$("#id2").html('<option selected="selected" value="0">Loading...</option>')
var id = $("#id1").find(':selected').val()
$("#id2").load('controllerMethod?yourVariable=' + id, function(response, status, xhr) {
if(status == "error") {
alert("No can getting Data. \nPlease, Try to late");
}
})
}
})
})
And JSP within
<table style="width: 100%;">
<tr>
<td width="40%"><form:label path="">Data 1: </form:label></td>
<td width="60%">
<form:select path="" cssClass="" id="id1">
<form:option value="" label="Select..." />
<form:options items="${yourList1FromController}" itemValue="id1" itemLabel="nameLabel1" />
</form:select>
</td>
</tr>
<tr>
<td width="40%"><form:label path="">Data 2: </form:label></td>
<td width="60%">
<form:select path="" cssClass="" id="id2">
<form:option value="" label="Select..." />
<form:options items="${yourList2FromController}" itemValue="id2" itemLabel="nameLabel2" />
</form:select>
</td>
</tr>
</table>
I hope help you :)
One solution would be to move some of the data gathering out into a service, so your main controller could use the service to gather the data before sending to the view.

Ajax-Generated Element Values In Form Won't Post to PHP

Although I'm getting correct options for an ajax-generated drop-down (based on the selection of another), I'm not seeing the value post to the PHP script. However, I see all the values from the normal HTML elements (not generated by ajax). What am I missing?
1. HTML produced by my scr_ajax.php script. - OK
$options is produced by the SQL query and the resulting selections are accurate. This is nearly identical to drop_down_1.).
<td>Drop Down 2</td>
<td></td>
<td>
<select name="drop_down_2" id="drop_down_2" value="" style="width:100%">
<option></option>
'.$options.'
</select>
</td>';
2. Where the ajax-generated HTML data goes.. - OK
Properly receives AJAX-generated form element above for the 2nd drop-down.):
...
<tr id="ajaxContent">
</tr>
...
3. Regular 'ol submit button.. - Not OK
drop_down_1 can be captured in $_POST data, but drop_down_2 cannot. I know I'm missing something here..)
<input type="submit" value="Submit Request" />
better start using jquery for everyday tasks.
http://api.jquery.com/jQuery.ajax/
[UPDATE: 11-25-2012]
I'm now able to combine the HTML and AJAX-generated post results by using the jQuery submit listener and populating the hidden field. However, this seems like more of a special technique/workaround as opposed to a more direct approach.
1st, I added the hidden input element:
<input type="hidden" name="drop_down_2" id="drop_down_2" value="" />
2nd, I added the jQuery submit listener:
<script type="text/javascript">
$(document).ready(function(){
$("#form_name").submit(function() {
var field = "drop_down_2";
var param = document.getElementById(field).options[document.getElementById(field).selectedIndex].value;
document.forms[0].elements[field].value = param;
});
});
</script>
[UPDATE: 12-01-2012]
It sounds like the proper solution involves mastery of the serialize function. I will post an update upon verification.

help me ! MVC and AJAX toolkit Editor in ASP.NET

I have view to use Ajax toolkit editor control.
View CreateProduct
<fieldset>
<legend>Product information</legend>
<table align="center">
<tr>
<td><label for="slogan">Slogan:</label></td>
<td><%= Html.TextBox("slogan")%></td>
</tr>
<tr>
<td><label for="content">Content :</label></td>
<td>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<cc1:Editor ID="content" runat="server" Height="300px" />
</td>
</tr>
</table>
</fieldset>
ProductController:
public ActionResult CreateProduct(string slogan, string content)
{
ProductDataContext data = new ProductDataContext();
PRODUCT p = new PRODUCT();
p.SLOGAN = slogan;
p.CONTENT = content;
data.AddProduct(p);
data.SubmitChanges();
return View();
}
When I added a product, just slogan was added, content was null.
I dont understand and how to repair it.
Help me, please!
Thanks so much!
It does not work this way. You are mixing ASP.NET WebForms with MVC. ID="content" only sets the server-side ID of the Editor control. Controller parameters however are mapped by form field names and in your case the name of the corresponding textarea is generated automatically. I'm not aware of any way you could normally change the name of a control rendered by ASP.NET. You can, however try the following:
<script type="text/javascript">
document.getElementById('<%= content.ClientID =>').name = 'content';
</script>
Put this at the bottom of your view. It might just work.
Keep in mind that even if it works, the above is a dirty hack. The right approach in an MVC project would be to initialize the Editor control using just client scripting. This is not always easy but doable. For reference, try looking at the source of this page:
http://www.asp.net/ajax/ajaxcontroltoolkit/samples/htmleditor/OtherSamples/ClientSide.htm

JSP drop down list - using selected item

I have a drop down list and a form with a few textboxes. I would like to populate this form with details of selected item in the drop down list.
I'm doing this in java MVC app (or wannabe) and I have in my jsp page something like this:
<select name="item">
<c:forEach items="${persons}" var="selectedPerson">
<c:set var="person" value="${selectedPerson}" />
<option value="$selectedPerson.id">${selectedPerson.LastName}</option>
</c:forEach>
</select>
Persons is a list of the Person class.
I wonder is it possible to use the variable 'person' directly to fill the form, for example:
<textarea name="name" rows="1" cols="34" >
${selectedPerson.Name}
</textarea>
so that the rest of the form updates when the selectedPerson is changed?
I know how to do this within c#, but I don't have experience with java technologies.
Is it necessary to submit the form to servlet to do this, or it can be done on the client, since I have all my data in the persons list, from the moment of populating the drop down list?
The ${} syntax is JSP syntax, which will only be parsed and run once on the server to generate the HTML, and then sent down the wire as HTML. The changes to the select list then just happen in the client browser: the server doesn't know anything about them.
What you want to do is register a javascript listener on the select box. You should look into using a library ideally to help you do this. JQuery is a very popular solution and is worth reading up on if you're going to be doing this type of development.
If you end up using JQuery, you'll want to do something like the following
<select id="item" name="item">
<c:forEach items="${persons}" var="selectedPerson">
<c:set var="person" value="${selectedPerson}" />
<option value="$selectedPerson.id">${selectedPerson.LastName}</option>
</c:forEach>
</select>
<input name="lastName" id="lastName" type="text"/>
<script type="text/javascript">
$(function() {
$("#item").change(function() {
$("#lastName").val($("option:selected", this).text());
});
});
</script>
This will make more sense once you've read a basic JQuery tutorial, but basically what it does is that each time the select list changes value, it gets the selected option and sets it's content to the lastName input field. Hope this helps.

prototype ajax updater div with different buttons

i'm learning it, but i cant find what's wrong in this!
i want the div2 to get data from the form in div1, called formulario.
i would like to know which item is selected and which button was clicked.
main html file:
<script src="utils/Scripts/prototype.js" type="text/javascript"></script>
<script type="text/javascript">
function sendf(formul, divi, php)
{
var params = Form.serialize($(formul));
new Ajax.Updater(divi, php, {method: 'post', parameters: params, asynchronous:true});
}
</script>
</head>
<body>
<div id="div1">
contenido div1
<form id="formulario" method="POST">
<select size="3" id="lista" onchange="sendf('formulario', 'div2', 'prodiv1.php');">
<option>elemento 1</option>
<option>elemento 2</option>
<option>elemento 3</option>
</select>
<input type="button" id="b1" value="bot1" onclick="sendf('formulario', 'div2', 'prodiv1.php');" />
<input type="button" id="b2" value="bot2" onclick="sendf('formulario', 'div2', 'prodiv1.php');" />
</form>
<div id="div2" style="background: blue;">
contenido div2
</div>
</div>
</body>
</html>
the php file, prodiv1.php:
<?
echo 'exec: prodiv1.php<br>';
print_r($_POST);
echo serialize($_POST);
if (isset($_POST))
{
foreach ($_POST as $key=>$value)
{
echo $key.'=>'.$value."<br>";
}
}
echo "select: ".$_POST['lista'];
if (isset($_POST['b1'])) {echo 'click: boton1';} else {echo 'click: boton2';}
?>
i've tried a lot of things, and seen that it could be done with event observers, httprequests and such, but what i need is quite easy, and probably there's an elegant way to solve it...
i thank in advance any help!
have a nice day.
guillem
if you dont need to actually process the form contents in some way then you have no need to use Ajax to pass to a PHP script. Depending on what exactly you wanted to display in div 2 you could do something as simple as this:
function sendf()
{
var listvar = $('lista').value;
$('div2').update('select menu value was ' + listvar);
}
This is obviously missing quite a lot of detail and can be massively improved but it should highlight the fact that AJAX is not required.
Edit Looking at the rest of the code you have posted, is AJAX really required for this? surely you are just updating the existing page with data already present on the page, the server has no real part to play in this?
Sorry to dive into jQuery again, but this should allow you to get the values into "div2" without an ajax request.
$(document).ready(function() {
$("input").click(function(e) {
$("#div2").html($(this).attr("id")+" clicked<br />");
updateList();
});
});
function updateList() {
$("#div2").append($("#lista").val() + " selected");
}
In plain English this code says "if an input element is clicked, update the value of div2 with the input variables id, and append the selected value from the list to the result". Hopefully that makes sense to you :)
If you need an easy, elegant way to solve this with AJAX, use the jQuery library's ajax and post methods. For more information take a look here, it will significantly cut down on the size and complexity of your code.

Resources