jqGrid Custom Edit Dialog - php

I am working to an application that uses jqGrid. The problem is that the edit dialog that should appear at row edit must have a specific layout. So I would prefer to load it via ajax and then send the data back to jqGrid manually. I searched a lot on the forums but I could not find an example of how to do it.
So, I just need jqGrid to fill the edit dialog pop-up with custom content from a PHP script.
UPDATE: THe idea is that I have a form generator, where the user sets the position/width/heigh/visibility of the edit fields... and this must be used in the edit dialog.

You can use editfunc or addfunc option of the navGrid. If for example editfunc are defined then instead of editGridRow jqGrid will be called editfunc with the id of selected row as the parameter.
Alternative you can use custom button (see this answer as an example).
To modify data in the table after ther custom edit dialog you can use setRowData function.
UPDATED: If you need just make some modification of layout of the edit dialog you can use beforeShowForm for th modifications.

You can check this Tutorial, which is the official demo website of jqGrid Plugin. I am sure that there are examples of some "Row Editing" in that category. You can view lots of other examples of jqGrid also, in this demo website.
You can also check the Home page.
If you have any more problems, you can ask it here. I did use some of those examples in one of my client's (confidential) website, so it will be easy to manipulate according to your needs.
Hope it helps.

My edit dialog had too many fields and so became too high, so I had to put the fields side by side in 2 columns. I did it as follows:
I tried various ways, using wrap(), etc, but found that the values are not posted to the server if you modify the original table structure. So I just cloned the tr elements, put them in new tables, and hid the old ones. I did not hide the whole table, so that the validation will still be visible. I put an onchange on the cloned elements to update the old ones. This works great. Parameter tableName is your jqgrid element id.
var splitFormatted = false;
function SplitFormatForm(tableName, add) {
if (!splitFormatted) {
splitFormatted = true;
$("#FrmGrid_" + tableName).append('<table><tr><td><table id="TblGrid_' + tableName + '_A" class="EditTable" border="0" cellSpacing="0" cellPadding="0" /></td><td><table id="TblGrid_' + tableName + '_B" class="EditTable" border="0" cellSpacing="0" cellPadding="0" /></td></tr></table>');
var cc = $("#TblGrid_" + tableName + "> tbody").children("tr").length;
var s = (cc / 2) - 1;
var x = $("#TblGrid_" + tableName + "> tbody").children("tr");
var i = 0;
x.each(function (index) {
var e = $(this).clone();
var oldID = e.attr("id") + "";
var newID = oldID;
if (oldID.substring(0, 3) === "tr_") {
newID = "clone_" + oldID;
$(this).css("display", "none");
e.change(function () { $("#" + oldID + " > .DataTD > .FormElement").val($("#" + newID + " > .DataTD > .FormElement").val()); });
e.attr("id", newID);
if (i++ < s) {
$("#TblGrid_" + tableName + "_A").append(e);
}
else {
$("#TblGrid_" + tableName + "_B").append(e);
}
}
});
//This hack makes the popup work the first time too
$(".ui-icon-closethick").trigger('click');
var sel_id = "'new'";
if (!add) {
sel_id = jQuery('#'+tableName).jqGrid('getGridParam', 'selrow');
}
jQuery('#'+tableName).jqGrid('editGridRow', sel_id, { closeAfterAdd: true, width: 800, afterSubmit: function (response, postdata) { return [response.responseText == 'OK', response.responseText]; } });
}}
Call this code in your editOptions as follows:
afterShowForm: function () { SplitFormatForm("SiteAccountsGrid", false); }

Related

Live filter in Laravel

I have a form that looks like below.
I have three "white" dropdowns to filter the value for the Equipment Registration Tag dropdown ( The values of the dropdown input field that has the Equipment Registration Tag label will only come out after the user selects values for the three "white" dropdowns). So the Equipment Registration Tag values will differ based on the "white" dropdowns value.
I want it to be a live filter, the dropdown options will change immediately every time user selects the "white" dropdown value. Currently, my approach is to use the onchange=" this.form.submit()" attribute on the "white" dropdowns and return the values after the filter, but I realize this method has a disadvantage which is a user might accidentally submit the form when changing the value of "white" dropdowns. How can I prevent this and only allow users to submit the form by clicking the save button?
$this->Calibration_Location = $request->get('selected_location');
$this->Calibration_Category = $request->get('selected_category');
$this->categories = Equipment::select('Category')->distinct()->get()->toArray();
$this->locations = Equipment::select('Location')->distinct()->get()->toArray();
$matchThese = ['Category' => $this->Calibration_Category, 'Location' => $this->Calibration_Location];
$this->Registration_Select_Tags = Equipment::select('Registration Tag')->distinct()->where($matchThese)->get();
I have also tried jQuery, but I can only trigger by a specified dropdown field, not any one of them.
<script type="text/javascript">
$(document).ready(function() {
var location, category
$('#selected_transfer_location').change(function() {
location = $(this).val();
console.log(location);
$('#selected_transfer_category').change(function() {
category = $(this).val();
console.log(category);
});
// $('#transfer_registration_tag').find('option').not(':first').remove();
$.ajax({
url: 'Transaction/' + location + '/' + category,
type: 'get',
dataType: 'json',
success: function(response) {
var len = 0;
if (response.data != null) {
len = response.data.length;
}
if (len > 0) {
for (var i = 0; i < len; i++) {
var id = response.data[i]['Registration Tag'];
var name = response.data[i]['Registration Tag'];
var option = "<option value='" + id + "'>" + name +
"</option>";
$("#transfer_registration_tag").append(option);
}
}
}
})
});
});
</script>
I hope my question is clear, still new to Laravel and I hope could receive some hints from you.
First approach could be that, you use call ajax Query on change of each on of them and fetch filtered results. Something like this:
$('#dropdown1, #dropdown2, #dropdown3').change(function(){
var val1 = $('#dropdown1').val();
var val2 = $('#dropdown2').val();
var val3 = $('#dropdown3').val();
//And then your ajax call here to fetch filtered results.
});
Only issue is this Ajax call will occur min 3 times, one for each of them.
Second approach could be you give small button below those dropdowns, something like FetchTags. When user selects all the 3 values, will click on that button and you call your ajax onClick of that btn. So that your Ajax will be called only once.
You can use livewire to do that. It easy.
To install it, you have to use composer by taping the fowllowing command:
composer req livewire/livewire
Please check this tutorial to see how to how to do what you want to do using the framework.

jQuery - Search Mysql for results, then display within table, but also have a click link for each record

Ive spent several hours trying to resolve an issue with very limited experience with jQuery which is not helping me.
I am wanting to search a database for a list of results using a few input fields and then a submit button, when you click submit the values are passed to a .php script which returns the results and these are displayed in a table within a div container which works perfect.
Each record is then displayed in its own row within the table, with columns for different data.
record number
name
town
What i want is for the record number to be a click link of some kind, which when clicked, it then passes that value and does a different mysql request displaying that unique records data in more detail in a different div container. This is the part i cant get to work as i believe its something to do with BINDING, or the .ON which i dont really know anything or understand how it works, as my experience is very limited.
<script type="text/javascript">
$(document).ready(function() {
$(".click").click(function() {
var name = $("#name").val();
var name = $(this).attr("id");
$('#2').load("mysqlrequest_unique.php?recordid=" +name);
});
$("#get").click(function() {
var sales_record_number = "sales_record_number=" + $("#sales_record_number").val() + "&";
var item_id = "item_id=" + $("#item_id").val() + "&";
var user_id = "user_id=" + $("#user_id").val() + "&";
var buyer_fullname = "buyer_fullname=" + $("#buyer_fullname").val() + "&";
var sale_date = "sale_date=" + $("#sale_date").val() + "&";
var paypal_transaction_id = "paypal_transaction_id=" + $("#paypal_transaction_id").val() + "&";
var ship_to_zip = "ship_to_zip=" + $("#ship_to_zip").val() + "&";
var item_title = "item_title=" + $("#item_title").val() + "&";
$('#1').load("mysqlrequest_all.php?"+sales_record_number+item_id+user_id+buyer_fullname+sale_date+paypal_transaction_id+ship_to_zip+item_title, function(){
var name = $("#name").val();
var name = $(this).attr("id");
$('#2').load("mysqlrequest_unique.php?recordid=" +name);
}
);
});
});
</script>
<div id="1" name='container_display_all'></div>
<div id="2" name='container_display_unique'></div>
This is what each row would have in the table, which doesnt work when its contained in generated html using a jQuery
<a class = 'click' id = '19496'>19496</a>
This isn't working because you are adding html elements dynamically and the event handlers aren't being added to the dynamically added elements.
$(document).ready(...) is only run when the document loads. So if all the elements that have the class click are being added dynamically, this bit of code $(".click") (inside $(document).ready(...) ) will return a jquery object that contains no elements (as there are currently none in the DOM with the class click).
Then later your elements (with class click) are added to the DOM but have no handlers on them. What you need to do is set the handlers for those object when you add them.
So change this line:
$('#1').load("mysqlrequest_all.php?"+sales_record_number+item_id+user_id+buyer_fullname+sale_date+paypal_transaction_id+ship_to_zip+item_title);
to this:
$('#1').load("mysqlrequest_all.php?"+sales_record_number+item_id+user_id+buyer_fullname+sale_date+paypal_transaction_id+ship_to_zip+item_title, function(){
$(".click").click(function() {
var name = $("#name").val();
var name = $(this).attr("id");
$('#2').load("mysqlrequest_unique.php?recordid=" +name);
});
}
);
This code will execute the function that is passed once the new html is loaded into the first div, which will add the needed handlers to the new elements.

jQuery AJAX can't work when injected on external URL?

I am currently trying to retrieve some data from book search sites and populate a personal database with that data. My idea is to inject the necessary jQuery on the page, so that when I see a title I think I'd like to return to in future, I can then just click a cheeckbox, make necessary additional comments, which I then hope to submit by AJAX to a PHP script which then populates my MySQL database for me with the appropriate title.
Do look at this example for a library catalogue:
// for every book entry, append checkboxes
$('.document-frame').append('<p>Choose:?<input type="checkbox" class="Jcustom_c" /></p><p>Serendepity?:<input type="checkbox" class="Jserep" /></p><p>Include snippet?:<input type="checkbox" class="Jsnippet" /></p>');
// append a Submit button at the bottom of the page, and a blank div for feedback upon success in POST-ing the necessary data
$('#resultPage').append('<input id="Justin" class="Jcustom" type="submit"/><div id="Jfeedback"></div>');
// whenever my checkbox is checked, retrieve / "scrape" the necessary book data
$('.Jcustom_c').change(function() {
if ($(this).is(':checked'))
{
var title = $(this).parent().parent().find('.title a').text();
var author = $(this).parent().parent().find('.authors a').text();
var publishd = $(this).parent().parent().find('.publisher').text();
var status = $(this).parent().parent().find('.metadata .summary').text();
var img_link = $(this).parent().parent().find('img.artwork').attr("src")
// create an XML string from that data. Escape "<" and ">", otherwise when we append the string to the browser for feedback, the browser will not render them correctly.
var appended = '<div class="Jappended"><item><title>' + title + '</title><author>' + author + '</author><publisher_n_edn>' + publishd + '</publisher_n_edn><status>' + status + '</status><image>' + img_link + '</image><serep>N</serep></item></div>';
// show the string just below the book title. Hence if I "pick" the book from the catalogue, the XML string will show up to confirm my the fact that I "picked" it.
$(this).parent().parent().append(appended);
}
// if I uncheck the box, I remove the XML string
else {
$(this).parent().nextAll(".Jappended").remove(appended);
$(this).parent().prevAll(".Jappended").remove(appended);
}
});
And then I have the AJAX:
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
$(".Jappended").each(function() {
var placeh = $(this).text();
string = string + placeh;
$('.results_container').append(string);
})
// these come from <textarea> boxes I append to the end of the page just before the Submit button. (Above, I did not include the jQuery to append these boxes.)
var odp = $("#odp").val()
var mre = $("#motivation_revisit").val()
var mra = $("#motivation_rationale").val()
var stu = $(".hdr_block h5 span").text()
var string = string + "<odpath>" + odp + "</odpath><stused>" + stu + "</stused><motivation><revisit>" + mre + "</revisit><rationale>" + mra + "</rationale></motivation></itemset>"
var post_var = { xml_string : string, source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
$('#Jfeedback').html(data);
});
My problem is that I can't seem to get the AJAX to work: When I click on my Submit button, I do not see the output I would expect when I used the exact same jQuery on an HTML file I called from localhost. This, which I called using http://localhost:8888/some_html.html worked:
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
$(document).ready( function() {
...
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
/*
$(".Jappended").each(function() {
var post_var = { xml_string : "hello", source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
// if (data == "Success") {
$('#Jfeedback').html(data);
// }
});
});
});
</script>
<body>
...
</body>
</html>
db-ajax.php is simply:
echo "Success";
I have read this post: jQuery cannot retrieve data from localhost, which mentions something about "JavaScript cannot currently make direct requests cross-domain due to the Same-origin Policy". Is this the reason why my code didn't work on the external page? If yes, what can I do to make the code work, or what other approaches can I adopt to achieve the same goal? I have mutliple book search sites that I am working on, and many of these do not have an API where I can extract data directly from.
Thank you in advance.
P.S.: I've also tried the suggestion by CG_DEV on How to use type: "POST" in jsonp ajax call, which says that $.post can be done with jsonp, which is the data type to use for cross-domain AJAX. Result: On Firebug I do see the POST request being made. But my function callback is not fired, and firebug doesn't register a Response body when at least "Success" should be returned.
you can set allow cross origin resource sharing
Follow two steps:
From server set this on response header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:*
//* if you want to allow it for all origin domain , or you can specify origin domains also to which you want to allow cors.
In client side add this on your page
$.support.cors = true;
Cons: It is not fully supported on ie < ie10.

How would I duplicate form elements AND the data inside them with jQuery?

See this form - http://schnell.dreamhosters.com/form.php
This form has a portion of it where you enter data and can choose to add more of the same data by clicking a button called 'Add A Site' and it will make another of that section to enter another site. This is the jQuery that performs the duplication...
$(function () {
var sites = 1;
var siteform = $("#site1").html();
$(".addsites").live("click", function(e) {
e.preventDefault();
sites++;
$("#events").append("<div id='site" + sites + "'>"
+ "<br /><hr><br />"
+ siteform
+ "<center><button class='removesites' title='site"
+ sites + "'>Remove This Site</button><br />"
+ "<button class='addsites'>Add Another Site</button>"
+ "</center></div>");
});
$(".removesites").live("click", function(e) {
e.preventDefault();
var id = $(this).attr("title");
$("#" + id).remove();
});
});
The duplication works perfectly, but one thing that's bugging me is that when I have to enter data for someone claiming a LOT of sites, it gets very annoying having to repeat same or similar parts of this section of the form (like every site is in the same city, on the same day, by the same person, etc.) So I had the idea that with each duplication, the values of the form elements would also carry over and I just edit what's not the same. The current implementation only duplicates the elements, not the data. I'm not sure how to easily copy the data into new sections, and I can't find any jQuery tools to do that.
PS - This part isn't as important, but I've also considered using this same form to load the data back in for viewing/editing, etc. The only problem with this is that the reprinting of the form means that there will be a form section with the id "Site7" or something, but jQuery starts its numbering at 1, always. I've thought about using selectors to find the highest number site and start off the variable 'sites' at that number, but I'm not sure how. Any advice how to do this, or a better system overall, would be much appreciated.
You want to itterate over the input fields in siteform and store them in an object using their name attribute as a key.
Then after the duplication of the object you made and look for the equivelant fields in the new duplicated form ans set their values.
Somthing like this (not tested, just the idea)
var obj = new Object();
$("#site1 input").each(function(){
obj[this.id] = this.value;
);
// Dupicate form
$.each(obj, function(key, value){
$('#newform input[name="'+key+'"]').value = value;
});
Mind you these two each() functions differ from each other.
http://api.jquery.com/jQuery.each/
http://api.jquery.com/each/
You could consider using cloneNode to truely clone the previous site-div and (by passing true to cloneNode) all of its descendants and their attributes. Just know that the clone will have the same id as the original, so you'll have to manually set its id afterwards
Try this in your click-function
var clone = $("#site" + sites).clone(true, true); // clone the last div
sites++; // increment the number of divs
clone.attr('id', "site" + sites); // give the clone a unique id
$("#events").append(clone); // append it to the container
As Scuzzy points out in a comment jQuery does have its own clone() method (I don't use jQuery much, so I didn't know, and I didn't bother to check before answering). Probably better to use jQuery's method than the built-in cloneNode DOM method, since you're already using jQuery for event listeners. I've updated the code
The query to transfer values is quite simple (please, check the selector for all the right types on the form):
$("#site1").find("input[checked], input:text, input:hidden, input:password, input:submit, option:selected, textarea")
//.filter(":disabled")
.each(function()
{
$('#site2 [name="'+this.name+'"]').val(this.value);
}
Ok I finally figured this out. It's, more or less, an expansion on Alex Pakka's answer.
sites++;
$("#events").append("<div id='site" + sites + "'>"
+ "<hr><br />"
+ siteform
+ "<center><button class='removesites' title='site"
+ sites + "'>Remove This Site</button><br />");
$("#site1").find("input:checked, input:text, textarea, select").each(function() {
var name = $(this).attr("name");
var val = $(this).val();
var checked = $(this).attr("checked");
var selected = $(this).attr("selectedIndex");
$('#site' + sites + ' [name="'+name+'"]').val(val);
$('#site' + sites + ' [name="'+name+'"]').attr("checked", checked);
$('#site' + sites + ' [name="'+name+'"]').attr("selectedIndex", selected);
});
I used extra vars for readability sake, but it should do just as fine if you didn't and used the methods directly.
Dont forget to create a function for registering the event! Its very important because when the DOM is loaded, all new attributes need to be registrated to the DOM.
Small example:
<script>
$(document).ready(function(){
$('#click-me').click(function(){
registerClickEvent();
})
function registerClickEvent(){
$('<input type="text" name="input_field_example[]">').appendTo('#the-div-you-want')
}
registerClickEvent();
})
</script>

Printing results from function on page onclick?

Honestly, I'm not even sure the best way to go about this, but essentially, I have a function in an include file that takes a $type parameter and then will retrieve/print results from my db based on the $type passed into it... What I'm trying to do is have a series of links on a page that, when you click on a certain link, will run the function and display the results accordingly...
So, on the initial load of the page, there is a table that displays everything (and I'm simplifying the table greatly...)
<table>
<tr><th>Item</th><th>Type</th></tr>
<tr><td>Milk</td><td>Dairy</td></tr>
<tr><td>Yogurt</td><td>Dairy</td></tr>
<tr><td>Chicken</td><td>Meat</td></tr>
<tr><td>Zucchini</td><td>Vegetable</td></tr>
<tr><td>Cucumber</td><td>Vegetable</td></tr>
</table>
And, then, in a sidebar, I have a series of links:
Dairy
Meat
Vegetable
I'd like to filter the initial table (and back and forth, etc.) based on the link that is clicked, so that if the user clicks "Vegetable", the function from my include file will run and filter the table to show only "Vegetable" types...
The first idea that comes to mind is to add a class attribute to the <tr> tags and id attribs to the <a> tags so that you can easily filter that way:
<tr class="dairy"><td>Milk</td><td>Dairy</td></tr>
<tr class="meat"><td>Chicken</td><td>Meat</td></tr>
Dairy
Meat
Then in your JavaScript (I'm using jQuery here):
$('a').click(function(evt){
var myId = $(this).attr('id');
$('tr').each(function(idx, el){
if ($(el).hasClass(myId))
{
$(el).show();
}
else
{
$(el).hide();
}
});
});
This has the added benefit of allowing you to localize the text without having to change your code.
Ok I created a proper answer. You can do it the way Darrel proposed it. This is just an extension for the paging thing to avoid cookies:
$('a').click(function(evt){
var myId = $(this).attr('id');
// append a idndicator to the current url
var location = "" + document.location + "";
location = location.split('#',1);
document.location = location + '#' + $(this).attr('id');
//append to next and previous links
$('#nextlink').attr({
'href': $('#nextlink').attr('href') + '#' + $(this).attr('id')
});
$('#previouslink').attr({
'href': $('#previouslink').attr('href') + '#' + $(this).attr('id')
});
$('tr').each(function(idx, el){
if ($(el).hasClass(myId))
{
$(el).show();
}
else
{
$(el).hide();
}
});
});
Some code that is executed after page load:
var filter = window.location.hash ? '[id=' + window.location.hash.substring(1, window.location.hash.length) + ']' : false;
if(filter)
$('a').filter(filter).click();
This simulates/executes a click on page load on the link with the specific id.
But in general, if you have a large database, you should filter it directly with SQL in the backend. This would make the displayed table more consistent. For example if page 1 may only have 3 rows of class 'dairy' and on page 2 10 of class 'dairy'.
If youre printing out the whole tabel up front there is no need to go back to the server you can simple hide all teh rows of a given type. For example with jQuery:
$('#sidebar a').click(function(){
// grab the text content of the a tag conver to lowercase
var type = $(this).text().toLowerCase();
/* filter all the td's in the table looking for our specified type then hid the
* row that they are in
*/
$('#my_data_table td').contents().filter(function(){
return this.nodeType == 3 && this.toLowerCase() == type;
}).parent('tr').hide();
return false;
});
Really though the suggestion abotu adding a class to the TR is better because filtering on text content can get tricky if there is content youre not expecting for some reason (hence my conversion to all lower case to help with this).

Categories