Invalid JSON Response in Datatable Codeigniter - php

I need an expert to fix this . This is my controller that load JSON .
foreach ($result->result() as $row){
$customer = $row->customer_name;
$ipull = $row->ip;
if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true){
$PING = $this->routerosapi->comm("/ping", array(
"address" => $ipull,
"count" => "2"
));
if( $PING['0']['packet-loss'] == 0){
$status = "Online";
} else {
$status = "Offline";
}
} else {
$this->session->set_flashdata('Connect_False','Failed To get');
redirect('tmikrotik/router_list');
}
$data = array(
'customer' => $customer,
'address' => $ipull,
'status' => $status
);
print json_encode($data);
}
And this is JSON response:
{"customer":"Trakindo Utama","address":"192.168.1.3","status":"Online"}{"customer":"Adira Finance","address":"192.168.1.10","status":"Offline"}{"customer":"Mandala Finance","address":"192.168.1.50","status":"Online"}
The problem is, when I load it into my data table, show popup invalid JSON response. This is my jQuery code
$(function () {
var table = $("#cpe-status").DataTable({
fixedColumns: true,
fixedHeader: true,
"pageLength": 10,
"paging": true,
"ajax": {
url: "./cpe",
type: "GET",
dataSrc: ""
},
"scrollX": true,
"aoColumns": [
{"data": "customer", "title": "Host"},
{"data": "address", "title": "Customer Name"},
{"data": "status", "title": "Registered"}
// {"data": "status", "title": "Status"}
]
});
// setInterval(function () {
// table.ajax.reload();
// }, 10000);
})

You are printing each result inside the loop. You should print the result as 1 array.
/* ============= Declare the data outside the loop ============= */
$data = array();
foreach ($result->result() as $row){
$customer = $row->customer_name;
$ipull = $row->ip;
if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true) {
$PING = $this->routerosapi->comm("/ping", array(
"address" => $ipull,
"count" => "2"
));
if( $PING['0']['packet-loss'] == 0){
$status = "Online";
} else {
$status = "Offline";
}
} else {
$this->session->set_flashdata('Connect_False','Failed To get');
redirect('tmikrotik/router_list');
}
/* ============= Push each result on an array ============= */
$data[] = array(
'customer' => $customer,
'address' => $ipull,
'status' => $status
);
}
/* ============= print result (outside the loop ) ============= */
print json_encode($data);

Related

PHP add key data to json

Have a nice day. I have created the following basics:
{
"1111": {
"h264": {
"url": "TEST",
"expire": 1649453177
}
}
}
I need to add the following lines to the same key:
{
"1111": {
"h264": {
"url": "TEST",
"expire": 1649453177
},
"h265": {
"url": "TEST",
"expire": 1649456380
}
}
}
But whatever I try, it does this to me:
{
"1111": {
"h264": {
"url": "TEST",
"expire": 1649453177
},
"0": {
"h265": {
"url": "TEST",
"expire": 1649456380
}
}
}
}
Here is some sample code:
$time = time();
$codec = "h265";
$url = "TEST";
$id = "1111";
$data = json_decode(file_get_contents('./data.json'), true);
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
array_push($data[$id], $post_data);
$data = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
file_put_contents('./data.json', $data);
Can someone advise me not to add the 0 key to me there
Change:
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
array_push($data[$id], $post_data);
To:
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
$data[$id]['h265'] = $post_data;

codeigniter create response array object

I have the code below, but the result of the json response doesn't match
public function tes_get(){
$kode= $this->M_mymodel->tbl_kode('302'); // row
$res = array();
foreach ($kode as $key=> $value) {
$win = $this->M_mymodel->db_aa('302'); //row_array
$res = $this->M_mymodel->db_bb('302','LOSE'); //row_array
$res['data'][] = array(
'win' => $win['menang'],
'lose' =>$res['kalah']
);
}
$response = $this->set_response($res,200);
}
Below is the result of the response from the code I made above
{
"data": [
{
"win": "2",
"lose": "11"
}
]
}
How to make json response like below?
{
"data": [
{
"win": "2",
}
{
"lose": "11"
}
]
}
You can try :
$res['data'][] = array(
array('win' => $win['menang']),
array('lose' =>$res['kalah'])
);

Looping through validation data received from Ajax in laravel controller

I am sending a json request through Ajax, this request contains multiple objects,I am trying to find a way to validate the request to fail if at least one particular attribute fails the rule(min 5 characters in "value"); but dosent seems to work, can anyone help ?
I tried to loop data , I feel I am close but still dosent work.
my Ajax:
-------
< script >
function ajaxUpdate() {
var formdata = document.getElementsByTagName('input');
var formT = [].map.call(formdata, function(input) {
if (input.style.textDecoration === "line-through") {
input['completed'] = "1"; //add key value pairs
} else {
input['completed'] = "0"; //add key value pairs
}
return {
'value': input.value,
'id': input.id,
'completed': input.completed
}; //determine what keys to show.
});
formT.shift(); // Removes the first element from an array, because it contains token
formT = formT.filter(function(e) {
return e != null; //remove null elements.
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// e.preventDefault();
$.ajax({
url: "/updateAddTask",
dataType: "json",
contentType: "application/json",
data: {
objJSON: JSON.stringify(formT),
},
success: function(response) {
if ($.isEmptyObject(response.error)) {
if (response.success === true) {
successSweetAlert();
} else {
alert(JSON.stringify(response.errors.value.toString()));
}
}
},
// location.reload();
})
}
</script>
My controller:
--------------
public function loopData(Array $data)
{
foreach ($data as $key => $jsons) {
foreach ($jsons as $key1 => $value) {
return $jsons;
}
}
}
public function ajaxUpdateTasks(Request $request)
{
$data = json_decode($request->objJSON, true);//this will give an array of all the input elements
// dd($data);//output is below:
// array:3 [
// 0 => array:3 [
// "value" => "kilo"
// "id" => "55"
// "completed" => "0"
// ]
// 1 => array:3 [
// "value" => "new123"
// "id" => "793"
// "completed" => "1"
// ]
// 2 => array:3 [
// "value" => "ef4"
// "id" => "794"
// "completed" => "0"
// ]
//]
$rules = [
'value' => 'required|max:255|min:5', //value is
];
$messages = [
'value.max' => 'Todo title should be less than 255 characters',
'value.min' => 'Todo title should be more than 4 characters'
];
$validator = Validator::make($this->loopData($data),$rules, $messages);// ?????
if ($validator->fails()) {
$errors = $validator->getMessageBag()->toArray();
$result = ['success' => false, 'errors' => $errors];
return response()->json($result);
} else {
$result = ['success' => true, 'errors' => null];
$count = count(json_decode($request->objJSON, true));
$id = json_decode($request->objJSON, true)[0] ['id'];
$value = json_decode($request->objJSON, true)[0] ['value'];
$completed = json_decode($request->objJSON, true)[0] ['completed'];
-----remaining of the code --------
}
Thanks for any help.
I solve it by simply changing rules and messages: $rules = [ " *.value" => 'min:4', ]; $messages = [ " *.value.max" => 'Todo title should be less than 255 characters', " *.value.min" => 'Text should be more than 4 characters' ]; $validator=Validator::make($data, $rules,$messages);

how to change the format of json value data in codeigniter

I am trying to display data for a plugin with a predefined json format, but after I try the data does not match the format how the problem?
JSON Required
[
{
latLng: [-6.17343444,1206.834234294],
name: 'XY'
},
{
latLng: [-6.1742343244,106.898987294],
name: 'XK'
}
]
Result my JSON
[
{
"latLng": "-6.17343444,1206.834234294",
"name": "XK"
},
{
"latLng": "-6.1742343244,106.898987294",
"name": "XY"
}
]
myscript PHP
public function lat_lang() {
foreach($this->model->name_model() as $row){
$data[] = array(
'latLng' => $row->lat_long,
'name' => $row->city
);
}
header('content-type: application/json');
echo json_encode($data);
}
call JSON
$.parseJSON('<?php echo base_url().'mycontrollers';?>', function(datas) {
console.log(datas);
});
You can use explode() to transform the string "-6.17343444,1206.834234294" into an array [-6.17343444,1206.834234294]:
public function lat_lang() {
foreach($this->model->name_model() as $row){
$data[] = array(
'latLng' => explode(',',$row->lat_long),
'name' => $row->city
);
}
header('content-type: application/json');
echo json_encode($data);
}
If you want to get floats (for all value in the JSON), you could use JSON_NUMERIC_CHECK:
json_encode($data, JSON_NUMERIC_CHECK);
Or, just for a specific value:
$latLng = explode(',', $row->lat_long);
$latLng = array_map('floatval', $latLng);
$data[] = array(
'latLng' => $latLng,
'name' => $row->city
);

Inserting JSON data into mysql using Codeigniter

I have json input as mentioned below am decoding the the json response and inserting it into the mysql database,Now am converting this into Codeigniter I am not able to understand how to write the controller and the model for the below code,Please let me know how to write the controller and model, also am providing the controller and model which is written by me
PHP Code
<?php
include ('config.php');
// read json file
date_default_timezone_set('Asia/Kolkata');
$timestamp = time();
$date_time = date("Y-m-d H:i:s", $timestamp);
$createdon = $date_time;
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// $filename = 'employee.json';
// $json_data = file_get_contents($filename);
$json_data = $_POST['QUESTION'];
//convert json object to php associative array
$data = json_decode($json_data, true);
// print_r($data);
if (is_array($data) || is_object($data)) {
$jsonData = $data['DATA'];
$jsonAnswers = $data['ANSWERS'];
$drcode = $data['DATA']['DRCODE'];
$divcode = $data['DATA']['DIVCODE'];
$brdcode = $data['DATA']['BRDCODE'];
$prdcode = $data['DATA']['PRDCODE'];
// echo $drmobile." -- ";
for ($i = 0;$i < sizeof($data['ANSWERS']);$i++) {
$quecode[$i] = $data['ANSWERS'][$i]['ADCODE'];
$answer[$i] = $data['ANSWERS'][$i]['ANSWER'];
$quecodes = $quecode[$i];
$answers = $answer[$i];
// echo $quecode[$i]." <--> ".$answer[$i]."<br/>";
$sql = "INSERT INTO ANSWERS(DRCODE,ADCODE,DIVCODE,BRDCODE,PRDCODE,ANSWERS,CREATEDON)VALUES ('$drcode', '$quecode[$i]', '$divcode', '$brdcode', '$prdcode', '$answer[$i]', '$createdon')";
$qur = mysql_query($sql);
if ($qur) {
$json = array("status" => 1, "msg" => "Data added Successfully!");
} else {
$json = array("status" => 2, "msg" => "Already Submitted");
}
}
// echo "<br/>-----------<br/>";
}
} else {
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
//close connection
?>
Json Input
{
"DATA": {
"DRCODE": "D40504",
"DIVCODE": 1,
"BRDCODE": 5,
"PRDCODE": 5
},
"ANSWERS": [{
"ADCODE": 1,
"ANSWER": "VERY GOOD"
}, {
"ADCODE": 2,
"ANSWER": "GOOD"
}, {
"ADCODE": 3,
"ANSWER": "SGH"
}, {
"ADCODE": 4,
"ANSWER": "NO"
}, {
"ADCODE": 5,
"ANSWER": "NO"
}, {
"ADCODE": 6,
"ANSWER": "CGHJ"
}]
}
Controller
public function feedback_post() {
$json_data = $this->post('QUESTION');
$data = $this->json_decode($json_data, true);
if (is_array($data) || is_object($data)) {
$jsonData = $this->$data['DATA'];
$jsonAnswers = $this->$data['ANSWERS'];
$drcode = $this->$data['DATA']['DRCODE'];
$divcode = $this->$data['DATA']['DIVCODE'];
$brdcode = $this->$data['DATA']['BRDCODE'];
$prdcode = $this->$data['DATA']['PRDCODE'];
for ($i = 0;$i < sizeof($data['ANSWERS']);$i++) {
$quecode[$i] = $this->$data['ANSWERS'][$i]['ADCODE'];
$answer[$i] = $this->$data['ANSWERS'][$i]['ANSWER'];
$quecodes = $this->$quecode[$i];
$answers = $this->$answer[$i];
}
$insert_array = array('DRCODE' => $drcode, 'DIVCODE' => $divcode, 'BRDCODE' => $speciality, 'PRDCODE' => $prdcode, 'ANSWER' => $answers, 'ADCODE' => $quecodes);
$feedback_data = $this->Rest_user_model->feedbacksubmission($insert_array);
if ($feedback_data) {
$message = ['status' => 1,
// 'result' => array(),
'message' => 'Feedback Submitted Successfully'];
} else {
$message = ['status' => 2,
// 'result' => array(),
'message' => 'Feedback Submitted Successfully'];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
try this
public function feedback_post()
{
$objDate = new DateTime();
$data = json_decode($this->input->post('QUESTION'), true);
if (is_array($data))
{
foreach($data['ANSWERS'] AS $arrAnswer)
{
$arrInsertData =
[
'DRCODE' => $data['DATA']['DRCODE'],
'DIVCODE' => $data['DATA']['DIVCODE'],
'BRDCODE' => $data['DATA']['BRDCODE'],
'PRDCODE' => $data['DATA']['PRDCODE'],
'ADCODE' => $arrAnswer['ADCODE'],
'ANSWERS' => $arrAnswer['ANSWER'],
'CREATEDON' => $objDate->format('Y-m-d H:i:s'),
];
$feedback_data = $this->Rest_user_model->feedbacksubmission($arrInsertData);
$message = ($feedback_data) ? ['status' => 1, 'message' => 'Feedback Submitted Successfully'] : ['status' => 2, 'message' => 'Already Submitted'];
}
}
else
{
$message = ["status" => 0, "msg" => "Request method not accepted"];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
this is pretty much basic understanding of php - but you've to ask yourself - if you've multiple answers - what happens if one fails and one is successful ?
Because your sample php code is simply wrong...

Categories