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
});
},
Related
I have below code which is reloading new records if inserted.
On page load it works fine But after reloading div when get new data, it is keep reloading again and again and also not including a file which is included in order_new_orders.php.
I want only reload the div if new record inserted and then keep close.
order_new_orders.php
**EXAMPLE:**
$sqla = "select order_id from orders where status = 0
and store_id = '".$_SESSION['ses_user_idx']."'";
$sqlb = $dba2->query($sqla);
while ($sqlc = $sqlb->fetch_assoc()){
include ('inc/afile.php');
echo $sqlc['name'];
}
Code:
var currentNewOrders = "";
function auto_loadNewOrders(){
$.ajax({
type: 'POST',
url: 'order_new_orders.php',
success: function(data){
if(currentNewOrders !== data) {
$("#newOrderRefresh").html(data);
currentNewOrders = data;
}
}
});
}
auto_loadNewOrders();
setInterval(auto_loadNewOrders,1000);
PHP
order_new_orders.php
<?php
//Dummy Data
$datas = array(
array('id' => 1, 'name' => 'Dummy Name1', 'age' => 25),
array('id' => 2, 'name' => 'Dummy Name2', 'age' => 28),
array('id' => 3, 'name' => 'Dummy Name2', 'age' => 28),
);
if (isset($_GET['checkNew']) && isset($_GET['lastDataID'])) {
if (count($datas) > $_GET['lastDataID']) {
echo 1;
} else {
echo 'No new Data';
}
exit;
}
//Data Output structure
$htm = "<table border='1'>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
";
foreach ($datas as $row) {
$htm.="<tr class='data-row' data-row-id='$row[id]'>
<td>$row[name]</td>
<td>$row[age]</td>
</tr>";
}
$htm.="</table>";
echo $htm;
exit;
HTML & jQuery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="newOrderRefresh"></div>
<script>
$(document).ready(function() {
auto_loadNewOrders();
setInterval(checkForNew, 1000);
});
function auto_loadNewOrders() {
$.ajax({
type: 'POST',
url: 'order_new_orders.php',
success: function(data) {
$("#newOrderRefresh").html(data);
}
});
}
function checkForNew() {
var lastData = $('.data-row').last().attr('data-row-id');
$.ajax({
type: 'POST',
url: 'order_new_orders.php?checkNew&lastDataID=' + lastData,
success: function(data) {
if (data == 1) {
auto_loadNewOrders();
}
}
});
}
</script>
I am building a blog application. I have a search box which will suggest the categories as user types. So I use jquery-ui autocomplete. But not sure why its not working. I am new to it and spend a whole day. please help. Here is my code.
Model:
public function getCategoriesJson ($keyword) {
$this->db->select('cat_name');
$this->db->from('categories');
$this->db->like('cat_name', $keyword);
$data = $this->db->get()->result_array();
$output = array();
if ($data) {
foreach ($data as $d) {
array_push($output, $d['cat_name']);
}
}
echo json_encode($output);
}
view:
Controller:
public function getCatJson () {
$this->Category_model->getCategoriesJson($this->input->get('query'));
}
Script:
$('#search').autocomplete({
source: '<?php echo base_url(); ?>categories/getCatJson?query=' + $('#search').val(),
minLength: 1
});
Finally, I have got a solution. I changed my model function code and my script like below and it works.
Model:
public function getCategoriesJson($keyword)
{
$this->db->select('cat_name');
$this->db->from('categories');
$this->db->like('cat_name', $keyword);
$data = $this->db->get()->result_array();
$output = array();
if($data)
{
foreach($data as $d)
{
array_push($output, ['label' => $d['cat_name']]);
}
}
echo json_encode($output);
}
Script:
$("#search").autocomplete({
source: function (request, response) {
$.ajax({
url: '<?php echo base_url(); ?>categories/getCatJson',
type:'GET',
dataType: "json",
data: {
query: request.term
},
success: function (data) {
response(data);
},
error: function (message) {
response([{'label': 'Not found!'}]);
}
});
},
minLength: 2
});
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>
I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.
For some reason, nothing happens when I click the save button.. not even in the console.
It's just using jQuery at the moment, will I have to use AJAX for this?
If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.
Here is my code:
index.php
<div class="caption" id="caption1" contenteditable="true" style="min-height: 450px;">
<?php
$query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
$show = mysql_query($query3, $con);
while ($row = mysql_fetch_array($show))
{
echo $row['file'];
}
?>
</div>
<button type="button" id="save"><span>Save</span></button>
<script>
$(document).ready(function (e) {
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
var options = {
url: "save.php",
type: "post",
data: { "editor" : encodeUriComponent(data) },
success: function (e) {
echo "Succesfully updated!";
}
};
}
});
</script>
</div>
save.php
<?php
$connection = mysql_connect("localhost", "", "");
$db = mysql_select_db("castle", $connection);
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>
You need to send the data to the server like this;
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
//Success
},
type: 'POST'
});
Currently you are just creating an object called 'options'
Your code should look like this;
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
alert('Success');
},
type: 'POST'
});
}
Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'
I'm trying to delete an element from a JSON array. The action starts when the user click in a delete button. I can't figure out what's wrong. Maybe it's something on the PHP script.
javascript.js
$(".delete").on('click', function(e){
var deleteItem = e.target.id;
console.log(deleteItem);
$(this).closest('div').css({"text-decoration": "line-through", "color": "#e74c3c"}).fadeOut(600);
$.ajax({
url: 'deletejson.php',
method: 'POST',
dataType: 'json',
data: { target: e.target.id},
success: function(){
console.log('Item was deleted');
console.log(data);
}
});
data.json
{ "prescriptions":[
{
"name":"Edogen",
"unit":"drops",
"dosage":"2 drops",
"doc_name":"Dr. Wu",
"apperance":"black",
"days":"Monday",
"frequency":"twice",
"hour":"1pm"
},
{
"name":"Lexapro",
"unit":"drops",
"dosage":"2 drops",
"doc_name":"Dr. Wu",
"apperance":"black",
"days":"Sunday",
"frequency":"twice",
"hour":"1pm"
},
{
"name":"Plavix",
"unit":"drops",
"dosage":"4 drops",
"doc_name":"Dr. Ammy Lee",
"apperance":"blue",
"days":"Monday",
"frequency":"twice",
"hour":"10pm"
}
]}
deletejson.php
<?php
$var = $_POST["target"];
$file = "json/data.json";
$json_array = json_decode(file_get_contents($file), true);
function removeNode($var, $json_array) {
foreach($json_array["prescriptions"] as $key => $value) {
if($value === $var)
unset($json_array["prescriptions"][$key]);
}
$json = json_encode($json);
file_put_contents($file, $json);
}
?>
Try replacing your foreach loop with the following:
foreach($json_array["prescriptions"] as $values) {
foreach($values as $key => $value) {
if($value === $var){
unset($json_array["prescriptions"][$key]);
}
}
}