Multiple row select with shift key using jqGridRender - php

I'd like to implement a multiselect function using jqGridRender (the php only version of jqGrid that uses javascript). Anyways i'm having troubles implementing it. I've found solution for javascript (and you can use javascript in predefinded function), which is here: http://www.trirand.com/blog/?page_id=393/help/multiselect-with-shift-to-emulate-the-same-behaviour-as-in-the-file-explorer/#p9963 I'm declaring this function as heredoc string ($myevent variable), and then call it under $gird->setGridEvent('onSelectRow', $myevent); but it doesn't work, here are the errors (but i'm not suer if they are the real cause):
Notice: Undefined variable: gird in C:\xampp\htdocs\kmedia\grid.php on line 72
Fatal error: Call to a member function setGridEvent() on a non-object in C:\xampp\htdocs\kmedia\grid.php on line 72
I'd also like to ask, how do i make cellEdit function, save the changes into variable, since when i'm setting grid options to cellEdit it works, but doesn't save etc.

You can use Oleg great suggestion from other answer (I modified it a bit):
$.extend($.fn.jqGrid, {
bindKeys: function (settings) {
var o = $.extend({
onEnter: null,
onSpace: null,
onLeftKey: null,
onRightKey: null,
scrollingRows: true
}, settings || {});
return this.each(function () {
var $t = this;
if (!$('body').is('[role]')) { $('body').attr('role', 'application'); }
$t.p.scrollrows = o.scrollingRows;
$($t).keydown(function (event) {
if (isInlineEdit()) {
return; // am if removed space etc does not work in inline edit
}
var target = $($t).find('tr[tabindex=0]')[0], id, r, mind,
expanded = $t.p.treeReader.expanded_field;
if (!target && $t.p.selrow !== null) {
r = $("#" + $t.p.selrow);
if (r.length > 0) {
target = r[0];
}
}
//check for arrow keys
if (target) {
mind = $t.p._index[target.id];
if (event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40) {
// up key
if (event.keyCode === 38) {
r = target.previousSibling;
id = "";
if (r) {
if ($(r).is(":hidden")) {
while (r) {
r = r.previousSibling;
if (!$(r).is(":hidden") && $(r).hasClass('jqgrow')) { id = r.id; break; }
}
} else {
id = r.id;
}
}
if ($.inArray(id, $t.p.selarrrow) === -1) {
if (!event.shiftKey) {// AM. added for shift+up arrow
$($t).jqGrid('resetSelection');
idsOfSelectedRows = []; // AM. Added
}
// todo: how to unselect row if shift is hold?
// this only selectcts row
$($t).jqGrid('setSelection', id);
saveWindowState();
} else {
$t.p.selrow = id;
}
}
//if key is down arrow
if (event.keyCode === 40) {
r = target.nextSibling;
id = "";
if (r) {
if ($(r).is(":hidden")) {
while (r) {
r = r.nextSibling;
if (!$(r).is(":hidden") && $(r).hasClass('jqgrow')) { id = r.id; break; }
}
} else {
id = r.id;
}
}
if ($.inArray(id, $t.p.selarrrow) === -1) {
if (!event.shiftKey) {// AM. added for shift+up down arrow
$($t).jqGrid('resetSelection'); // AM. added
idsOfSelectedRows = [];
}
// todo: how to unselect row if shift is hold?
// this only selectcts row
$($t).jqGrid('setSelection', id);
saveWindowState();
} else {
$t.p.selrow = id;
}
}
// left
if (event.keyCode === 37) {
if ($t.p.treeGrid && $t.p.data[mind][expanded]) {
$(target).find("div.treeclick").trigger('click');
}
if ($.isFunction(o.onLeftKey)) {
o.onLeftKey.call($t, $t.p.selrow);
}
}
// right
if (event.keyCode === 39) {
if ($t.p.treeGrid && !$t.p.data[mind][expanded]) {
$(target).find("div.treeclick").trigger('click');
}
if ($.isFunction(o.onRightKey)) {
o.onRightKey.call($t, $t.p.selrow);
}
}
return false;
}
//check if enter was pressed on a grid or treegrid node
else if (event.keyCode === 13) {
if ($.isFunction(o.onEnter)) {
o.onEnter.call($t, $t.p.selrow);
}
return false;
} else if (event.keyCode === 32) {
if ($.isFunction(o.onSpace)) {
o.onSpace.call($t, $t.p.selrow);
}
return false;
}
}
});
});
}
});

Related

How to set limitations for checkbox using ajax and session?

I have never done combining ajax and session before. So far i have done something like this.
var sessionvar;
$.ajaxSetup({cache: false})
$.get('test.php' ,function (data) {
sessionvar = data;
alert(sessionvar);
var checkedCbs = $('sessionvar:checked');
if (checkedCbs.length === 4) {
alert("You can only select 3 books");
this.checked = false;
}
});
I want to try set the limitations based on session. Inside the test.php i have something like this
<?php
session_start();
if(isset($_POST['sBorrow']) && $_POST['action']){
if(isset($_SESSION['sBorrow']) && is_array($_SESSION['sBorrow'])){
$sborrow = $_POST['sBorrow'];
$set = $_SESSION['sBorrow'];
}
else{
$set = array();
}
if($_POST['action'] == "SET"){
array_push($set, $_POST['sBorrow']);
$_SESSION['sBorrow'] = $set;
}
else if($_POST['action'] == "UNSET"){
$unset = $_SESSION['sBorrow'];
if(($key = array_search($_POST['sBorrow'], $unset)) !== false) {
unset($unset[$key]);
$_SESSION['sBorrow'] = $unset;
}
}
}
//session_destroy();
if(isset($_SESSION['sBorrow'])){
$countses = count($_SESSION['sBorrow']);
echo $countses;
}
// nothing requested, so return all values
print json_encode($_SESSION);
?>
Inside these i have create some array to store something. Never mind that, i just want to know how to run an ajax with session. Im not sure if my codes is right for implementing that.

Nested if statement not firing

I am posting data to my db, however, before I do I have set in my php to echo out any issues. When the 'data != 'signup success' it should run the if within it, this does not work. Any ideas ?
PHP:
if($u == ""){
echo "Please create a username";
exit();
}
Js:
var submitBtn = $('#signUpBtn');
submitBtn.on('click', function() {
var fn = $('#fname'),
ln = $('#lname'),
u = $('#uname'),
e = $('#email'),
p = $('#pword1'),
p2 = $('#pword2'),
fnVal = fn.val(),
lnVal = ln.val(),
uVal = u.val(),
eVal = e.val(),
pVal = p.val(),
p2Val = p2.val();
$.post('phpsrc/parsers/signUp.php',
{fn: fnVal, ln: lnVal, u: uVal, e: eVal, p: pVal},
function(data) {
if (data != 'signup success') {
if (data === 'Please create a username') {
alert('uname');
}
} else {
}
}
);
});
You'd be better off json encoding the data:
if($u == ""){
$data = array("response" => "Please create a username");
exit(json_encode($data));
}
Allowing you to check the response in your ajax request like this:
function(data) {
if (data.response !== 'signup success') {
if (data.response == 'Please create a username') {
alert('uname');
}
} else {
alert('something');
}
}

retrieving Message from a json array

I want to check the username availability while users register. I am working on the front end. The backend code was given to me.
These are the php code in signup.php
if (isset($_GET['chkusername']))
JSON_username_avail($_GET['chkusername']);
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username, $ret));
die();
}
function validate_username($username, & $retval_arr) {
if ($username == NULL)
$retval_arr['E_UserName'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['E_UserName'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['E_UserName'] = "USERNAME_EXISTS";
return $retval_arr;
}
function username_validation($user) {
$username = str_split($user);
foreach($username as $i) {
$i = ord($i);
if ($i >= 48 and $i <= 57)
continue;
if ($i >= 65 and $i <= 90)
continue;
if ($i >= 97 and $i <= 122)
continue;
return FALSE;
}
return TRUE;
}
function data_not_exists($table, $field, $data, $CSense = FALSE) {
$conn = connect_db();
$data = filter_var($data, FILTER_SANITIZE_STRING);
if ($CSense == TRUE)
$sql = "SELECT * FROM ".$table.
" WHERE ".$field.
"='".$data.
"'";
else
$sql = "SELECT * FROM ".$table.
" WHERE upper(".$field.
")='".$data.
"'";
$result = mysqli_query($conn, $sql);
switch ($result - > num_rows) {
case 0:
return TRUE;
break;
case 1:
return FALSE;
break;
default:
die("500 Internal Server Error: 122");
} //switch
}
Now I dont know that much of php. I created a javascript function to send the username to the signup.php page for validation.
Here is my function
function submit_form() {
var u = document.getElementById("username").value;
$.post("signup.php", {
"chkusername": u
},
function (data) {
var x = data; //here i dont know how to get the return string. Whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS.
}, "json");
}
here i am getting the value of x as [object Object].
But i need to store the return message in variable x. I want to know whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS. Kindly help me with that.
The username is POSTed but in the PHP you try to access it with $_GET, change to:
if (isset($_POST['chkusername']))
JSON_username_avail($_POST['chkusername']);
Also your validation logic doesn't look right, what if the username is valid and available? I would add an else clause and set a success variable:
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username));
die();
}
function validate_username($username) {
$retval_arr = array('success' => false, 'message' => '');
if ($username == NULL)
$retval_arr['message'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['message'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['msessage'] = "USERNAME_EXISTS";
else
$retval_arr['success'] = true;
return $retval_arr;
}
and the ajax:
if(!data.success){
console.log(data.message);
} else {
// valid and available
}
Try,
function(data){
var x = data.E_UserName;
}, "json");
also change your request to GET as per MrCode's answer
function submit_form() {
var u = document.getElementById("username").value;
$.get("signup.php", {
"chkusername": u
},
function (data) {
var x = data.E_UserName
}, "json");
}

Javascript using on php [duplicate]

This question already has answers here:
Pass Javascript Array -> PHP
(5 answers)
Closed 9 years ago.
k, i got that so i checked again and found interesting thing that i was missing:
javascript:
function my_tmpDropFunc(ddObj, targetObj ,doll)
{
if(isDropTarget(targetObj, ddObj) || confirmed)
{
var typeTarget = getPositionType(targetObj.id);
var typeDD = getPositionType(ddObj.id);
// Item-Types to Confirm using
toConfirm = new Array();
//toConfirm.push(new Array(32768, 'confirmCostume'));
//Itembox
if (typeTarget == 384)
{
onDropOnItembox(ddObj, targetObj)
return "break";
}
if (typeDD == 384 && onDropFromItembox(ddObj, targetObj))
return "break";
//Essen
if(typeTarget == 8)
{
ddObj.moveTo(pickObj.x, pickObj.y);
SwapBlockingfields(false);
changeShow();
SetToolTip(true);
PICK_ITEM = false;
// Gurt, Style
if(ddObj.contenttype == 64 || ddObj.contenttype == 32768)
{
// If a Confirmation needed, not confirmed an the type requires a confirmation...
if (confirmNeeded && !confirmed && in_multi_array(toConfirm, ddObj.contenttype))
{
// Get the correct BlackOutDialogBox (Defined in array).
for (key in toConfirm)
{
if (ddObj.contenttype == toConfirm[key][0])
{
blackOutDialogBoxToUse = toConfirm[key][1];
if (showUseItemAlarm(ddObj,targetObj,typeTarget,doll,typeDD,blackOutDialogBoxToUse))
return "return";
}
}
}
//Verbrauchen
dd.elements[ddObj.name].hide();
targetObj.div.style.cursor = 'wait';
changeDraggable(false);
ddObj.moveTo(pickObj.x, pickObj.y);
doll = document.getElementById('plDoll').value;
sendRequest('get', 'ajax.php', 'mod=overview&submod=useItem&item='+ ddObj.id +'&doll='+doll);
}
return "return";
}
//Crafting
if (checkCrafting(ddObj,targetObj,typeDD,typeTarget))
return "return";
//Enchanten
if (targetObj.iid && typeTarget < 256 && !ddObj.enchanttype)
return "continue";
if (checkEnchant(ddObj, targetObj, typeTarget))
return "return";
//Ins Inventar
if (typeTarget >= 512)
{
x = getPositionX(targetObj.id)-1;
y = getPositionY(targetObj.id)-1;
field = CalcFieldWithObj(ddObj, typeTarget, maxcols, maxrows);
if(!(field[x][y] & ddObj.contentsize))
return "continue";
}
if(!(targetObj.contenttypeaccept & ddObj.contenttype))
return "continue";
//Bestätigung bevor Item Seelengebunden wird.
if (showUniqueItemAlarm(ddObj,targetObj,typeTarget,doll,typeDD))
return "return";
my_SwapContent (targetObj,ddObj);
newXY(targetObj);
newXY(ddObj);
if(typeTarget < 256)
reformEquiped(targetObj, targetObj.w, targetObj.h, true);
else if(typeDD < 256)
{
reformEquiped(ddObj,targetObj.w, targetObj.h, false);
ddObj.contentsize = ddObj.contentsizebase;
newXY(dd.obj);
}
targetObj.maximizeZ();
//aElts[i].div.style.zindex = 200;
// Pruefen ob von Lager verschoben wird
var from = ddObj.id.substring(1, 4);
var storage = false;
if (from >= 352 && from <= 357)
storage = true;
if (storage)
sendRequest('get', 'ajax/guildstorageswap.php', 'old='+ ddObj.id +'&new='+targetObj.id+'&doll='+doll);
else
sendRequest('get', 'ajax/inventoryswap.php', 'old='+ ddObj.id +'&new='+targetObj.id+'&doll='+doll);
tt_Init(1);
return "break";
}
}
as you can see like "Reflic" suggested it sends data to ajax, so in ajax.php what do i need to create to receive that data what does it send?
Look into json_encode. Example:
var myJSvariable = <?php echo json_encode($myPHPvariable); ?>;
This works for any type of PHP variable, excluding Resources.
Use AJAX to send Requests via JavaScript to an PHP Script.
http://api.jquery.com/category/ajax/ - http://api.jquery.com/jQuery.ajax/
Edit: And of course use the JSON Format.

detect empty field - problem

I am trying detect in ajax what is the field that is empty. (echo $field; >>> output is radios)
This if (!data.livre && data.livre == "radios") { checks if data.livre is not true (that is working) and now i want to check if the echo is radios or not. If is radios i showed to the user: empty radios
function check($form) {
$fields = array("radios", "age");
foreach($fields as $field) {
if(empty($form[$field])) {
echo $field;
return false;
}
}
return true;
}
$data = array();
$data['livre'] = $val-> check($form);
echo json_encode($data);
JSON output:
radios{"livre":false}
js
success: function(data) {
if (!data.livre && data.livre == "radios") { //problem here
$("#msgbox1").fadeTo(200, 0.1, function() {
$(this).html('empty radios').addClass('messageboxerror1').fadeTo(900, 1);
});
}
}
EDIT: What is the best way to identify if the field that is empty is radios or age ?
thanks
If the result can be that only radios or age or none of both can be empty then you have to edit your check to !data.livres || data.livres == "radios" || data.livres == "age". It will then print the message if your json output is the following:
{livres: false}
or
{livres: "radios"}
or
{livres: "age"}
Edit: Changes according to your comment
if (!data.livre) { //problem here
// Do whatever you want to do when livres is false
} else if (data.livre == "radios") {
// Do whatever you want to do when livres is "radios"
} else if (data.livre == "age") {
// Do whatever you want to do when livres is "age"
}

Categories