Javascript using on php [duplicate] - php

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.

Related

Send vairables to php via bash CURL

I have a code like this:
<?php
$steamid64="76561197987276114"; //YOUR STEAM ID 64
echo "<br><br>Steamid32: ".getSteamId32($steamid64);
echo "<br><br>Steamid64: ".getSteamID64(getSteamId32($steamid64)); // 76561197985756607
//OBTER STEAM ID 64
function getSteamID64($id) {
if (preg_match('/^STEAM_/', $id)) {
$parts = explode(':', $id);
return bcadd(bcadd(bcmul($parts[2], '2'), '76561197960265728'), $parts[1]);
} elseif (is_numeric($id) && strlen($id) < 16) {
return bcadd($id, '76561197960265728');
} else {
return $id; // We have no idea what this is, so just return it.
}
}
function parseInt($string) {
// return intval($string);
if(preg_match('/(\d+)/', $string, $array)) {
return $array[1];
} else {
return 0;
}
}
function getSteamId32($id){
// Convert SteamID64 into SteamID
$subid = substr($id, 4); // because calculators are
$steamY = parseInt($subid);
$steamY = $steamY - 1197960265728; //76561197960265728
if ($steamY%2 == 1){
$steamX = 1;
} else {
$steamX = 0;
}
$steamY = (($steamY - $steamX) / 2);
$steamID = "STEAM_0:" . (string)$steamX . ":" . (string)$steamY;
return $steamID;
}
?>
The question is: How do I make $steamid64 readable? I mean, without form. So it could be posted by curl from linux bash and reply (return $steamID;) received.
Sorry for a very newb question. Thanks in advance.
i voted to close your question as unclear, but my best guess is that you want to change
<?php
$steamid64="76561197987276114"; //YOUR STEAM ID 64
to
<?php
$steamid64=$_POST['steamid64']??''; //YOUR STEAM ID 64
if(empty($steamid64) || !is_string($steamid64)){
http_response_code(400);
die("missing POST parameter steamid64!");
}
then you can do
curl -d "steamid64=76561197987276114" http://127.0.0.1/page.php
(but again, idk what you're asking, hence the close-vote.)

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.

GET JSON provides two values, I want to add these two togther using php, and then return to callback

$_GET['numberofwelds']; & $_GET['numberofconwelds']; are sent to this script using GET JSON. I want to add these together, and then use json_encode to send a total back to the callback (in another php script) . If both $_GET 's are empty, then I want nothing to happen. How should I change this?
$numberofwelds = $_GET['numberofwelds'];
$numberofconwelds = $_GET['numberofconwelds'];
if (isset($_GET['numberofwelds']) && $_GET['numberofwelds'] != '' {
$numberofwelds + $numberofconwelds = $sum_total;
echo json_encode($sumtotal);
} else {
exit()
}
Firstly, you are trying to access your $_GET variables without checking they exist first.
Secondly, you should be throwing Exceptions instead of just calling exit() or die(). You can then log them with $e->getMessage() or write them to the local filesystem.
Finally, you need to validate your data. Make sure it is what you expect it to be.
if (isset($_GET['numberofwelds']) && isset($_GET['numberofconwelds']))
{
// Now we know both values definitely exist, VALIDATE them
$numwelds = $_GET['numberofwelds'];
$numconwelds = $_GET['numberofconwelds'];
if (is_int($numwelds) && is_int($numconwelds))
{
// Calculate your total
$total = $numwelds + $numconwelds;
echo json_encode($total);
}
else
{
// We get here because your GET variables do exist but they aren't
// numbers as you expect (you or someone else has sent rubbish data)
// You want to do nothing, although I would return an error in your json
// to be displayed to the user or logged by the consumer of the service
}
}
else
{
// We get here because your GET variables simply don't exist. They haven't been
// passed in as you are expecting them to be
// You want to do nothing, although I would return an error in your json
// to be displayed to the user or logged by the consumer of the service
}
Always code defensively.
I'm going to show you what I would do in this situation.
if (isset($_GET['numberofwelds']) && isset($_GET['numberofconwelds']))
{
$numwelds = $_GET['numberofwelds'];
$numconwelds = $_GET['numberofconwelds'];
if (is_int($numwelds) && is_int($numconwelds))
{
$total = $numwelds + $numconwelds;
$response = array("status" => "success", "message" => $total);
echo $response;
}
else
{
$response = array("status" => "failure", "message" => "GET params were not numbers");
echo $response;
}
}
else
{
$response = array("status" => "failure", "message" => "GET params do not exist");
echo $response;
}
Then, in your consuming service (most likely a JavaScript / jQuery AJAX call), you can do the following:
.done(function(data) {
var json = $.parseJSON(data);
if (data.status === "success") {
// Yay, we got a success back
console.log("The total is: " + data.message);
} else if (data.status === "failure") {
// Uh oh, something's gone wrong server-side
console.log(data.message);
}
});
change this
if ($_GET['numberofwelds'] != '' && $_GET['numberofconwelds'] != '') {
$numberofwelds + $numberofconwelds = $sum_total;
echo json_encode($sumtotal);
} else {
exit()
}
to this
if ($numberofwelds && $numberofconwelds ) {
$sum_total = array(
'sumTotal' => $numberofwelds + $numberofconwelds,
);
echo json_encode($sum_total);
}else {
exit();
}
Please always check existence of the array keys with isset() construction or array_key_exists() function.
if (isset($_GET['numberofwelds']) && $_GET['numberofwelds'] != '' && isset($_GET['numberofconwelds']) && $_GET['numberofconwelds'] != '') {
echo json_encode(array("total" => $_GET['numberofwelds'] + $_GET['numberofconwelds']));
} else {
exit();
}
UPDATE
With is_numeric() function this code should be more robust:
if (isset($_GET['numberofwelds']) && is_numeric($_GET['numberofwelds']) && isset($_GET['numberofconwelds']) && is_numeric($_GET['numberofconwelds'])) {
echo json_encode(array("total" => $_GET['numberofwelds'] + $_GET['numberofconwelds']));
} else {
exit();
}
PHP reference: array_key_exists()
PHP reference: isset()
$numberofwelds = json_decode($_GET['numberofwelds'], true);
$numberofconwelds = json_decode($_GET['numberofconwelds'], true);
$mergedJson = array_merge(numberofwelds, numberofconwelds);
echo json_encode($mergedJson);
This should do it. It grabs the json, decodes and turns it in to an array (second parameter of json_decode set to true) and then combines them.

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");
}

Multiple row select with shift key using jqGridRender

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;
}
}
});
});
}
});

Categories