JS AJAX POST to PHP, edit JSON file is giving errors - php

post function in js:
var srcd = document.getElementById("pictwo").src;
$.ajax({
type: "POST", //type of method
url: "/file.php", //your page
data: {
src: srcd
}, // passing the values
success: function(res) {
location.reload(); //do what you want here...
}
});
}
file.php:
<?php
header('Access-Control-Allow-Origin: *');
$src = $_POST["src"];
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode( $jsonString, true );
foreach ( $data as $key => $entry )
{
if ( $entry['src'] == $src )
{
$data[$key]['counter']++;
}
}
$newJsonString = json_encode( $data );
file_put_contents( 'jsonFile.json', $newJsonString );
?>
I know that the POST is successful, because I added a console.log(srcd) to the js function, and it was the desired value.
jsonFile.json:
[
{
"src": "https://",
"counter": "0"
},
{
"src": "https://",
"counter": "0"
},
{
"src": "https://",
"counter": "0"
},
The error in error_logs is :
PHP Warning: Invalid argument supplied for foreach() in /file.php on line 8
After the function is called, the json file is changed to null.
Why is this happening?
How can I fix this?
Thank you.

Related

Insert JSON into Mysql problem (ajax/php)

I have a Json that I build after dropping a tab separated text into a text area (from this codepen example):
[
{
"0": "2019-08-31",
"1": "Bank Exp.",
"2": "EUR"
},
{
"0": "2019-08-31",
"1": "Legal",
"2": "EUR"
},
{
"0": "2019-08-31",
"1": "Legal",
"2": "EUR"
}
]
and is stored in variable:
jsonString = JSON.stringify(data, null, 2);
I then pass this json via ajax to a php file
var options = {
type: "POST",
url: "test.php",
data: { test: jsonString },
dataType: 'json',
success: function( data, status, xhr ) {
alert ("php:"+data);
},
error: function( xhr, status, error ) {
alert (data);
}
};
$.ajax( options );
to process a simple MYSQL insert of the different rows in the columns 0, 1, 2 in my 'test.php' file:
<?php
$host="localhost";
$user="renaud";
$pass="Mod100572$";
$db="accounting";
$con= new mysqli($host,$user,$pass,$db) or die("ERROR:could not connect to the database!!!");
$test = utf8_encode($_POST['test']);
$data_array = json_decode($test);
foreach($data_array as $row) {
$query .= "INSERT INTO `test` set
`field1` = '".$row['0']."',
`field2` = '".$row['1']."',
`field3` = '".$row["2"]."';";
}
if(mysqli_multi_query($con, $query)) {
$msg = "success";
} else {
$msg = "Something wrong! Please try again.";
}
mysqli_close($con);
?>
I Apparently do not achieve to convert my '$_POST['test']' into a correct array and the loop only gets '[' values. It is considered as a string, not an array.
I tried other parameters such as $data_array = json_decode($test,true); with no luck.
Any help to understand my error is deeply appreciated...
Insert syntax error
$query .= "INSERT INTOtestVALUES (
field1= '".$row['0']."',
field2= '".$row['1']."',
field3= '".$row["2"]."');";

sorting,paging,ordering,searching json data response from API server using datatable in codeigniter

i was trying to use paging,sorting,ordering and searching in datatable but i still dont get right reference when data get from json response API. how can sorting,paging,ordering,searching in datatable read json data in API if its not query? im new to this kind of json data from API things. i hope someone can tell me the right things to do it in codeigniter and reference too. thanks!
this is what im doing so far. i already get json data from api to table view but when i use paging etc its just run same process because i know there is no condition for paging etc to process json data. thanks for advice!
this is my function in model for get json data from API
function get_filter_order_report($idseri,$idstatus,$orderdate,$nohal,$halaman)
{
$APIId = '*******';
$APIKey = '*******';
$url = '*******';
$RequestUrl = urlencode($url);
$RequestUrl = strtolower($RequestUrl);
$requestHttpMethod = 'get';
$requestHttpMethod = strtoupper($requestHttpMethod);
$RequestBodyBase64 = base64_encode(md5('""',true));
$RequestTimeStamp = time();
$Nonce = bin2hex(openssl_random_pseudo_bytes(10));
$SignatureRawData = $APIId.''.$requestHttpMethod.''.$RequestUrl.''.$RequestTimeStamp.''.$Nonce.''.$RequestBodyBase64;
$SignatureBase64 = base64_encode(hash_hmac('sha256', $SignatureRawData, $APIKey, 'true'));
$dataSignature = $APIId.':'.$SignatureBase64.':'.$Nonce.':'.$RequestTimeStamp;
$AuthString = base64_encode($dataSignature);
$data = new stdClass;
$proxy = '********';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization : amx '.$AuthString)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$result = curl_exec($ch);
curl_close($ch);
$var = json_decode($result);
echo json_encode($var->Records);
}
and my controller now just get data there is no condition for datatable server side paging,sorting,searching and ordering
function show_order_report()
{
if($_POST){
$arr = array('IdSeri' => $this->input->post('seriid'),
'Status' => $this->input->post('statid'),
'TglPemesanan' => $this->input->post('orderdate')
);
$halaman = 10;
$nohal = 1;
$idseri = $arr['IdSeri'];
$idstatus = $arr['Status'];
$orderdate = $arr['TglPemesanan'];
echo $this->Pemesanan_model->get_filter_order_report($idseri,$idstatus,$orderdate,$nohal,$halaman);
}else{
echo '<script type="text/javascript">parent.content.location = "'.base_url().'default"</script>';
}
}
and this is my datatable ajax serverside script in view
function filterOrder(){
var token = document.getElementById('token').value;
$(document).ready(function() {
$("div#form-wrap").show();
var postData = {
<?= $this->security->get_csrf_token_name() ?> : token,
seriid: $('#seriid').val(),
statid: $('#statid').val(),
orderdate: $('#orderdate').val()
};
var code = {<?= $this->security->get_csrf_token_name() ?> : token,};
var tglorder = formatDate('TglPemesanan');
var table = $('#orders').DataTable({
"responsive" : true,
"processing" : true,
"serverSide" : true,
"destroy": true,
"paging": true,
"searching": true,
"ajax" : {
url : "<?=base_url();?>SBNReport.jsp/show_order_report",
type: "post",
data: postData,
dataSrc: ''
},
"columns": [
{ "data": "NamaInvestor" },
{ "data": "KodePemesanan" },
{ "data": "Seri" },
{ "data": "Sid" },
{ "data": "KodeBilling" },
{ "data": "Nominal" },
{ "data": "Status" },
{ "data": "TglPemesanan" },
{ "data": "NTPN" },
{
sortable: false,
"render": function ( data, type, full, meta ) {
var buttonID = full.KodePemesanan;
return '<a class="btn btn-sm btn-primary btn-sm" href="javascript:getTransaction(\''+buttonID+'\')">Detail</a>';
}
},
],
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 9 ], //last column
"orderable": false, //set not orderable
"searchable" : false,
},
{
"targets" : 7,
render : function(data){
//Here you should call the date format function:
return formatDate(data);
}
}
],
"language": {
"lengthMenu": "<?= $this->lang->line('dt_show') ?> _MENU_ <?= $this->lang->line('dt_record') ?> <?= $this->lang->line('dt_per_page') ?>",
"zeroRecords": "<?= $this->lang->line('dt_empty') ?>",
"info": "<?= $this->lang->line('dt_show') ?> <?= $this->lang->line('dt_page') ?> _PAGE_ <?= $this->lang->line('dt_of') ?> _PAGES_ <?= $this->lang->line('dt_page') ?>",
"infoEmpty": "<?= $this->lang->line('dt_empty') ?>",
"infoFiltered": "<?= $this->lang->line('dt_filtered') ?> <?= $this->lang->line('dt_of') ?> _MAX_ <?= $this->lang->line('dt_record') ?>)",
"search": "<?= $this->lang->line('dt_search') ?>",
"processing": "<?= $this->lang->line('dt_processsing') ?>",
},
"initComplete": function( oSettings ) {
parent.setIframeHeight('content');
},
"drawCallback": function( oSettings ) {
parent.setIframeHeight('content');
},
});
});
}
Genaraly, datatables send a number of parameters to a source (i.e. your Ajax url) in a request (You can also check in the network tab by Crtl+Shift+i).
I dont know about JSP which is your server script but
Check this for PHP server side code.
First print all the values in the request.
Look from line no. 31, which is for paging.Datatable and automatically send the limit value for the query when you click next/prev/any page number of the pagination.
I made changes to it for multiple tables, different columns, and extra conditions by passing extra parameters in the request.
Hope you get the idea.

how to add row as html to BootStrap Plugin DataTable?

Is there a way to add row as html to datatable? I understand that the suggested way of doing it is this:
$('#addRow').on( 'click', function () {
t.row.add( [
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
] ).draw( false );
counter++;
} );
But I have a complex JSON input and I want to pre process it in PHP. Is it doable or even possible?
EDIT:
So instead of doing the code above:
t.row.add(resultfromphpserverwithalltherows);
UPDATE:
JSON output
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
and sometimes:
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed","othersubjects":[{"applied math":"90","general science":96,"world history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
So I can't really define the columns because the JSON output is dynamic and that's why I want to preprocess it in PHP first.
No matter how you approach this, there's going to be some significant data-formatting required.
Best approach for what you're asking: use DataTables server-side tools.
It requires including some additional components, but will simplify the javascript down to:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
...with a little tweaking, you can simplify that further:
$(function(){
var dt = new dataTableAuto();
dt.load();
});
function dataTableAuto() {
this.params = {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
};
this.load = function() {
$('#example').DataTable( this.params );
}
}
php ajax server to send raw JSON as a single row
Simply send an ajax request to php which includes the counter, then respond with a json array matching what you want to build.
Javascript snippet
counter = 0;
$.ajax({
url: '[your url]',
type: 'post',
data: {"counter":counter},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.row.add(JSON.parse(response)).draw( false );
counter++;
},
});
php Snippet
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$counter = $data['counter'];
$totalRows = 10;
for( $i = 0; $i < $totalRows; $i++) {
$result[] = $counter .".". $i;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
DataTables pure AJAX approach
javascript
$(function(){
t = $('#example');
$.ajax({
url: '[your url]',
type: 'post',
data: {"classID":12},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.DataTable( JSON.parse(response) );
},
});
});
php
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$classID = intval($data['classID']);
$cols = array('Name', 'Position', 'Score');
foreach ( $cols as $colName ) {
$entry = new stdClass();
$entry->title = $colName;
$result['columns'][] = $entry;
}
$result = // some query [ex: get rows by class id]
foreach( $result as $row) {
$thisRow = array();
foreach ( $cols as $colName ) {
$thisRow[] = $row['$colName']
}
$result['data'][] = $thisRow;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
This should produce an object similar to:
{
data: [
['Joseph Taylor', '22', '90']
],
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Score" }
]
}

Send data with AJAX and receive in PHP

I'm having a script which is generating a JSON array, based values user have selected. These values are sent as a JSON with AJAX to a PHP script which should receive this values and process it.
What could be wrong?
JSON (That is sent):
[{
"Pages":
{"name":" Page Name 1",
"id":"252456436636644"}
},
{
"Pages":{
"name":" Page Name 2",
"id":"345345435435232"
}
}]
Jquery:
var json_pages = JSON.stringify(publish);
$.ajax({
url: "post.php",
type: "post",
data: { PublishToPages: json_pages },
success: function(){},
error: function(){}
});
Problem is that the JSON I recieve from PHP isn't getting the data,
if($_POST['PublishToPages']) {
$json = $_POST['PublishToPages'];
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
echo $page_id;
}
}
If I manually put in the JSON in the PHP script like this it Works,
if ($_POST['PublishToPages']) {
$json = '[{"Pages":{"name":" Page Name","id":"234545355345435"}},{"Pages":{"name":" Page Name 2","id":"345345435435435435"}}]';
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
echo $page_id;
}
}
Try using this:
if($_POST['PublishToPages']) {
$json = $_POST['PublishToPages'];
$items = array();
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
$items[] = $page_id;
}
echo json_encode($items);
}
Try this
$.ajax({
url: "post.php",
type: "post",
dataType:"json",
data: { PublishToPages: json_pages },
success: function(){},
error: function(){}
});
Thanks for all input! I figured it out using the var_dump and realized it was encoding error so added stripslashes(); and it worked! :)
if ($_POST['PublishToPages']) {
$json = stripslashes($_POST['PublishToPages']);
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
echo $page_id;
}
}

Issue with CodeIgniter Login form with Jquery

I am working with CodeIgniter and am trying to capture the JSON values that are returned from a controller using jquery $.ajax() function.
Here is my "login/process" Controller below
public function process() {
$this->form_validation->set_rules('email','Email Address','trim|required|xss_clean');
$this->form_validation->set_rules('passwd','Password','trim|required|xss_clean|md5|callback_check_database');
$red = ($this->input->post('redirect_url')) ? $this->input->post('redirect_url') : null;
if ($this->form_validation->run() == false) {
$output = '{ "success": "no", "redirct": "' . $red . '", "err" : "' .validation_errors() . '" }' ;
} else {
//Go to private area
$output = '{ "success": "yes", "redirct": "account" , "err" : ""}';
}
}
header('Content-Type: application/json', true);
echo json_encode($output);
}
}
Here is part of my view below:
<script type='text/javascript' language='javascript'>
$(document).ready(function() {
$("#LoginForm").on("submit",function() {
var datastring = 'email='+$("#email").val()+'&passwd='+$("#passwd").val()+'&redirect_url='+$("#redirect_url").val();
$.ajax({
type: "POST",
url: "<?= base_url("login/process") ?>",
dataType: "json",
data: datastring,
cache: false,
success: function(output) {
// alert(output.success);
if (output.success == 'yes') {
document.location.href=output.redirct
}
if (output.success == 'no') {
alert(output.err)
}
}
})
return false; // To prevent form submission
})
});
</script>
When I tried to debug with FireBug, below is what I got as the POST Response
"{ \"success\": \"no\", \"redirct\": \"messaging.php\", \"err\" : \"<p>The Password field is required.<\/p>\n\" }"
You can't use json_encode on a json string. It's for encoding arrays as a json string
. I would suggest you to define $output as an array and then use json_encode (it's also less error-prone):
$output = array("success" => "no", "redirect" => $red, "err" => validation_errors());
echo json_encode($output);

Categories