jqgrid - copy row(s) with data from database - jqgrid

I'm trying to copy a row, but I'm using the data from a database, and I'm returning it with JSON. I'd like to know if it's possible to make a copy of a row, and if can I delimited the number of times that I can copy the rows. For example, I need to copy a row with id = 6, but I need to make 5 copies of this row. How can I do that?

You could make main work on server side not on client
In jqgrid decraration something like this:
grid.jqGrid({
...
loadComplete: function(data) {
var ids = grid.jqGrid('getDataIDs');
for (var i=0;i<ids.length;i++) {
var id=ids[i];
var rowData = thisGrid.jqGrid('getRowData', id);
grid.jqGrid('setCell', id, 'buttons', '<input type="button" class="copy" value="Copy">');
}
$('button.copy').click(function (e) {
var id = $(e.target).parents('tr')[0].id;
$.ajax({
url: 'some_url',
dataType : "json",
data: {'id': id},
timeout: 10000,
type: 'POST',
success: function (data) {
grid.trigger('reloadGrid');
},
});
});
}
....
});
In php part something like this
$array = array(
'success'=>false
);
if(isset($_POST['id])) {
if($db -> num_rows($q = $db->query("SELECT FROM ... WHERE `id` = ".intval($_POST['id'])) == 1) {
$row = $db -> fetch_assoc($q);
$db->query("INSERT INTO .....);
$array['success'] = true;
}
}
echo json_encode($array);
If you want to copy more than one time you could add some dialog on client side to input number of copies

use getRowData To Grab a Single row from jqgrid and then create an array by var s = new Array() and push the single row no of times you want ..
create a new column inside jqgrid .. using formatter Formatter In jQgrid place a link inside that column write handler for click over that link .. on that handler use getrowdata and grab the fields and then make a ajax call to send to the server...

Related

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.

datatables fnRowCallback: binding click to an event handler

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

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.

how to assign a value to text box when we are select a value from the dropdown

I am using Mvc3 and my view engine is razor and also writing jquery in my view,
how can i assign a value to text box based on select a value from drop down list.
example:
if i am selected EmpId form drop down then the text box will be fill with Employee Name form same table.
$("#Emplist").change(function(){
$.ajax({
url:"#Url.Action("GetEmployeeName","Employee")",
data:{
id: $(this).val()
},
success: function(data){
$("#EmployeeName").val(data);
}
})
})
<select id="Emplist"><option value='1'>Mehmet</option></select>
public string GetEmployeeName(int id){
var emp = //Get Employee by Id
return emp.Name
}
You could bind your OnChange event, make an ajax call and then populate the textbox with the response. You can pass a json result as response, and handle all the parameters you want.
$('#dropDownId').change(function()
{
empId = $(this).attr('value');
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ EmpId: empId }),
success: function (data) {
if (data.Result) {
$("#txtId").val(data.EmpName);
}
}
});
});
Here is a sample example, where dropDownBoxId is the id of the dropDownBox and txtBoxId is the id of Textbox.
$(function () {
$('#dropdownBoxId').change(function () {
// gets the value from the drop down box
var selected = $("#dropdownBoxId option:selected").text();
// puts the value into the textbox
var txtBox = document.getElementById('txtBoxId');
txtBox .value = selected
});
});

how to show filtered jqgrid with search toolbar prefilled using single call to retrieve data

I'm looking for a way to show jqgrid with search toolbar pre-filled and data filtered by this toolbar. I tried code below but this makes two requests to retrieve data. First request retrieves
unfiltered data and only second request retrieves proper data.
How to eliminate first request so that filtered data is retrieved and search toolbar is pre-filled immediately ?
var grid = $("#grid"),
notLoaded= true;
grid.jqGrid({
datatype: "json",
mtype: 'POST',
loadComplete: function() {
$("#gs_Name").val('<%= Request.QueryString["Name"] %>');
if (notLoaded) {
setTimeout( function() {
$("#grid")[0].triggerToolbar();
}, 100 );
notLoaded = false;
}
}
});
Update
I tried to fill search toolbar using search criteria passed from query string
$(function () {
var grid = $("#grid"),
urlFilters;
var namedParameters = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'),
parameters = {},
nameAndValue,
i;
for (i = 0; i < namedParameters.length; i += 1) {
nameAndValue = namedParameters[i].split('=');
parameters[nameAndValue[0]] = decodeURIComponent(nameAndValue[1]);
if (nameAndValue[0] === "filters") {
urlFilters= decodeURIComponent(nameAndValue[1]);
}
}
grid.jqGrid({
postData: { filters: urlFilters },
search:true,
loadComplete: function() {
refreshSearchingToolbar( $(this), 'eq');
}
...
Search toolbar is empty if grid is loaded but grid is filtered and find dialog is filled properly.
Search toolbar is also filled if find dialog is opened.
Debugger shows that in refreshSearchingToolbar condition
if (typeof (postData.filters) === "string" &&
typeof ($grid[0].ftoolbar) === "boolean" && $grid[0].ftoolbar) {
if not satisfied: ftoolbar is undefined.
I removed this check but after that got error at line tagName = control[0].tagName.toUpperCase(); about undefined tagName
How to fix this ?
You should create jqGrid with search: true and postData: {filters: theFilterAsJSON} parameters. Look the answer, this one of this one for details.
UPDATED: The answer shows how to parse postData.filters and fill the fields of the searching toolbar (whenever it's possible) the the corresponding filters.

Resources