Retrieve JSON Post Data in Codeigniter

Retrieve JSON POST data in CodeIgniter

General method I use for my Ajax Calls in CI :

JS :

post_array =
{
"myvar" : "value1",
"myvar2": "value2"
}

$.post(baseUrl + "/AjaxController/my_function", post_array,
function(data)
{
var res = jQuery.parseJSON(data);
alert(res.property);
}

Controller :

public function my_function()
{
$myvar = $this->input->post('myvar');
$myvar2 = $this->input->post('myvar2');

//Stuff

echo json_encode($myobject);
}

Handling JSON data in Codeigniter Controller

when you send json data to php its in doesn't come in $_POST or $_GET its in php://input strem;

the ajax request u send ws not jQuery its core js, which is good but its quite unflexible and tends to break in different browser. i just used the jQuery version of the ajax which is very flexible and cross-browser as well.

try this :
JS:

$.ajax({
method:'POST',
contentType:'application/json',
url:'http://example.com/share/new',
data: JSON.stringify({"id": "1", "type": "new", "data": "testabcd"}),
success:function(response){
console.log(response);
}

});

PHP:

public function reservation()
{

$Data = json_decode(file_get_contents('php://input'), true);

$data_share = array(
'id' => $Data['id'],
'type' => $Data['type'],
'data' => $Data['data']);

$this->db->insert('mytable', $data_share);

return "200";
}

Get JSON response In Codeigniter

use this code:

header('Content-type: application/json');

$Data = json_decode(file_get_contents('php://input'),true);

now, you will get $Data as a array.

and you get value by $Data['name'].

How get data JSON multi array via POST in php

Tge post method returns an associative array of the parameters from the browser
By definition its not a json string

Let's assume that the parameter sent by post is json, we can play with that :

$json = $_POST['json'];

Then this should work:

print_r($json);

To get the json as an array, then you should json decode $json, with the true parameter, to get an associative array and not an object

$jsonarray = array();
$jsonarray = json_decode($json, true);

now to print it,foreach is needed:

foreach ($jsonarray as $fieldpost1) {
print_r($fieldpost1);
}

hope that helps

Get JSON Encode Data PHP CodeIgniter

From your data structure. It is object inside array then this is the code.

$nama_fields = [];
foreach($data_form as $data_field){
$jsonData = json_decode($data_field->field_form);

if (is_array($jsonData)) {
foreach ($jsonData as $index => $item) {
if (isset($item->nama_field)) {
$nama_fields[] = $item->nama_field;
}
}
}
}

// then use $nama_fields variable.
var_dump($nama_fields);


Related Topics



Leave a reply



Submit