jsGrid: How to pass additional variables from javascript to php using ajax - javascript

I'm using jsGrid for my project. View here for original source code
I want to pass an additional variable call $user_session to use for mysql select query in fetch.php but failed. Below is what i have been trying.
<script>
var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//......
controller: {
loadData: function(){
return $.ajax({
type: "GET",
url: "fetch_data.php",
data: {user_session:user_session} //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
});
},
//......
Here's the fetch.php file
<?php
if($method == 'GET')
{
$user_session = $_GET['user_session']; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
$statement = $connect->prepare($query);
$statement->execute($user_session); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'id' => $row['id'],
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'age' => $row['age'],
'gender' => $row['gender']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
//......
?>
What is the proper way to do this?

First of all, anyone could open up a dev console inside a browser and start fuzzing your session id. While you are correctly preparing your query, defusing sql injection, it does does not protect you from an IDOR, or, i could enumerate your users by just querying your application repeatedly.
If you really want to pass your session id client-side, maybe you could consider using a cookie, as it is less easily editable by a normal user.

I'm able to do by this way.
<script>
//......
controller: {
loadData: function(filter){
var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<
return $.ajax({
type: "GET",
url: "fetch_data.php",
data: {filter,
user_session:user_session //<<<<<<<<<<<<<<<<<<<<<<<<<<<
},
});
},
//......
</script>
In fetch.php i do this.
<?php
if($method == 'GET')
{
$user_session = $_GET['user_session'];//<<<<<<<<<<<<<<<<<<<<<<<<<<<
$query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
$statement = $connect->prepare($query);
$statement->execute([$user_session]); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'id' => $row['id'],
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'age' => $row['age'],
'gender' => $row['gender']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
//......
?>
For the security issue mentioned by #Andrea Golin, i will post another question.Thanks.

Finally, i found a better way.
I can directly call $user_session inside fetch.php.
<?php
require('user_session.php'); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
require('includes/db.php');
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'GET')
{
$query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
$statement = $conn->prepare($query);
$statement->execute([$user_session]); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'ChildID' => $row['ChildID'],
'Name' => $row['Name'],
'BirthDate' => $row['BirthDate'],
'Gender' => $row['Gender'],
'StudyorWorking' => $row['StudyorWorking'],
'CourseorOccupation' => $row['CourseorOccupation'],
'Married' => $row['Married']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
?>

Related

query wont get variable from page

php isn't passing $id to query
I am trying to execute an inline edit script using data pulled from a mysqli query that pulls specific data based on url ?id= using if isset $_GET $id, the page is getting and echoing the id correctly, however, the query isn't getting the $id variable.
I have tested the query by replacing the $id var with a number relative to the data and it works without issue.
I have tried adding the $id into the $_SESSION and retrieving it from there but still no luck.
The main page is an index.php (which has url of index.php?id=2019018) which fetches data and displays it as a datagrid with inline edit capability through js (fetch_data.php).
you may notice tests etc that have been commented out
both scripts are below, any help appreciated
index.php
<html>
<head>
<title>Inline Table Insert Update Delete in PHP using jsGrid</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<style>
.hide
{
display:none;
}
</style>
</head>
<body>
<div class="container">
<br />
<div class="table-responsive">
<h3 align="center">Inline Table Insert Update Delete in PHP using jsGrid</h3><br />
<div id="grid_table"></div>
</div>
</div>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
//session_start();
//$_SESSION['id_sess'] = $id;
?>
<?php
// echo $_SESSION['id_sess'];
echo $id;
?>
</body>
</html>
<script>
$('#grid_table').jsGrid({
width: "100%",
height: "600px",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete data?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "fetch_data.php",
data: filter
});
},
insertItem: function (item) {
return $.ajax({
type: "POST",
url: "fetch_data.php",
data: item
});
},
updateItem: function (item) {
return $.ajax({
type: "PUT",
url: "fetch_data.php",
data: item
});
},
deleteItem: function (item) {
return $.ajax({
type: "DELETE",
url: "fetch_data.php",
data: item
});
},
},
fields: [
{
name: "job_id",
type: "text",
//css: 'hide'
},
{
name: "part_id",
type: "text",
//css: 'hide'
},
{
name: "part_name",
type: "text",
width: 150,
validate: "required"
},
{
name: "part_cost",
type: "text",
width: 150,
validate: "required"
},
{
name: "part_rrp",
type: "text",
width: 50,
validate: "required"
},
{
name: "quantity",
type: "text",
width: 50,
validate: "required"
},
{
type: "control"
}
]
});
</script>
fetch_data.php
<?php
//$id = $_GET['id'];
//$id = $_SESSION['id_sess'];
$connect = new PDO("mysql:host=localhost;dbname=****", "****", "****");
$method = $_SERVER['REQUEST_METHOD'];
/* if(!isset($_GET['id'])) // if it doesnt get id?
{
echo "IT WORKS";
//$id = $_GET['id'];
}else{
$id = $_GET['id'];
} */
if ($method == 'GET') {
$data = array(
':part_name' => "%" . $_GET['part_name'] . "%",
':part_cost' => "%" . $_GET['part_cost'] . "%",
':part_rrp' => "%" . $_GET['part_rrp'] . "%",
':quantity' => "%" . $_GET['quantity'] . "%"
);
//$query = "SELECT job_id, part_id, part_name, part_cost, part_rrp, quantity FROM jobs INNER JOIN job_parts USING (job_id) INNER JOIN parts USING (part_id) Where job_id = 2019018";
$query = "SELECT job_id, part_id, part_name, part_cost, part_rrp, quantity FROM jobs INNER JOIN job_parts USING (job_id) INNER JOIN parts USING (part_id) Where job_id = '$job_id'";
$statement = $connect->prepare($query);
$statement->execute($data);
$result = $statement->fetchAll();
foreach ($result as $row) {
$output[] = array(
'part_id' => $row['part_id'],
'part_name' => $row['part_name'],
'part_cost' => $row['part_cost'],
'part_rrp' => $row['part_rrp'],
'quantity' => $row['quantity']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
if ($method == "POST") {
$data = array(
':part_name' => $_POST['part_name'],
':part_cost' => $_POST["part_cost"],
':part_rrp' => $_POST["part_rrp"]
);
$query = "INSERT INTO parts (part_name, part_cost, part_rrp) VALUES (:part_name, :part_cost, :part_rrp)";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if ($method == 'PUT') {
parse_str(file_get_contents("php://input"), $_PUT);
$data = array(
':part_id' => $_PUT['part_id'],
':part_name' => $_PUT['part_name'],
':part_cost' => $_PUT['part_cost'],
':part_rrp' => $_PUT['part_rrp']
);
$query = "
UPDATE parts
SET part_name = :part_name,
part_cost = :part_cost,
part_rrp = :part_rrp
WHERE part_id = :part_id
";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if ($method == "DELETE") {
parse_str(file_get_contents("php://input"), $_DELETE);
$query = "DELETE FROM parts WHERE part_id = '" . $_DELETE["part_id"] . "'";
$statement = $connect->prepare($query);
$statement->execute();
}
?>
You need to pass the id to your AJAX request too since it is considered a totally separate request.
e.g.
insertItem: function (item) {
return $.ajax({
type: "POST",
url: "fetch_data.php?id="<?php echo $id; ?>,
data: item
});
},

how to obtain registration ids when sending push notifications in curl php

So basically... here are working two files, one is a curlphp script and the other an angular1 js file.
in the js file, When an admin user clicks on 'send notification' an event is triggered in order to send a message by invoking curl through a function.
That function looks like this
$scope.notify = function(title, content, ¿¿ userId ??){
$.ajax({
url: 'app/backend/src/curl-service.php',
type: 'POST',
data: {
userId: 'the problem is here',
title: title,
message: content
},
success: function(data) {
console.log('time to use curl service');
},
error: function(){
console.log('Error! you can't use curl service');
}
});
};
as you can see, I pass some data with ajax to fill the notification's content that will be pushed by this curl-service.php file
<?php
// Incluimos el api asignada al app
define('API_ACCESS_KEY', 'AIzaSyAJvT_Tx7vwZzViWkwUcQHdhx2osTiSXHA');
$registrationIds = array($_POST['userId']);
$title = array($_POST['title']);
$message = array($_POST['message']);
// preparamos los array
$msg = array
(
'title' => $title,
'message' => $message,
'sound' => default,
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Content-Type: application/json',
'Authorization: key=' . API_ACCESS_KEY
);
//iniciamos el servicio conectando con la url
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
curl_close($ch);
echo $result;
//ejecutamos el servicio
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//verificamos posibles errores y se genera la respuesta
if ($err) {
echo "Se ha producido el siguiente error:" . $err;
} else {
echo $response;
}
?>
What I actually need to know, is how can I obtain the registration ids so then I can use it in my php file too
What you are doing wrong is right here in this bit of code:
$registrationIds = array($_POST['userId']);
$title = array($_POST['title']);
$message = array($_POST['message']);
// preparamos los array
$msg = array
(
'title' => $title,
'message' => $message,
'sound' => default,
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
)
You are creating Arrays from your POST data and then using then as Strings afterwards, if you change the first bit to:
$registrationIds = $_POST['userId'];
$title = $_POST['title'];
$message = $_POST['message'];
or even better with security in mind:
$registrationIds = filter_input(INPUT_POST, 'userId', FILTER_SANITIZE_STRING);
$title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);
You should be good to go

how can I use jquery variable in mysql query

At the moment, I am using a $_GET to query mysql and populate a select statement, which works fine. However, I now need to query db using jquery variable and am unable to find a way to use 'depts' instead of '$_GET['dept']'.
I have declared the var global, but realise that you cannot use var in query.
I would be grateful if someone could show me how to amend my code to achieve this. Thanks
php code to populate select
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("sample", $conn);
$result = mysql_query("SELECT * FROM boxes where department = '{$_GET['dept']}' and status = 1 ORDER BY custref ASC");
?>
<select name="boxdest[]" id="boxdest" size="7" multiple="multiple">
<?php
$i=0;
while($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row["custref"];?>"><?php echo $row["custref"];?></option>
<?php
$i++;
}
?>
</select>
jQuery change event code
<script type="text/javascript">
var depts;
$('#dept').on('change', function() {
depts = $('#dept option:selected').html();
if (depts === 'Select a Department') {
$('#deptResult').html('<p>ERROR: You must Select a department to proceed<p/>').css({'color':'red'});
$( "#submit" ).prop( "disabled", true );
return;
}
$('#deptResult').html('<p>SUCCESS: You have selected the following dept: ' + depts + '</p>').css({'color':'black'});
});
</script>
Use jquery ajax() like:
$.ajax({
url : 'process.php',
method : 'get',
async : false,
data : {
variable : value,
// you can pass multiple variables like this and this is available in php like $_REQUEST['variable']
},
success : function(response){
// do what ever you want with the server resposne
}
});
process.php:
$variable = $_REQUEST['variable']; // you can use $variable in mysql query
Can you? Yes
You have to use AJAX. I can recommend crafting simple API for this task. Example using JSON:
api.php
<?php
function output($arr) {
echo json_encode($arr);
exit();
}
if (!isset($_GET['dept'])) {
output([
'success' => false,
"message" => "Department not defined"
]);
}
$mysqli = new mysqli("localhost", "root", "", "test");
if ($mysqli->connect_errno) {
output([
'success' => false,
'dept' => $_GET['dept'],
'message' => "Connect failed: ". $mysqli->connect_error
]);
}
$result = $mysqli->query("SELECT DISTINCT(`department`) FROM `boxes`");
if (!$result) {
output([
'success' => false,
'dept' => $_GET['dept'],
'message' => "Query failed"
]);
}
$departments = [];
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$departments[] = $row['department'];
}
if (!in_array($_GET['dept'], $departments)) {
output([
'success' => false,
'dept' => $_GET['dept'],
'message' => "Department not present in database"
]);
}
$result = $mysqli->query("SELECT `custref` FROM `boxes` WHERE `department`='". $_GET['dept'] ."' ORDER BY `custref` ASC");
if (!$result) {
output([
'success' => false,
'dept' => $_GET['dept'],
'message' => "Query failed"
]);
}
$custref = [];
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$custref[] = $row['custref'];
}
output([
'success' => true,
'dept' => $_GET['dept'],
'custref' => $custref
]);
$result->free();
$mysqli->close();
$(function () {
$('select[data-key][data-value]').each(function (i, element) {
var key = $(element).data("key");
var value = $(element).data("value");
var $originSelector = $('[name="'+ key +'"]');
/**
* Get options from element by name
*/
function getOptions () {
var request = {};
request[key] = $originSelector.val();
$.ajax({
url: "./api.php",
method: "GET",
dataType: "json",
data: request
}).done(function(data) {
setOptions(data);
});
}
/**
* Remove old options
*/
function clearOptions () {
$(element).find('option').remove();
}
/**
* Put new options in input
*/
function setOptions (data) {
if (data['success'] && data[value] !== undefined) {
clearOptions();
$.each(data[value], function (i, option) {
$(element).append('<option value="'+ option +'">'+ option +'</option>');
});
}
}
getOptions();
$originSelector.on("change", function () {
getOptions();
});
});
});
<select name="dept">
<option value="accounting">Accounting</option>
<option value="it">Information technology</option>
</select>
<select name="boxdest[]" id="boxdest" size="7" multiple="multiple" data-key="dept" data-value="custref"></select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Json Encoded PHP array has null appended to it

At this point in the debugging this is what I am sending to my javascript
header("Content-Type: application/json");
//echo json_encode($full_product_list);
echo json_encode(array());
and here is my ajax call
jQuery.get( "non public api sorry ")
.done(function(data) {
console.log("I got a response")
console.log(data)
})
.fail(function(data) {
console.log("Error?")
console.log(data);
})
It errors everytime and in the data my response string for the empty array is
"[]null"
Entire function being called for reference same thing I get an error and at the end of my json there is "null" appended.
function getAllProducts() {
$full_product_list = array();
$loop = new WP_Query( array( 'post_type' => 'product', 'posts_per_page' => -1 ) );
$pf = new WC_Product_Factory();
while ( $loop->have_posts() ) : $loop->the_post();
$post_id = get_the_ID();
$product = $pf->get_product($post_id);
$attributes = $product->get_attributes();
$attrs = array();
foreach ($attributes as $attr) {
$name = str_replace("pa_fablab_", "", $attr["name"]);
$attrs[$name] = $attr["value"];
}
$item = array(
"id" => $post_id,
"name" => get_the_title(),
"price" => $product->get_price()
);
if (sizeof($attrs) > 0) {
$full_product_list[] = array_merge($item, $attrs);
}
endwhile; wp_reset_query();
header("Content-Type: application/json");
//echo json_encode($full_product_list);
echo json_encode(array());
}
Return something from your php page, add die() after to remove the null
header("Content-Type: application/json");
//echo json_encode($full_product_list);
echo json_encode(array("message"=>"ok"));
die();

Get Success Results From AJAX call

I am trying to get the results from an AJAX call, but I keep getting the error results of the function and I have no idea why.
Here is the javascript:
var curfrndurl = "http://www.website.com/app/curfrnd.php?frndid=" + secondLevelLocation + "&userid=" + items;
$("#loadpage1").click(function(event){
event.preventDefault();
$.ajax({
url: curfrndurl,
dataType: 'json',
type: "GET",
success: function (data){
if (data.success) {
alert("Hi");
$("#curstatus").html(data);
$("#curstatus2").hide();
$("#subtform").hide();
}
else
{
alert("Bye");
$("#curstatus2").html(data);
$("#curstatus").hide();
$("#addform").hide();
}
},
error: function() {
alert('Doh!');
}
});
});
The PHP file is:
<?php
$userdbme = $_GET['userid'];
$frndid = $_GET['frndid'];
$query2 = mysql_query("SELECT * FROM follow WHERE yoozer1='$userdbme' AND yoozer2='$frndid' ORDER BY followid DESC LIMIT 0,1");
$numfriends = mysql_num_rows($query2);
if ($numfriends!=0)
{
echo json_encode(array(
'success' => true
//'user_name' => $userdb
));
echo "<h4>Current Friends</h4>";
}
else {
echo json_encode(array('success' => false));
echo "<h4>Not Friends</h4>";
}
?>
Any help would be greatly appreciated! Thanks!
If you want to echo JSON data, then you need to make sure you don't echo anything else before or after the data.
echo json_encode(array(
'success' => true
));
echo "<h4>Current Friends</h4>";
This is not parsable as JSON, because of the "extra" stuff after the JSON data. Try this:
echo json_encode(array(
'success' => true,
'html' => "<h4>Current Friends</h4>"
));
Then you can do: $("#curstatus").html(data.html);

Categories

Resources