Trying to remove value from a JSON file - php

I'm trying to remove value from a json file with AJAX request, it don't show any error but it don't delete the value, someone can check it? Thanks you!
Before the AJAX function (for insert the ID on the "erase"). (the function deletee(item) click the button that activate the dlt function)
JS:
function deletee(item) {
var el = document.getElementById('erase');
el.value = Checker[item].id;
var r= confirm("Do you want delete it?")
if (r==true) {
document.getElementById('rmv').click()
}
}
JS AJAX:
function dlt(item) {
var iddlt = document.getElementById('erase').value;
$.ajax({
type: 'GET',
url: 'api/delete/'+ iddlt,
dataType: 'json'
});
}
php:
$app->get('/delete/{id}', function (array $args) {
$jsonContents = file_get_contents('data/data.json');
$id = $args['id'];
$data_array = json_decode($jsonContents, true);
foreach ($data_array as $key => $value) {
if ($value['id'] == $id) {
unset($data_array[$key]);
}
}
$data_array = array_values($data_array);
file_put_contents('data/data.json', json_encode($data_array));
});

Pass ID to your function and Ajax URL :
function dlt(item_id) {
$.ajax({
type: 'GET',
url: 'api/delete' + item_id,
dataType: 'json'
});
}

Add id in your URL to make your API work.
function dlt() {
var id= "it should be a valid id";
$.ajax({
type: 'GET',
url: 'api/delete/'+ id,
dataType: 'json'
});
}

Related

jQuery use ajax and json to switch page with button

Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }

Passing URL params with Jquery into php

I'v been trying for last 2 hours to pass parameters from my jquery to PHP.
I cannot seem to figure this out.
So my code goes following
var something = getUrlParameter('month');
function Refresh()
{
$.ajax({
type: 'POST',
url: 'getCalendar.php',
data: {test:something},
success: function(data){
if(data != null) $("#calendarDiv").html(data)
}
});
}
getUrlParameter is
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
I just cant seem to be able to pass anything to my php file.
Thanks.
My goal is to pass ?month=something&year=something into PHP file, so I can based on that display calendar.
Url of example:
http://chanceity.com/calendartest.html
But it doesn't work because my php file is not getting those params.
$.ajax({
type: 'POST',
url: 'getCalendar.php',
cache: false,
dataType:'json',
data: "data=" + {test:something},
success: function(data)
{
$("#calendarDiv").html(data)
},
error:function()
{
$("#calendarDiv").html('Could not get results')
}
});
and next go to your php file get the results and echo the variable back thats it
$value = htmlentities($_GET['data']);
if(!empty($value))
{
$results = 'action you want to do ';
}
else
{
$results = '';
}
echo json_encode($results);
You can also do it with just javascript
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}

Get a single row from the database using AJAX in CodeIgniter?

I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
Here is my view:
<?php echo $faq_title; ?>
Here is my controller:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Try this:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().
The way I see it, you aren't using the anchor tag for its intended purpose, so perhaps just use a <p> tag or something. Ideally, you should use an id integer instead of a title to identify a row in your database.
View:
<p class="faq_title"><?php echo $faq_title; ?></p>
If you had an id integer, you could use a $_GET request an receive the id as the lone parameter of the get_faq_data() method.
Controller:
public function faqByTitle(): void
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$title = $this->input->post('title');
if ($title === null) {
show_404();
}
$this->load->model('model_faq', 'FAQModel');
echo json_encode($this->FAQModel->getOne($title));
}
FAQ Model:
public function getOne(string $title): ?object
{
return $this->db->get_where('faq', ['faq_title' => $title])->row();
}
JavaScript:
$(".faq_title").click(function() {
let title = $(this).text();
$.ajax({
url: 'faq/faqByTitle',
data: {title:title},
dataType: 'json',
type: 'post',
success: function(response) {
console.log(response);
}
});
});
None of these snippets have been tested.

Simple ajax function in cakephp 2.x not working

I am new to cakephp and trying to implement AJAX . I have a view add.ctp in which I have written the following lines :
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_names_by_catagory/";
$.ajax({
type: "GET",
url: url_to_call,
data = data,
//dataType: "json",
success: function(msg){
alert(msg);
}
});
}
});
And the function get_office_names_by_catagory() within OfficenamesController.php is:
public function get_office_name_by_catagory($type = '') {
Configure::write("debug",0);
if(isset($_GET['type']) && trim($_GET['type']) != ''){
$type = $_GET['type'];
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
return 'Hello !';
}
But unfortunately, its not alerting anything ! Whats wrong ?
Could be caused by two issues:
1) In your js snippet, you are querying
http://localhost/testpage/officenames/get_office_names_by_catagory/.
Note the plural 'names' in get_office_names_by_category. In the PHP snippet, you've defined an action get_office_name_by_catagory. Note the singular 'name'.
2) You may need to set your headers appropriately so the full page doesn't render on an AJAX request: Refer to this link.
I think, you have specified data in wrong format:
$.ajax({
type: "GET",
url: url_to_call,
data = data, // i guess, here is the problem
//dataType: "json",
success: function(msg){
alert(msg);
}
});
To
$.ajax({
type: "GET",
url: url_to_call,
data: { name: "John", location: "Boston" }, //example
success: function(msg){
alert(msg);
}
});
You should specify the data in key:value format.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_name_by_catagory/"+office_id;
$.ajax({
type: "GET",
url: url_to_call,
success: function(msg){
alert(msg);
}
});
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
exit;
}
See what I have done is I have changed your request to function get_office_name_by_catagory, as there is one paramenter $type is already defined in the function, so if I have the request by /get_office_name_by_catagory/2 then you will find value in $type in action.
So no need to use $_GET and rest everything is fine!
Try this,
remove type from ajax and try.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = yourlink +office_id;
**$.ajax({
url: url_to_call,
success: function(msg){
alert(msg);
}
});**
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
}

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

Categories