Reloading div only if database has new records - javascript

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>

Related

initialization Materialize-autocomplete dataset using api call with ajax and jquery

Good morning all,
I am using materialize.css in a PHP app
I will want to initialize the auto-complete data with an API call.
The .autocomplete () initializes the data with a JSON array " data ":,
which I get with the .ajax ({..., url: '/search.php', ... datas}).
but I can't inject the datas into the.autocomplete (),
how can I do it?
Here is the source code:
<body>
<form action="">
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix">title</i>
<input id="searchOnAPI" name="name" type="text" class="autocomplete" value="{{ item.name }} ">
<label for="searchOnAPI">{{ siteData('admin.titre') }}</label>
<ul id="autocomplete-content" class="autocomplete-content"><li><a></a></li></ul>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
<script>
$(document).ready(function () {
$('#searchOnAPI').keyup(function () {
$('#autocomplete-content').html('');
let search = $(this).val();
if (search !== "") {
$.ajax({
type: 'GET',
url: '/search.php',
data: 'search=' + encodeURIComponent(search),
success: function (datas) {
if (datas !== "") {
$('#searchOnAPI').autocomplete(datas);
} else {
document.getElementById('autocomplete-content').innerHTML = '<ul class="autocomplete-content dropdown-content"><li><a class="black-text">{{ siteData('site.search.nodata') }}</a></li></ul>';
}
}
});
}
});
});
</script>
I think the problem comes from here:
The variable datas ...
but I don't understand the error anymore.
success: function (datas) {
if (datas !== "") {
$('#searchOnAPI').autocomplete(datas);
}
the code of the search page:
and call API
<?php
if (isset($_GET['search']) && !empty($_GET['search'])) {
$search = trim(htmlspecialchars($_GET['search']));
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.themoviedb.org/3/search/multi?api_key=". API_KEY ."&language=fr-FR&query=$search",
CURLOPT_CAINFO => dirname(__DIR__) . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR ."cert.tmdb.cer", //api.themoviedb.org
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
]);
$response = curl_exec($curl);
$err = curl_error($curl);
$response = json_decode($response, true);
$err = json_decode($err, true);
$datas = [];
if (!is_null($err) || $response === null || !isset($response['results'])) {
$datas[] = ['No Data' => null];
} else {
$response = $response['results'];
for ($i = 0; $i <= 5; $i++) {
if (isset($response[$i]['title'])) {
$datas[] = $response[$i]['title'] ;
} elseif (isset($response[$i]['name'])) {
$datas[] = $response[$i]['name'];
}
}
echo json_encode(array_fill_keys(['data'], array_fill_keys($datas, null)), true);
}
}
and here is the api return in json of the search page
{
"data": {
"O Amor Acontece": null,
"Quem Quer Namorar Com o Agricultor?": null,
"O'": null,
"O Clone": null,
"Hawaï police d'État": null,
"O Matador": null
}
}
Any advice is welcome!
.EDD
Your PHP code is returning a json object with a 'data' parameter, maybe you could try
if (datas !== "") {
$('#searchOnAPI').autocomplete(datas.data);
}
I found the error:
$.ajax({
type: 'GET',
url: '/search.php',
data: 'search=' + encodeURIComponent(search),
success: function (datas) {
I did not set the dataType ...
dataType:"json",
like this
$.ajax({
type: 'GET',
dataType:"json",
url: '/search.php',
data: 'search=' + encodeURIComponent(search),
success: function (datas) {
But with everything works.
find on [Jquery autocomplete _renderItem is not working][1]

How to update image with AJAX in Laravel

I'm having problems updating a record with an image. I don't what I need to do. My image is stored in a public folder called 'img/products'
ProductController.php
This is my controller. It works well without modifying the image.
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price_neto' => 'required',
'iva' => 'required',
'price_total' => 'required',
'image' => '',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$products = Product::find($id);
$products->name = $request->input('name');
$products->category_id = $request->input('category_id');
$products->description = $request->input('description');
$products->price_neto = $request->input('price_neto');
$products->iva = $request->input('iva');
$products->price_total = $request->input('price_total');
$products->image = $request->input('image');
$products->save();
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
Product.js
All I know is that I have to use var formData = new FormData ($ ("# frmAddProduct") [0]); as in the store function. I can enter records with images but not edit them. My image is stored in a public folder called 'img/products'
$(document).ready(function() {
$("#btn-edit").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'PUT',
url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
data: {
name: $("#frmEditProduct input[name=name]").val(),
category_id: $("#frmEditProduct select[name=category_id]").val(),
description: $("#frmEditProduct input[name=description]").val(),
price_neto: $("#frmEditProduct input[name=price_neto2]").val(),
iva: $("#frmEditProduct input[name=iva2]").val(),
price_total: $("#frmEditProduct input[name=price_total2]").val(),
image: $("#frmEditProduct input[name=image]").val(),
},
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
});
function editProductForm(product_id) {
$.ajax({
type: 'GET',
url: '/product/' + product_id,
success: function(data) {
$("#edit-error-bag").hide();
$("#frmEditProduct input[name=name]").val(data.products.name);
$("#frmEditProduct select[name=category_id]").val(data.products.category_id);
$("#frmEditProduct input[name=description]").val(data.products.description);
$("#frmEditProduct input[name=price_neto2]").val(data.products.price_neto);
$("#frmEditProduct input[name=iva2]").val(data.products.iva);
$("#frmEditProduct input[name=price_total2]").val(data.products.price_total);
$("#frmEditProduct file[name=image]").val(data.products.image);
$("#frmEditProduct input[name=product_id]").val(data.products.id);
$('#editProductModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
You should check if the file exists before trying to delete, for example:
$product = Product::find($id);
if(!$product)
{
return response()->json(['error' => 'Product not found'], 404);
}
if (Storage::disk('local')->exists('img/products/'.$product->image)) {
Storage::disk('local')->delete('img/products/'.$product->image);
}
Take a look one example only:
public function update(UpdateProductFormRequest $request, $id)
{
$product = Product::find($id);
$data = $request->only('name','category_id','description',
'price_neto','iva','price_total');
if(!$product)
{
return response()->json(['error' => 'Product not found'], 404);
}
// when saving the file, delete the old file first
if ($request->hasFile('image')) {
$file = $request->file('image');
$original_filename = $file->getClientOriginalName();
// $mime = $file->getMimeType(); // Suggestion
$extention = $file->getExtension();
// $size = $file->getClientSize(); // Suggestion
$stored_filename = $original_filename; // md5($original_filename); // Suggestion
$file_path = storage_path('public/img/products/');
if (Storage::disk('local')
->exists("public/img/products/{$stored_filename}.{$extention}"))
{
Storage::disk('local')
->delete("public/img/products/{$recordSet->stored_filename}.{$extention}");
}
$file_moved = $file->move($file_path, "{$stored_filename}.{$extention}");
$data->image = "{$stored_filename}.{$extention}";
}
// Updating data
$result = $product->update($data);
if ($result) {
/* return redirect()
->route('products.index')
->withSuccess('Product was successfully updated'); */
return response()->json([
'message' => 'Product was successfully updated'
'product' => $product
]); // You don't have to put 200 because it's the default
}
/* return back()
->withErrors(['Unable to update the product'])
->withInput($request->input()); */
return response()->json(['error' => 'Unable to update the product'], 400);
}
It would be better if you create a form request to do your validations.
Don't forget to create links to the storage path:
php artisan storage:link
I think it would be helpful:
$("#btn-edit").click(function() {
var formData = new FormData($("#frmAddProduct")[0]);
formData.append('_method', 'put');
formData.append('_token', "{{ csrf_token() }}"); // if you are using Blade
var route= "{{ route('products.update', ['id' => ':id']) }}"; // if you are using Blade
route= route.replace(':id', $("#frmEditProduct input[name=product_id]").val())
$.ajax({
method: 'post',
url: route,
data: formData,
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
Is your js script in "Blade" ? If so, try it this way:
var image = '{{ asset("/img/products/_image_file") }}'
image.replace('_image_file', data.products.image)
$("#frmEditProduct file[name=image]").val(image)
Note that we can first use the "asset ()" helper to create the full path to use to find the image, but with a "_image_file" placeholder
After that, we use the replace () function to change the "_image_file" placeholder with the actual image file brought from the ajax response.
Something like this?
ProductController.php
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price_neto' => 'required',
'iva' => 'required',
'price_total' => 'required',
'image' => '',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$products = Product::find($id);
if ($request->hasFile('image')) {
$productImage = $request->file('image');
$productImageName = rand() . '.' . $productImage->getClientOriginalExtension();
if (Storage::disk('local')->exists("img/products/{$productImageName}")) {
Storage::disk('local')->delete("img/products/{$recordSet->$productImageName}");
}
$file_moved = $productImage->move(public_path('img/products'), $productImageName);
$data->image = "{$productImageName}";
}
$products->save([
'name' => $request->name,
'category_id' => $request->category_id,
'description' => $request->description,
'price_neto' => $request->price_neto,
'iva' => $request->iva,
'price_total' => $request->price_total,
'image' => $productImageName,
]);
return response()->json([
'error' => false,
'products' => $products,
]);
}
Product.js
$("#btn-edit").click(function() {
var formData = new FormData($("#frmEditProduct")[0]);
formData.append('_method', 'put');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
data: formData,
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});

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

Yii2 Ajax request in yii2

By using kartik select2 plugins in Yii2, I try to make dependence dropdown for country and states.
Form field for country and states:
$url = yii\helpers\Url::toRoute('op-client/lists');
$this->registerJs($this->render('script.js'), \yii\web\VIEW::POS_READY);
$form->field($model, 'country_id')->widget(Select2::classname(), [
'data' => $countryData,
'language' => 'en',
'options' => ['placeholder' => 'Select'],
'pluginOptions' => [
'allowClear' => true,
],
'pluginEvents' =>
[
'change' => 'function()
{
getstate
(
$("#select2-opclient-country_id-container").val(),
"'.$url.'"
)
}',
],
]).'
$form->field($model, 'states_id')->widget(Select2::classname(), [
'data' => $statesData,
'language' => 'en',
'options' => ['placeholder' => 'Select'],
'pluginOptions' => [
'allowClear' => true,
],
]).'
Script.js
function getstate($countryid,url)
{
//console.log(startdate + enddate);
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
type:"POST",
cache:false,
url:url,
data:{countryid:countryid, _crsf:csrfToken},
success:function(data){
$("#select2-opclient-states_id-container").val(data);
},
})
}
Controller:
public function actionLists()
{
$request = Yii::$app->request;
$country = $request->post('countryid');
$countStates = OpStates::find()
->where(['country_id' => $country])
->count();
$states = OpStates::find()
->where(['country_id' =>$country])
->all();
if($countStates > 0)
{
foreach($states as $state){
echo "<option value='".$state->id."'>".$state->state_name."</option>";
}
}
else
{
echo "<option></option>";
}
}
When I run the program, it show error "Uncaught ReferenceError: countryid is not defined".
But I thought i passed the countryid into it already? Where have I done wrong?
Any help/advice will be appreciated. Thankss
Please check below code,i think you did little mistake in country_id variable name.
public function actionLists()
{
$request = Yii::$app->request;
$country = $request->post('country_id');
$countStates = OpStates::find()
->where(['country_id' => $country])
->count();
$states = OpStates::find()
->where(['country_id' =>$country])
->all();
if($countStates > 0)
{
foreach($states as $state){
echo "<option value='".$state->id."'>".$state->state_name."</option>";
}
}
else
{
echo "<option></option>";
}
}
and here
function getstate(countryid,url)
{
//console.log(startdate + enddate);
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
type:"POST",
cache:false,
url:url,
data:{countryid:countryid, _crsf:csrfToken},
success:function(data){
$("#select2-opclient-states_id-container").val(data);
},
})
}
It will solve your issue.

Delete element from JSON array

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

Categories

Resources