how can I use jquery variable in mysql query - javascript

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>

Related

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

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

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 input value to database from 2 related option based on API data

I tried to input options value to database from 2 related option, the problem is the value on option is id, not the string. I successfully input value on 1 option value only, but i need 2 of that option value to inputted on my database.
here's my js code :
$(document).ready(function(){
loadProvinsi('#oriprovince');
loadProvinsi('#desprovince');
$('#oriprovince').change(function(){
$('#oricity').show();
var idprovince = $('#oriprovince').val();
loadCity(idprovince,'#oricity')
});
});
function loadProvinsi(id){
$('#oricity').hide();
$('#descity').hide();
$(id).html('loading...');
$.ajax({
url:'process.php?act=showprovince',
dataType:'json',
success:function(response){
$(id).html('');
province = '';
$.each(response['rajaongkir']['results'], function(i,n){
province = '<option value="'+n['province_id']+'">'+n['province']+'</option>';
province = province + '';
$(id).append(province);
});
},
error:function(){
$(id).html('ERROR');
}
});
}
function loadCity(province,id){
$.ajax({
url:'process.php?act=showcity',
dataType:'json',
data:{province:province},
success:function(response){
$(id).html('');
city = '';
$.each(response['rajaongkir']['results'], function(i,n){
city = '<option value="'+n['city_id']+'">'+n['city_name']+'</option>';
city = city + '';
$(id).append(city);
});
},
error:function(){
$(id).html('ERROR');
}
});
}
if i change to this line code :
province = '<option value="'+n['province']+'">'+n['province']+'</option>';
it successfully become string but the other option cant show the list of city because its based on province id, any suggestion like 2 value on option maybe ?
slice of register form registuser.php
<tr>
<td><label for="prov_usr">Provinsi</label></td>
<td>
<select name="prov_usr" id="oriprovince">
<option>Provinsi</option>
</select>
</td>
</tr>
<tr>
<td><label for="kota_usr">Kota</label></td>
<td>
<select name="kota_usr" id="oricity">
<option>Kota</option>
</select>
</td>
</tr>
slice of process.php
header("Content-Type: application/json");
require_once('idmore.php');
$IdmoreRO = new IdmoreRO();
if(isset($_GET['act'])):
switch ($_GET['act']) {
case 'showprovince':
$province = $IdmoreRO->showProvince();
echo $province;
break;
case 'showcity':
$idprovince = $_GET['province'];
$city = $IdmoreRO->showCity($idprovince);
echo $city;
break;
idmore.php (php class)
class IdmoreRO{
private $key;
public function __construct()
{
//masukan api key disini
$this->key = '3f01f13ce2b42ba983ad3f3bc4852f84';
}
//menampilkan data provinsi
public function showProvince()
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://rajaongkir.com/api/starter/province",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"key: $this->key"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
$result = 'error';
return 'error';
} else {
return $response;
}
}
//menampilkan data kabupaten/kota berdasarkan id provinsi
public function showCity($province)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://rajaongkir.com/api/starter/city?province=$province",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"key: $this->key"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
$result = 'error';
return 'error';
} else {
return $response;
}
}
You need to work with the two values, the string to send to the server on submit, and the id to query for the cities in your ajax request. You will need to use the string in the value attribute since that's what the form will submit to the server, and add an additional attribute with the id so you can use it in the ajax request.
So to build the province select you can do this:
'<option value="'+n['province']+'" data-province_id="'+n['province_id']+'">'+n['province']+'</option>';
and where you get the province_id to query for the cities, access it like
var idprovince = $("#oriprovince option:selected").data("province_id");
Your code should look like this:
$(document).ready(function(){
loadProvinsi('#oriprovince');
loadProvinsi('#desprovince');
$('#oriprovince').change(function(){
$('#oricity').show();
var idprovince = $("#oriprovince option:selected").data("province_id")
loadCity(idprovince,'#oricity')
});
});
function loadProvinsi(id){
$('#oricity').hide();
$('#descity').hide();
$(id).html('loading...');
$.ajax({
url:'process.php?act=showprovince',
dataType:'json',
success:function(response){
$(id).html('');
province = '';
$.each(response['rajaongkir']['results'], function(i,n){
province = '<option value="'+n['province']+'" data-province_id="'+n['province_id']+'">'+n['province']+'</option>'
province = province + '';
$(id).append(province);
});
},
error:function(){
$(id).html('ERROR');
}
});
}
function loadCity(province,id){
$.ajax({
url:'process.php?act=showcity',
dataType:'json',
data:{province:province},
success:function(response){
$(id).html('');
city = '';
$.each(response['rajaongkir']['results'], function(i,n){
city = '<option value="'+n['city_id']+'">'+n['city_name']+'</option>';
city = city + '';
$(id).append(city);
});
},
error:function(){
$(id).html('ERROR');
}
});
}
You can use jQuery.data() or jQuery.attr()

Retrieve parts of jquery response to populate inputs and selects

I send a jQuery request (incorporating a business_id) to a php file to retrieve all values in the database to populate the fields and selects that are in my form and correspond to this id. However, how am I able to retrieve the response from the database in pieces? So that I can provide the fields and selects that are in the form with the values from the database. My javascript function looks as follows:
businessselect: function(){
$('#busselect').change(function() {
opt = $(this).val();
if (opt=="new_bus") {
location.reload();
}
else
{
businessid = $(this).children(":selected").attr("id");
$.ajax({
url : "businessdata.php",
method : "post",
data : "business_id="+businessid,
success: function(response) {
$("#uitgevoerd_door_naam").val(response);
}
});
}
});
},
My businessdata.php looks as follows:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST)
{
$result = $mysqli->query("SELECT * from form WHERE ID ='$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
echo $row['uitgevoerd_door_naam'];
echo $row['hoev_gev_stof_score'];
}
}
mysqli_close($mysqli);
?>
What I want to achieve is:
$("#uitgevoerd_door_naam").val() == $row['uitgevoerd_door_naam'];
$("#hoev_gev_stof_score").val() == $row['hoev_gev_stof_score'];
etc.....
Fix:
Use json encode:
function:
businessselect: function(){
$('#busselect').change(function() {
opt = $(this).val();
if (opt=="new_bus") {
location.reload();
}
else
{
businessid = $(this).children(":selected").attr("id");
$.ajax({
url : "businessdata.php",
method : "post",
dataType: "json",
data : "business_id="+businessid,
success: function(response) {
$("#uitgevoerd_door_naam").val(response.a);
$("#riskpot_scorefield3").val(response.b);
}
});
}
});
},
php file:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST)
{
$result = $mysqli->query("SELECT * from form WHERE ID = '$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
echo json_encode(array("a" => $row['uitgevoerd_door_naam'], "b" => $row['hoev_gev_stof_score']));
}
}
mysqli_close($mysqli);
?>

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