0

I am using jqgrid 4 and i have got a lot of help from stackoverflow and especially Oleg.

The problem is that when i open my edit form for the first time the comboboxes do not show the selected values. And this happen only in the first open of the edit form. After the first time the comboboxes are set to the right value in the edit form. I have used things from this page : jqgrid incorrect select drop down option values in edit box but problem still exists.

I changed all things Oleg proposed.

The first problem that i mentioned still exists. Moreover the datepicker in the first field of the form does not appear until i press in a another field first.

My update code is

the html is

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
    <title>Grid</title>
    <?php 
        session_start(); 
        include("showprogram.php"); 
    ?>
    <link rel="stylesheet" type="text/css" media="screen" href="src/css/jquery-ui-1.8.1.custom.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="src/css/ui.jqgrid.css" />
    <script type='text/JavaScript' src='Scripts/calendar.js'></script>
    <!-- <script type='Text/JavaScript' src='scw.js'></script> -->
    <script src="Scripts/jquery.js" type="text/javascript"></script>
    <script src="Scripts/jquery.blockUI.js" type="text/javascript"></script>
    <script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
    <script src="js/jquery.layout.js" type="text/javascript"></script>
    <script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
    <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
    <script src="js/jquery-ui-timepicker-addon.js" type="text/javascript"></script>
    <style type="text/css">
    #list1 {
        font-size : 12px 
    }   

    body {z-index: 1000}
    </style>        
    <script type='text/JavaScript'>
    function showprogram () {
        document.all.Calculation.style.visibility = "visible";  
        try {
            ShowSchedule('#list1', '#pager1');

        } catch (e) {
            alert("An exception occurred while fetching the schedule. Error name: " + e.name + ". Error message: " + e.message);
        }
    }
    </script>
</head>
<body>
    <div id="grid" style="display:inline;">
    <table id="list1" class="scroll" cellpadding="0" cellspacing="0"></table> 
    <div id="pager1" class="scroll" style="text-align:center;"></div>
    </div>
</body>

and dataform is:

$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1;
// connect to the database
include ('../library/opendb.php');
$result = mysql_query("SELECT COUNT(*) AS count FROM customers ");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;

$start = $limit*$page - $limit; // do not put $limit*($page - 1) 

$SQL = "SELECT ID as id,Day AS Day, CustomerName AS name
       FROM customers";

$result = mysql_query( $SQL ) or die("Couldn t execute query.".mysql_error());

if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) 
{
header("Content-type: application/xhtml+xml;charset=utf-8");
}
else
{
header("Content-type: text/xml;charset=utf-8");
}
$et = ">";
echo "<?xml version='1.0' encoding='utf-8'?$et\n";
echo "<rows>";
echo "<page>".$page."</page>";
echo "<total>" . $total_pages . "</total>";
echo "<records>".$count."</records>"; // be sure to put text data in CDATA

while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
echo "<row id='". $row[id]."'>";
echo "<cell>". $row[id]."</cell>";
echo "<cell>". $row[Day]."</cell>";
echo "<cell>". iconv("ISO-8859-7", "UTF-8", $row[name])."</cell>";

echo "<cell> Is this a button?<input type='button' value='E' onload=\"alert('ok');\"/>        </cell>";
echo "</row>";
} 
echo "</rows>"; 

include ('../library/closedb.php'); 

and the add.php is

$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
$oper = $_POST['oper'];
if(!$sidx) $sidx =1;
$Day = $_POST['Day'];
$name = $_POST['name'];

include ('../library/opendb.php');      
//Set at the right position 
        $name=$name+1;

if($oper == 'add') 

{   

$sql="INSERT INTO Customers (
              Day, 
              CustomerName VALUES ( 
      '".$Day."',
      '".$name."')";
echo $sql;
$result = mysql_query($sql) or die (_ERROR26.":".mysql_error());
include ('../library/closedb.php');
}

elseif($oper == 'del') 

{
$id = $_POST['id'];
$id=mysql_real_escape_string($id);

$sql="DELETE FROM customers 
    WHERE ID=
      '".$id."'";
echo $sql;
$result = mysql_query($sql) or die (_ERROR26.":".mysql_error());
include ('../library/closedb.php');
}

elseif($oper == 'edit') 
{
        $id = $_POST['id'];
        $id=mysql_real_escape_string($id);      
        $sql="UPDATE customers SET 
                        Day = '".$Hmera."', 
                        CustomerName = '".$name."'
                        WHERE ID = '".$id."'";
echo $sql;
$result = mysql_query($sql) or die (_ERROR26.":".mysql_error());
include ('../library/closedb.php');
}

and showprogram.php:

function getDatacustomer()
{
include ('../library/opendb.php');
$SQL = "SELECT CustomerName FROM customers ORDER BY CustomerID ;";
$result = mysql_query( $SQL ) or die("Couldn t execute query.".mysql_error());
$count = mysql_num_rows($result);
include ('../library/closedb.php');
$value="";
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
if ($i!=($count-1)){
$value=$value.''.$i.':'. $row[CustomerName].';';}
else
{$value=$value.''.$i.':'. $row[CustomerName].'';}
$i=$i+1;
}
$value='value:"'.$value.'"';
return $value;
}
?>
<script type='text/JavaScript'>
function ShowSchedule(list, pager) {

jQuery().ready(function (){ 
jQuery(list).jqGrid({
    url:Url, 
    datatype: "xml",
    height: "auto",
    colNames:['id','Day','name'],
    colModel:[
    {name:'id',index:'id', width:40, align:'right', editable:false, editoptions:{readonly:true,size:10}},
    {name:'Day',index:'Day', width:70, align:'right', editable:true, sorttype: 'date', editrules:{date:true},
    editoptions:{dataInit:function(elem){setTimeout(function()
                {$(elem).datepicker({dateFormat:"yy-mm-dd"});},100);}}},
    {name:'name',index:'name', width:120, align:'right', editable:true, edittype:'select',editoptions:{<?php echo getDatacustomer() ?>}},
    ],
    rowNum:30,
    rowList:[10,20,30],
    pager: pager,
    sortname: 'Day',
    viewrecords: true,
    sortorder: "asc",
    loadonce: true,
    shrink: true,
    //toppager: true, for toppage pager 
    editurl:'add.php',
    caption:"Grid",     
    forceFit : true
    });

    jQuery(list).jqGrid('navGrid',pager,{edit:true,add:true,del:true,search:false,view:true, reload:true},
    {width:600,height:"auto",
    reloadAfterSubmit:true,
    closeAfterEdit: true,
    recreateForm: true, 
    onClose: function() {jQuery(list).jqGrid('setGridParam',{datatype:'xml', url:Url}).trigger('reloadGrid');},
    beforeShowForm: function(form) {
              var dlgDiv =  $("#editmod" + jQuery(list)[0].id);
              var parentDiv = dlgDiv.parent(); // div#gbox_list
              var dlgWidth = dlgDiv.width();
              var parentWidth = parentDiv.width();
              var dlgHeight = dlgDiv.height();
              var parentHeight = parentDiv.height();
              // TODO: change parentWidth and parentHeight in case of the grid
                   // is larger as the browser window
              dlgDiv[0].style.top = "260 px";
              dlgDiv[0].style.left = "600 px";
            }
    },
    {width:600,height:"auto",reloadAfterSubmit:true,closeAfterAdd: true,recreateForm: true, onClose: function() {
        jQuery(list).jqGrid('setGridParam',{datatype:'xml', url:Url}).trigger('reloadGrid');},beforeShowForm: function(form) {
              var dlgDiv =  $("#editmod" + jQuery(list)[0].id);
              var parentDiv = dlgDiv.parent(); // div#gbox_list
              var dlgWidth = dlgDiv.width();
              var parentWidth = parentDiv.width();
              var dlgHeight = dlgDiv.height();
              var parentHeight = parentDiv.height();
              // TODO: change parentWidth and parentHeight in case of the grid
                   // is larger as the browser window
              dlgDiv[0].style.top = "260 px";
              dlgDiv[0].style.left = "600 px";
            }
    },
    {width:600,height:"auto",reloadAfterSubmit:true,recreateForm: true}, 
    {height:280,reloadAfterSubmit:true}, 
    {width:650,height:"auto",reloadAfterSubmit:true,recreateForm: true, beforeShowForm: function(form) {
              var dlgDiv =  $("#viewmod" + jQuery(list)[0].id);
              var parentDiv = dlgDiv.parent(); // div#gbox_list
              var dlgWidth = dlgDiv.width();
              var parentWidth = parentDiv.width();
              var dlgHeight = dlgDiv.height();
              var parentHeight = parentDiv.height();
              // TODO: change parentWidth and parentHeight in case of the grid
                   // is larger as the browser window
              dlgDiv[0].style.top = "100 px";
              dlgDiv[0].style.left = "600 px";
            }},
    {});
    jQuery(list).jqGrid('setGridParam',{datatype:'xml', url:Url}).trigger('reloadGrid');
    });
}

The table i want in the grid from the database is like:

id      Day       CustomerName

1    2011-09-09      John

Please help!

Community
  • 1
  • 1
ilektrologaki
  • 95
  • 1
  • 1
  • 8
  • Currently some functions or objects which you use (`Customers` and `ShowSchedule` for example) are not defined. Could you post more full code inclusive full JavaScript code and the test data which can be used to reproduce your problem? – Oleg Oct 06 '11 at 11:04
  • Tried to translate all in English.I appreciate your help! – ilektrologaki Oct 07 '11 at 06:48
  • @Oleg Tried to fix the mess. If there are any other suggestions i will be glad to hear them. – ilektrologaki Dec 09 '11 at 12:09
  • Sorry, but one can see from the code of `ShowSchedule` that you misundestand how the JavaScript code will be executed. The `$(document).ready(function () {/*body*/});` must be **on the top level**. Inside of the body of the `ready` the handler you can call `jQuery(list).jqGrid({...})` **once** to *create* the grid. Later you should call `jQuery(list).trigger('reloadGrid')` to *reload* the grid contain from the server instead of calling `ShowSchedule`. Currently your code try to work like Baron Munchausen who tried to pool himself out of the swamp by pulling his hair. It can't work! – Oleg Dec 09 '11 at 12:41
  • @Oleg I did understand about the only one time that Grid must be created but only today i found out how to do that from the http://stackoverflow.com/questions/3772334/how-to-get-jqgrid-reload-to-go-to-server. You really are an expert. So the two problems i mention in the forms still exist. Is there something else going wrong that influence the form fields? – ilektrologaki Dec 12 '11 at 08:28
  • Sorry, but I can't say anything what do the program which you posted if I see that it's organized in absolutely wrong way (I mean recursive calling of `ShowSchedule` with creating of the same events handler in the event handler). So I can't give any prognoses how the program work and to solve your main problem. I recommend you first make the changes which I described in my previous comment. Moreover you understand not quite correctly what the stackoverflow is. It is not help forum where you can post any code and ask to find an error inside. – Oleg Dec 12 '11 at 10:22
  • You should pick up some technical problem which you has and formulate is *as a question*. The idea of stackoverflow is to collect *good questions* which other people could have. The good answers on the questions *could help other people*. So one try solve not individual problem of one person, but to share user experience. Long program code will be typically included in the text of the question only if it can be used *to reproduce some bug*. You current question don't corresponds the requirements of the stackoverflow. Please read FAQ and [this](http://meta.stackexchange.com/a/86998/147495). – Oleg Dec 12 '11 at 10:30
  • @Oleg I do not understand which of your comments i did not change. I stopped calling ShowSchedule as you said because i understood that this was a mistake. I have a specific problem about the first value that the combobox have when i open the form.this is my original question. Thanks again. – ilektrologaki Dec 12 '11 at 12:28
  • The problem is very easy. You should just inform other if you modified the code. In the most cases one always just append the text of the question with words "**UPDATED**" which follows new information. Independent from this now I know this, I'll reread the current code which you posted and will write my comments later. – Oleg Dec 12 '11 at 12:54
  • @Oleg I am sorry.It was a misunderstanding.I appreciate your help. – ilektrologaki Dec 12 '11 at 13:03
  • I suppose that you have some effects of the mix code between PHP and JavaScript: see "**UPDATED**" part of my answer. – Oleg Dec 12 '11 at 14:14

1 Answers1

0

Your code have too many errors. I recommend you to compare your code with the code from My First Grid part of jqGrid documentation. I point only on some from there because the list of all errors will be too long:

  • You have to include <!DOCUMENT ...> line as the first line of your HTML file which generate your PHP file. The simplest form has HTML5: <!DOCUMENT html>. Currently you use quirks mode which is not supported by jQuery UI and jqGrid. Moreover you include currently showprogram.php event before <html>.
  • You include some JavaScript or CSS files many times in different versions (minimized and not minimized), full code and a part of the same code and so on. If you include for example jquery-ui-1.8.1.custom.css you don't need include ui.datepicker.css. If you include ui.jqgrid.css you don't need include jqModal.css. Including both jquery.js and jquery-1.3.2.min.js is the next error. Including ui.datepicker.js, jquery-ui-1.8.1.custom.min.js and jquery.ui.datetimepicker.min.js instead of just one jquery-ui-1.8.1.custom.min.js is the next error. If you includes jquery.jqGrid.min.js it would be wrong to include non-minimized parts of the same code grid.common.js, ... jqDnR.js. I can continue...
  • You should call the methods like jQuery(list).setGridParam and so on only inside of jQuery(document).ready(function () {...}); (the usage of old styled jQuery().ready(function (){...}); or out of the block is wrong).
  • Setting jqGrid parameter and calling jQuery(list).trigger("reloadGrid") before the grid will be created (before jQuery(list).jqGrid({...});) is wrong.
  • The code jQuery(list).jqGrid({...}); create the grid. It create many internal structures and create many HTML elements of the grid like title, column headers, pager and so on. The grid should be created only once. If you want to reload the data in the grid you should use jQuery(list).trigger('reloadGrid'). In your current code, for example in the onClose event handler you just call ShowSchedule which will try to create the grid one more time, which is wrong.

So you should examine your fill code and redesign how you divide the code in ports. I can repeat that the above list of errors is not full. You have to examine your code vary careful and rewrite many its parts.

UPDATED: You modified code are still a mix from PHP code and JavaScript code. I don't use PHP myself, but I suppose that your problem with selection of the items in the comboboxes exist only because of the mix.

The only syntax error in your code is the usage of trailing commas at the end of colModel definition (,] is illegal). If I just use your code with some simple XML input and some simple result of <?php echo getDatacustomer() ?> (I use value:'John:John;Bob:Bob') the code works see the demo.

More better would be to make clear separation of JavaScript code from the PHP code. I would recommend you to use dataUrl property of editoptions. In the case the corresponding part of PHP code should generate

<select><option value='John'>John</option><option value='Bob'>Bob</option></select>

instead of value:"John:John;Bob:Bob".

UPDATED 2: The option

ajaxEditOptions: {cache: false}

should solve your problem if I understand your current problem correctly.

Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Thanks Oleg!I will do all these and i will come back if there will be the problem again. – ilektrologaki Oct 07 '11 at 08:29
  • Still have the same problem. Even if i use value:'John:John;Bob:Bob' it does not work. Also i see at the demo that you have the same problem with the datepicker as i have. – ilektrologaki Dec 13 '11 at 11:49
  • @ilektrologaki: You should examine the HTML page which will be generated by PHP and which run on the client. Just open source in teh web browser and compare the resulting page with my last demo. – Oleg Dec 13 '11 at 11:53
  • I am doing this all day now. No difference that could explain that yet. I will keep looking. You are very helpful.Thanks – ilektrologaki Dec 13 '11 at 12:31
  • @ilektrologaki: You are welcome! Because I used your code as the basis try to use WinDiff.exe to compare the files. It *must* be differences which you skip during the reading. – Oleg Dec 13 '11 at 13:47
  • I just found out that in Chrome there is no problem. On the other hand I.E.8 is the browser that appears this problem. But your demo works in I.E.8 – ilektrologaki Dec 14 '11 at 09:12
  • The problem with the datepicker still exists in both browsers. Is this something about the initilization of the form? – ilektrologaki Dec 14 '11 at 09:18
  • @ilektrologaki: Probably the reason of the problems is the compatibility settings of IE which you use. Try to add `` in the `` somewhere at the beginning. See [here](http://msdn.microsoft.com/en-us/library/cc288325(v=vs.85).aspx#SetMode) and [here](http://stackoverflow.com/a/5263387/315935) including comments. – Oleg Dec 14 '11 at 09:36
  • Did that and no difference. IE 9 also has the same problem in my other PC – ilektrologaki Dec 14 '11 at 09:48
  • @ilektrologaki: [my demo](http://www.ok-soft-gmbh.com/jqGrid/ilektrologaki.htm) has no problem in IE9 in my tests and I can't see *you version* to find the reason of your problem. I have one more idea: try to include `ajaxSelectOptions: { cache: false }` in the list of jqGrid options (see [the answer](http://stackoverflow.com/a/7422410/315935)). – Oleg Dec 14 '11 at 10:00
  • The problem is that i do not really know how to show you my version. Tried the one with ajaxselectoption and no result. :-( – ilektrologaki Dec 14 '11 at 10:11
  • @ilektrologaki: Do you tried with `ajaxselectoption` or with `ajaxSelectOptions` option? Could you describe your current state more detailed: what is the current problem, in which browsers it exist... What you can find out during debugging? Do you can see that new requests will be send to the server? You can use [Fiddler](http://www.fiddler2.com/fiddler2/) or [Firebug](http://getfirebug.com/) to examine the HTTP traffic. – Oleg Dec 14 '11 at 10:29
  • ajaxSelectOptions. The problem is that the comboboxes are not set at the right value when i open the edit form in I.E. In chrome there is no problem except that in the form the datepicker is not shown until i click in the form just like your demo. I will try Fiddler and come back. – ilektrologaki Dec 14 '11 at 11:24
  • @ilektrologaki: The options `ajaxEditOptions: {cache: false}` should solve your problem. – Oleg Dec 14 '11 at 11:37
  • It did not. Is there a way to catch the values send to the form when initalizing? – ilektrologaki Dec 14 '11 at 12:33
  • @ilektrologaki: What do you mean with "the values send to the form"? I suppose that you used `ajaxEditOptions: {cache: false}` in the wrong place. See [the documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing#properties). You should place in the same property set where you used `recreateForm: true`. It is an option of Add or Edit operation. – Oleg Dec 14 '11 at 13:11
  • I put this option in Edit operation and did not work. I suppose that the form gets the row values in order to show them in a way. Is there a possibility the form not getting the values of comboboxes and therefore not set them in the right value? – ilektrologaki Dec 14 '11 at 13:26
  • @ilektrologaki: I am almost sure that you use something in the wrong way. Do you use now `dataUrl` in the `editoptions` like I recommended you in my answer or just use `value`? `ajaxEditOptions: {cache: false}` will be used of course only in case of usage of `dataUrl`. – Oleg Dec 14 '11 at 13:50
  • Thank you very much for your help!I used the dataUrl, the ajaxEditOptions and changed the encoding of my sql and finally after two months worked! I still have the problem with the datepicker in the form although. – ilektrologaki Dec 16 '11 at 09:15
  • @ilektrologaki: You are welcome! In the future you should always use tools like Fiddler or Firebug to examine the HTTP traffic. Then the problems with wrong encoding of data you would be able to localize in 5 minutes. What is your problem with the datepicker? – Oleg Dec 16 '11 at 09:25
  • You were very helpful and patient with me!When i open the edit form the cursor is in the field of the date but if i click in this field the datepicker does not appear. If i first click inside the form and then in the field of the date then the datepicker is appeared. If i use recreateForm: false the datepicker appear when the form is opened. I do not want neither of them. I want to be able to open the datepicker in the first field when i click in the field without having to click in the form first. I think that this problem appears because the date is the first field of the form. – ilektrologaki Dec 16 '11 at 09:46
  • @ilektrologaki: The reason on the problem seems me easy. You have form where datepicker are in the *first* field which receive focus immediately after the grid creating. You attach the datepicker in the thread which work *after* the focus already set. So you can either try to create datepicker directly in `dataInit` without the usage of `setTimeout` or, if you would have any problem in the way, you can call `$(elem).focus();` inside of `setTimeout` directly after the `$(elem).datepicker({dateFormat:"yy-mm-dd"});`. – Oleg Dec 16 '11 at 10:17
  • Both of these solutions open the datepicker when i open the form. I would prefer to open the datepicker if i want and not when i open the form. This has to do with the focus of the form. Can i make it to focus in the second field? – ilektrologaki Dec 19 '11 at 08:50
  • @ilektrologaki: you can set focus inside `dataInit` for the column having the datepicker, but in the case you should call `$(elem).focus()` inside of `setTimeout` and choose the timeout not too short. – Oleg Dec 19 '11 at 08:58
  • I understood what you are proposing but this only make the datepicker appear a little later but also without clicking in the field.I mean if i do not want to change the date why to appear the datepicker? – ilektrologaki Dec 19 '11 at 09:11
  • @ilektrologaki: Sorry, but I don't understand what you want. Probably you should just use `showOn: 'button'` option of the datepicker? – Oleg Dec 19 '11 at 09:16
  • That's a good solution for my problem. It works! Thanks Oleg!(What i meant is not to have the cursor in the first field when i open the form.That could solve the problem too) – ilektrologaki Dec 19 '11 at 09:23
  • @ilektrologaki: You are welcome! You can change the focus to any other field of the form inside of [afterShowForm](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing#events) instead of the usage of `dataInit`. The ids of the fields in the form are the same as the value of the `name` property of the corresponding column. – Oleg Dec 19 '11 at 09:31