datatables fnRowCallback: binding click to an event handler - ajax

Using datatables and fnRowCallback.
I am trying to bind click to each row on the 2nd column.
The table is returning the correct anchor in the 2nd column with the correct variables, but when I click on the link, ajax is sending each one as the same userid.
I think i need to use .each().click but every thing I try doesn't work.
Anybody know what im doing wrong.....
"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
$('td:eq(1)', nRow).html(''+ aData[3] +'').click(function() {
var url = $('.view_log').attr("id");
var timestamp = (new Date()).getTime();
$("#table_container").hide();
$(".themenu").hide();
$("#log").show();
$.ajax({
type: "GET",
url: ''+url+'&x='+timestamp,
dataType: "html",
success: function(data) {
$("#log").html(data);
}
});
});
}

$('.view_log').attr("id"); will get only the first occurrence.
In this SO page try this in the console:
$('.post-tag') //returns all the tags element
$('.post-tag').attr('href') //returns only the href value of the first occurrance
In the handler, specify the event parameter and then use $(e.target) instead.
So $(e.target).attr('id') should do the job.
... .click(function(e){
var url = $(e.target).attr('id');
});
Demo

Related

Kendo Tooltip is empty

dI use a kendo tooltip on cells of a column of a kendo grid but the content of the tooltip is empty.
When I use the chrome debugger, values are correctly set but there is nothing in my tooltip.
$("#gri").kendoTooltip({
filter: "span.tooltip",
position: "right",
content: function (e) {
var tooltipHtml;
$.ajax({
url: ".." + appBaseUrl + "api/Infobulle?id=" + $(e.target[0]).attr("id"),
contentType: "application/json",
dataType: "json",
data: {},
type: "GET",
async: false
}).done(function (data) { // data.Result is a JSON object from the server with details for the row
if (!data.HasErrors) {
var result = data.Data;
tooltipHtml = "Identifiant : " + result.identifiant;
} else {
tooltipHtml = "Une erreur est survenue";
}
// set tooltip content here (done callback of the ajax req)
e.sender.content.html(tooltipHtml);
});
}
Any idea ? Why it is empty ?
After looking at the dev's answer on telerik forums, i found out that you need to do something like
content: function(){
var result = "";
$.ajax({url: "https://jsonplaceholder.typicode.com/todos/1", async:false , success: function(response){
result = response.title
}});
return result;
}
changing directly with e.sender.content.html() won't work, instead we have to return the value. And i tried several approach :
i tried mimick ajax call with setTimeOut, returning string inside it or using e.sender.content.html() wont work
i tried to use content.url ( the only minus i still don't know how to modify the response, i display the whole response)
the third one i tried to use the dev's answer from here
AND check my example in dojo for working example, hover over the third try

AJAX unsubmit form

I've made an ajax search filter which loads when a certain input has a value (this is the search query box):
$("#filter").keyup(function(event){
var query = document.getElementById('query').value;
if(query!=""){
$("#filter").submit();
}
else{
}
});
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "filter_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
Is there a way to "unsubmit" the form when there is no value? So the ajax loaded content will disapeare instead of showing the content related to the last value (that wasn't blank)?
Thanks in advance!
If you want to make the content disappear why don't you just change $('#result').html() to an empty or a default value. This could be done in the 'else' part of query check. There is nothing called unsubmit form. Hope that makes sense

Multiple Ajax PUTs in Laravel 4 Giving Errors

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.

Putting a JSON response into a hidden field and retrieving it into a function

I'm retrieving the number of rows contained by a table in my database with the following function using JSON.
function rowCount()
{
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
datatype:"json",
type: "GET",
url: "/wagafashion/ajax/CmsRowCount.htm",
success: function(response)
{
$("#rows").val(response);
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
In the success handler, the response is arriving as expected. There is no problem on the server side.
The response is just mapped with the long type of Java which represents the number of rows in a database table.
I'm putting this response in a hidden field whose id is rows using $("#rows").val(response); in the success handler.
The above function is invoked when the form is submitted using the following jQuery function.
$(function() {
$('#dataForm').submit(function() {
rowCount(); //Invokes the above function that makes a JSON request.
var rows=$("#rows").val();
alert("rows = "+rows);
return false;
});
});
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time. It alerts the actual value only when I press the submit button once again (without a page refresh).
Also tried to replace the preceding function with the following.
$(function() {
$('#dataForm').submit(function() {
rowCount(); //Invokes the first function that makes a JSON request.
var form = $(this),
url = form.attr('action'),
rows = form.find('input[name="rows"]').val();
alert("rows = "+rows);
return false;
});
});
But it didn't work either. Why does this happen? What is the way of retrieving the correct value of that hidden field into the preceding jQuery function?
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time.
Ajax calls are asynchonrous. When you call rowCount, you start the call, but then rowCount returns and your code continues. The call doesn't complete until later (which is why ajax accepts a callback).
If you trigger the next step in what you're doing from the callback, you'll have the value. You typically do this by having rowCount accept a callback of its own, like this:
function rowCount(callback) // <==== Accept the callback
{
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
datatype:"json",
type: "GET",
url: "/wagafashion/ajax/CmsRowCount.htm",
success: function(response)
{
$("#rows").val(response);
callback(); // <==== Call the callback
},
error: function(e)
{
alert('Error: ' + e);
callback(); // <==== Probably want to give it a value telling it things failed
}
});
}
Then using it:
$(function() {
$('#dataForm').submit(function() {
var form = $(this); // <== Grab this outside the callback
rowCount(function() {
var url = form.attr('action'),
rows = form.find('input[name="rows"]').val();
alert("rows = "+rows);
});
return false;
});
});
If you want to decide whether to allow the form to be submitted on the basis of the callback, you'll have to always cancel the submission, and then trigger submitting it programmatically from the callback if you want to allow it.

Appending data on an area in the view MVC

$("##ViewBag.PageGroupID").append(data);
Now ViewBag.PageGroupID returns the id of the div at runtime.What if i want to append data in the div(the id which i will get runtime).How do i acheive this?
$('#btnPageElementClick').click(function () {
var flag = false;
var b;
$.ajax({ type: 'GET', url: '/ScriptedTestCase/pageElementPV/' + $('#PageElements').val(), data: null,
success: function (data)
{
$("##ViewBag.PageGroupID").append(data); //where divID is the id of the div you append the data.
}
});
return false;
});
Make sure that inside the controller action that rendered the view that contains the script you have shown, you have actually set this data:
ViewBag.PageGroupID = "someDivId";
Also note that in HTML ids cannot start with numbers.

Resources