Using AJAX returned JSON encoded data in Codeigniter - json

I am relatively new to codeigniter. While I was trying to perform a searching operation on my data base using AJAX, The code is returned as successful and the data is retrieved but, This data is JSON encoded and is in the javascript portion of my view so I am unable to use the json_decode function of codeigniter
public function lookup(){
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->MAutocomplete->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
echo json_encode($data); //echo json string
}
the data is accessed in the javascript as data.message.
Please tell me is there anyway i can use this data in the php part of my program
<?php
class MAutocomplete extends CI_Model{
function lookup($keyword){
$this->load->database();
$this->db->select('*');
$this->db->from('Students');
$this->db->like('firstName',$keyword,'after');
$query = $this->db->get();
// echo '<pre>'; print_r($query->result()); exit;
return $query->result();
}
}

I think you need to parse json response in Ajax's success function using JSON.parse().Like this..
$.ajax({
url:'',//your url
dataType:'JSON',
data:'',//your data
success:function(response){
data = JSON.parse(response);
alert(data.message.value);//alerts value
}
});
In controller use count rather than empty.To check the array
if( count($query) >0 )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}

You should use to response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($data));

Related

JSON response return HTML inside a Loop

I have this function in Laravel 5.1
public function calcolaKilometri()
{
$partenza = Input::get('partenza');
$destinazione = Input::get('destinazione');
$distanceMatrix = new DistanceMatrix(new Client(), new GuzzleMessageFactory());
$response = $distanceMatrix->process(new DistanceMatrixRequest(
[$partenza],
[$destinazione]
));
foreach ($response->getRows() as $row) {
foreach ($row->getElements() as $element) {
$distance = $element->getDistance();
$text = $distance->text;
$value = $distance->value;
$data = ['text' => $text, 'value' => $value];
return \Response::json($data);
}
}
}
need to return to Ajax JSON data but this function return plain HTML response, because we are in a forech loop. How i can do the trick?
I'm not sure I fully understand what you're saying but I assume you want to return all of the data found when looping through your result set in a single JSON response.
Try something like this:
// Your previous code...
// Initialise a $data array here, that we're going to fill with data
$data = [];
foreach ($response->getRows() as $row) {
foreach ($row->getElements() as $element) {
$distance = $element->getDistance();
$text = $distance->text;
$value = $distance->value;
// Append the new set of data to your array
$data[] = ['text' => $text, 'value' => $value];
}
}
// Return the data as JSON only when we've filled it with everything
return response()->json($data);
Try This...
$json = json_encode($data);
return \Response::json($json);
Solved using sessions. If someone have the same issue:
public function calcolaKilometri()
{
$partenza = Input::get('partenza');
$destinazione = Input::get('destinazione');
$distanceMatrix = new DistanceMatrix(new Client(), new GuzzleMessageFactory());
$response = $distanceMatrix->process(new DistanceMatrixRequest(
[$partenza],
[$destinazione]
));
foreach ($response->getRows() as $row) {
foreach ($row->getElements() as $element) {
$text = $element->getDistance()->getText();
$value = $element->getDistance()->getValue();
\Session::put('testo', $text);
\Session::put('valore', $value);
}
}
// Return the data as JSON only when we've filled it with everything
$testo = \Session::get('testo');
$valore = \Session::get('valore');
$result = ['text' => $testo, 'value' => $valore];
return \Response::json($result);
}

How to decode multiple json array in codeigniter

How to decode the below json array and insert into database
{`user`:[{"user_id":1,
"address_id":4,
"total_quantity" :8,
"total_amount":12000},],
"products":[{"products_name":"Shirt",
"quantity":4,
"price":1000},
{"products_name":"sari",
"quantity":4,
"price":2000}]}}
Try this
$data = json_decode($json);
foreach($data->users as $user)
{
$user_id = $user->user_id;
$address _id = $user->address_id;
//similar for other data and save it to database
}
For products
foreach($data->products as $product)
{
$products_name = $product->products_name;
$quantity = $product->quantity;
//similar for other data and save it to database
}
Something like
$data = json_decode($data);
foreach($data->products as $row) // if $data->products does not work try $data['products']
{
$this->db->insert('products',$row)
}

How to return Repository Objects as Json on Symfony2

I'm trying to return the users like this, but of course it doesn't work, I need the data as JSon since im working with BackboneJs
/**
* #Route("/mytest",name="ajax_user_path")
*/
public function ajaxAction()
{
$em = $this->get('doctrine')->getManager();
$users = $this->get('doctrine')->getRepository('GabrielUserBundle:Fosuser')->findAll();
$response = array("users"=>$users);
return new Response(json_encode($response));
}
Thanks for your help guys, here is the Solution
Get the JMSSerializerBundle,
This is the code on the controller
/**
* #Route("/user")
* #Template()
*/
public function userAction()
{
$em = $this->get('doctrine')->getManager();
$users = $this->get('doctrine')->getRepository('GabrielUserBundle:Fosuser')->findAll();
$serializer = $this->get('jms_serializer');
$response = $serializer->serialize($users,'json');
return new Response($response);
}
So, findAll returns an array of entities (objects) and json_encode cannot correctly encode that array. You have to prepare your data berofe send response like that:
Example:
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* #Route("/mytest",name="ajax_user_path")
*/
public function ajaxAction()
{
$users = $this->get('doctrine')->getRepository('GabrielUserBundle:Fosuser')->findAll();
$response = array();
foreach ($users as $user) {
$response[] = array(
'user_id' => $user->getId(),
// other fields
);
}
return new JsonResponse(json_encode($response));
}
Moreover, it would be great if you put preparing response to ex. UserRepository class.
With Symfony you have JsonResponse like :
return new JsonResponse($users);
And don't forget to add the header :
use Symfony\Component\HttpFoundation\JsonResponse;
I have never tried to encode a complete object, but I have used json with arrays of informations like this:
$vars = array(
'test' => 'test'
);
$response = new JsonResponse($vars);
return $response;
As you can see in JsonResponse, its function setData() is encoding the array, so you don't have to do it yourself:
public function setData($data = array())
{
// Encode <, >, ', &, and " for RFC4627-compliant JSON, which may also be embedded into HTML.
$this->data = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
return $this->update();
}

Ajax JSON multi array - determing array index contains specified values

I am returning a JSON multi array from PHP via JQuery Ajax, and want to determine which array contains a value in order to access values in that array (likewise for the other arrays - up to three arrays altogethebeing returned.
$.ajax({
type: "POST",
url: "scripts/get_model_imaging_report.php",
data: {
case_id:caseId,
level:currentLevel
},
dataType: "json",
success: function(returnedData) {
}
});
PHP;
$case = $_POST['case_id'];
$level = $_POST['level'];
$query = "SELECT * FROM model_image_report WHERE case_fk = '$case' AND level = '$level'";
$result = mysql_query($query, $connection) or die(mysql_error());
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array(
'image_report_type' => $row['image_report_type'],
'subject' => $row['subject'],
'clinical' => $row['clinical'],
'study_type' => $row['study_type'],
'report' => $row['report'],
'comment' => $row['comment'],
'image' => $row['image'],
'image_annotated' => $row['image_annotated']
);
}
echo json_encode($data);
The key I need to check is 'image_report_type' and the values can be 'nuclear', 'radiology' and 'ultrasound'.
Then I need to access values in those arrays where 'image_report_type' == 'nuclear' for example.
The JSON array looks like:
[{"image_report_type":"nuclear","subject":"Brain Scan","clinical":"Clinical","study_type":"nuclear image scan.","report":"Report","comment":"Comment","image":"original_image_case_3_level_1_nuclear.jpg","image_annotated":"annotated_image_case_3_level_1_nuclear.png"},{"image_report_type":"ultrasound","subject":"Brain Scan","clinical":"Clinical","study_type":"Ultrasound image scan.","report":"Report","comment":"Comment","image":"original_image_case_3_level_1_nuclear.jpg","image_annotated":"annotated_image_case_3_level_1_nuclear.png"}]
You can accomplish this with the jQuery each function.
function(returnedData) {
$.each(returnedData, function(i,o) {
if (o.image_report_type == "nuclear") {
//Do Something
}
});
}
Here is a jsFiddle Demonstrating this technique
Try this http://jsfiddle.net/mN4LF/3/
Javascript
function findIndexOf(data, searchField, searchValue){
var result = new Array();
for(var i = 0; i < data.length; i++){
if(data[i][searchField] == searchValue){
result.push(i);
}
}
return result;
}

Convert codeigniter query to json?

I want to convert a model query to json with json_encode, it doesn't work. But with a ordinary array it does.
$arr = array("one", "two", "three");
$data["json"] = json_encode($arr);
Output
<?php echo "var arr=".$json.";"; ?>
var arr=["one","two","three"];
But when I try to convert a query codeigniter throws an error. What is it with that?
This is the error message:
A PHP Error was encountered Severity:
Warning Message: [json]
(php_json_encode) type is unsupported,
encoded as null
And the converted "query" result = I mean model method is like this:
{"conn_id":null,"result_id":null,"result_array":[],"result_object":[],"current_row":0,"num_rows":9,"row_data":null}
I try to do like this
$posts = $this->Posts_model->SelectAll();
$data["posts"] = json_encode($posts);
By the way, the model and method works just fine when I do it without json_encode.
Something I'm propably doing wrong, but the question is what?
You appear to be trying to encode the CodeIgniter database result object rather than the result array. The database result object acts as a wrapper around the cursor into the result set. You should fetch the result array from the result object and then encode that.
Your model code appears to be something like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
// Return the result object
return $this->db->query($sql);
}
It should be more like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
}
This will return an array of objects which you can encode in JSON.
The reason you are getting an error trying to encode the result object is because it has a resource member variable that cannot be encoded in JSON. This resource variable is actually the cursor into the result set.
public function lastActivity()
{
header("Content-Type: application/json");
$this->db->select('*');
$this->db->from('table_name');
$query = $this->db->get();
return json_encode($query->result());
}
As per latest CI standard use the following code in your controller file:
$this->output->set_content_type('application/json')->set_output(json_encode($arr));
Models (Post):
function SelectAll()
{
$this->db->select('*');
$this->db->from('post');
$query = $this->db->get();
return $query;
}
Controllers :
$data['post'] = $this->post->SelectAll()->result_array();
echo json_encode($data);
Result:
{"post":[{"id":"5","name":"name_of_post"}]}
Here is the working solution:
$json_data = $this->home_model->home_getall();
$arr = array();
foreach ($json_data as $results) {
$arr[] = array(
'id' => $results->id,
'text' => $results->name
);
}
//save data mysql data in json encode format
$data['select2data'] = json_encode($arr);