Json_encode and json_decode not working in yii2 - yii2

i want to insert value through Json_encode through controller but json_encode() not working in yii2.
json_encode();

You can test json_encode() in a controller:
public function actionIndex()
{
$json = json_encode(['key'=>'value']);
echo $json;
}
The result should be:
{"key":"value"}
json_encode() won't be unworked without an error such as no php-json extension, and it is a PHP function which works the same in Yii2.

Related

Laravel controller won't let me passing data as a json for with the error : Call to a member function withData() on string

hi guys im stuck here i dont know whay i cant send json data with a laravel controller.
controller :
$data = DB::table('users')
->where('id','=',$id)
->get();
// dd($data);Working perfectly
return '/medcine/homeMS'->withData(json_encode($data));//error in this line
my route :
Route::get('/medcine/homeMS', function () {
return view('auth.medcine.homeMS');
})->middleware('verified')->middleware('medcineMS');
and in my blade i added this line :
<div data={{$data}} ></div>
you are not configured your route correctly
in the second parameter you should specify your controller
route:
Route::get('/medcine/homeMS', "YourController#method")->middleware('verified')->middleware('medcineMS');
and in your controller:
$data = DB::table('users')
->where('id','=',$id)
->get();
return view('auth.medcine.homeMS')->with('data' , json_encode($data));

Yii2 Functional test send ajax get request not working

I am trying to test an ajax request with a basic install of Yii2. I am just using the SiteController::actionAbout() method to try this out.
public function actionAbout()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'message' => 'hello world',
'code' => 100,
];
}
And in the test:
public function sendAjax(\FunctionalTester $I)
{
$I->sendAjaxGetRequest('site/about');
$r = $I->grabResponse();
die(var_dump($r));
}
The grab response method is one I wrote myself in a \Helper\Functional.php file:
public function grabResponse()
{
return $this->getModule('Yii2')->_getResponseContent();
}
When I dump out the response, I just see the html from the site/index page.
This happens for any route except the site default. If I try to do the same thing using site/index then it returns:
string(36) "{"message":"hello world","code":100}"
What am I missing / doing wrong?
Note the difference between a Yii route and the actual URL.
The argument to sendAjaxGetRequest() is the URL, not the route (at least if you pass it as a string, see below).
Dependent on your UrlManager config you might have URLs like /index.php?r=site/about, where the route is site/about. You can use the Url helper of Yii to create the URL:
$I->sendAjaxGetRequest(\yii\helpers\Url::to(['site/about']));
I am not sure about this but if you have the Codeception Yii2 module installed you should also be able to pass the route like this:
$I->sendAjaxGetRequest(['site/about']);

Doctrine2 & zf2 : fetchAll() result to JSON ,cont convert result to array and then to json in ZF2

Im completely new to Doctrine and ZF2 , coming from C# env. from few days im working on doctrine and zf2 . and trying to learn the basic things so that I can build RESTFull Service API in coming days . Now , I am trying to get the doctrine fetch All() result in to json but failing to do so. mys API client ( backbone.js ) is working fine and it is result but showing empty objects
my controller code goes like this
public function getList() {
$repository = $this->getEntityManager()->getRepository('Application\Entity\Test');
$posts = $repository->findAll();
echo var_dump((array)$posts);
header('Access-Control-Allow-Origin:http://api.server.com');
return new JsonModel($posts);
}
var_dump result
array(2) {
[0]=>
object(Application\Entity\Test)#339 (2) {
["id":"Application\Entity\Test":private]=>
int(2)
["name":"Application\Entity\Test":private]=>
string(5) "Kumar"
}
[1]=>
object(Application\Entity\Test)#340 (2) {
["id":"Application\Entity\Test":private]=>
int(1)
["name":"Application\Entity\Test":private]=>
string(8) "Panindra"
}
}
and my JSONModel out put is [{},{}].
I want to build this as RESTFull Service
You can use the QueryBuilder API and getResult() method of the Doctrine\ORM\Query object with HYDRATE_ARRAY option to achieve that. Example:
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$queryBuilder->select('t')
->from('Application\Entity\Test', 't');
$results = $queryBuilder->getQuery()
->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
return new JsonModel($results);
Everything in your code is correct and works fine. The JsonModel is "empty" because your class members are private. If you set them to public, you will get the expected JsonModel.

Yii Restful API will create on POST but not populate any variables

Hello I am currently trying to use POSTMAN to test an early API that is based of of this post
http://www.yiiframework.com/wiki/175/how-to-create-a-rest-api/
I am having an error when trying to either submit variables via POST in php url style or even sending an object. The response from the API comes back 200 and it creates a new entry into the database, but unfortunately it will not take any info from the post variables or jason object, it just comes up null. It seems now that that code is just looking through $_POST variables to and trying to match them to a model variable and if so, it should update it save it, However when i try to send through url parameters in POSTMAN or even change content type json and send raw json object I seem to have no luck with it.
Also I really only need it to decode a jason object and not post parameters so maybe that is where I will start by removing the $post loop and working on retrieving a JSON object instead. Thanks for any help!
public function actionCreate()
{
switch($_GET['model'])
{
// Get an instance of the respective model
case 'event':
$model = new Event;
break;
case 'media':
$model = new Media;
break;
case 'comment':
$model = new Comment;
break;
default:
$this->_sendResponse(501,
sprintf('Mode <b>create</b> is not implemented for model <b>%s</b>',
$_GET['model']) );
Yii::app()->end();
}
// Try to assign POST values to attributes
foreach($_POST as $var=>$value) {
// Does the model have this attribute? If not raise an error
if($model->hasAttribute($var))
$model->$var = $value;
else
$this->_sendResponse(500,
sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var,
$_GET['model']) );
}
// Try to save the model
if($model->save())
$this->_sendResponse(200, CJSON::encode($model));
else {
// Errors occurred
$msg = "<h1>Error</h1>";
$msg .= sprintf("Couldn't create model <b>%s</b>", $_GET['model']);
$msg .= "<ul>";
foreach($model->errors as $attribute=>$attr_errors) {
$msg .= "<li>Attribute: $attribute</li>";
$msg .= "<ul>";
foreach($attr_errors as $attr_error)
$msg .= "<li>$attr_error</li>";
$msg .= "</ul>";
}
$msg .= "</ul>";
$this->_sendResponse(500, $msg );
}
}
Fixed by removing $POST loop and changing to a JSON object scheme only. Here is the code if anyone happens to find themselves in this situation.
//read the post input (use this technique if you have no post variable name):
$post = file_get_contents("php://input");
//decode json post input as php array:
$data = CJSON::decode($post, true);
//load json data into model:
$model->attributes = $data;
Used that instead of the foreach loop through $_POST variables. Now it accepts a json object instead. Happy Coding all!
Honestly, I'm not sure what your problem is. If you can see the values POSTed in $_POST but not assigned to $model, it's probably because you did not specify the validation rules for those fields in the model. If you do not need to validate the fields, simply mark them as 'safe' in the model's rules() function like below.
public function rules() {
return array(
array('fieldName1,fieldName2', 'safe'),
);
}

Symfony2 returns empty JSON on AJAX call while variable isn't empty

Problem
I'm trying to get an AJAX response so I can fiddle around with it to make my forms easier to use. When I make the controller (code below) return a normal response with var_dump(), I get the object's output so I know the query isn't wrong (I'm using ID 1 to query to debug). However, when I return the output with json_encode(), I just get an empty JSON file.
HTML form in the view
<div id="content">
<form id="myForm" action="{{path('snow_ajax')}}" method="POST" >
Write your name here:
<input type="text" name="name" id="name_id" value="" /><br />
<input type="submit" value="Send" />
</form>
</div>
Script in the same view
<script type="text/javascript">
$(document).ready(function() {
$("#myForm").submit(function(){
var url=$("#myForm").attr("action");
$.post(url,{
formName:"ajaxtest",
other:"attributes"
},function(data){
if(data.responseCode==200 ){
alert("Got your json!");
}
else{
alert("something went wrong :(");
}
});
return false;
});
});
</script>
Controller with normal response (works)
public function ajaxAction()
{
$location = $this->getDoctrine()->getRepository('SnowFrontBundle:Location')
->find(1);
$output = var_dump($location);
return $output;
}
Controller with AJAX response (doesn't work, returns empty JSON)
public function ajaxAction()
{
$location = $this->getDoctrine()->getRepository('SnowFrontBundle:Location')
->find(1);
return new Response(json_encode($location), 200);
}
Could anyone help me out here, please? This is driving me nuts!
I managed to fix it by using Doctrine2's entity manager to get the result in an array, after which I proceeded to encode it into JSON. I'm not sure if this is the cleanest way to do it (getEntityManager() seems to be deprecated according to my IDE) but it works fine for now.
public function ajaxAction()
{
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery('SELECT l FROM Snow\FrontBundle\Entity\Location l WHERE l.id=:id');
$query->setParameter('id', 1);
$result = $query->getArrayResult();
return new Response(json_encode($result), 200);
}
This is happening because json_encode() does not know how to serialize an object (other than StdClass) to JSON. There are at least two ways to solve this:
If you are on PHP 5.4 or above, you can have your object implement JsonSerializable, which PHP will use when you call json_encode() on the object.
If you are on PHP 5.3 or earlier, you can use Symfony's Serializer component to convert the object to JSON using a number of different methods. I won't explain how exactly to do that, since the documentation is pretty clear.
Code example:
$entity = // Get some entity
$result = array(
'id' => $entity->getId(),
'name' => $entity->getName()
);
return new Response(json_encode($result));
If you want to get back data, you have to use a query repository (dsl) and on your $query variable use the getArrayResult() method. That allows you to get an array directly.