I'm using Laravel to return a JSON object and I can't find a way to delete the index of my array.
My code :
<?php
class PlayerController extends BaseController {
public function checkupdate()
{
$datapack = DB::table('datapack')->first();
return Response::json(array(['datapack'=>$datapack],'time' => date('Y-m-d H:i:s')),200);
}
}
which give me :
{
"0":{
"datapack":{
"id":"FD524D0F-5732-44B7-AC46",
"timeUpdated":1401184091
}
},
"time":"2014-10-06 15:58:20"
}
and I want something like this :
{
"datapack":{
"id":"FD524D0F-5732-44B7-AC46",
"timeUpdated":1401184091
},
"time":"2014-10-06 15:58:20"
}
Change:
return Response::json(array(['datapack'=>$datapack],'time' => date('Y-m-d H:i:s')),200);
into:
return Response::json(array('datapack'=>$datapack,'time' => date('Y-m-d H:i:s')),200);
You put the datapack in its own sub-array with the [].
You've got a level of array nesting in there you don't need.
Instead of
Response::json(array(['datapack'=>$datapack],'time' => date('Y-m-d H:i:s')),200);
Try
Response::json(array('datapack'=>$datapack,'time' => date('Y-m-d H:i:s')),200);
Related
i am trying to show a consult which have an array with arrays in symfony using Ajax and json, this is my ajax's script :
<script>
var boton=document.getElementById("form_Boton");
function ajax() {
var nombre=$('#form_nombre').val();
$.ajax({
type: 'POST',
url: "{{ path('buscar_porCriterio') }}",
data: ({nombre: nombre}),
dataType:"json",
beforeSend:function () {
alert("enviará a: "+nombre);
},
success:function (resp) {
if(resp!=""){
$('#resultados').html(resp["nombre"]+" "+resp["apellido"]+" "+resp["residencia"]);
}
if(resp==""){
alert("NO SE ENCONTRO NADA");
}
}
})
}
boton.addEventListener("click",ajax);
</script>
And this is my controller:
public function PorCriterioAction(Request $request){
if(!$request->isXmlHttpRequest())
{
throw new Exception("Error, NO ES AJAX");
}
$nombre=$request->request->get('nombre');
$em=$this->getDoctrine()->getManager();
$encontradas=$em->getRepository('FormulariosBundle:persona')->findBynombre($nombre);
if ($encontradas == null) {
$response = new Response("VACIO " . $nombre . " Sorry");
return $response;
}
else{
$persona_encontrada = (array("id" => $encontradas->getId(),
"nombre" => $encontradas->getNombre(),
"apellido" => $encontradas->getApellido(),
"residencia" => $encontradas->getResidencia()
));
$response= new JsonResponse($persona_encontrada);
return $response;}}
what i need is get all data from my DB whose name be $nombre, and show every data in my div 'resultados'. but. when i realize my search, symfony show me this exception:
Exception
my question is: How can i do to pass every data of that consult to my div 'resultados'?
as you see, i want to show such consult in a div whose id is "resultados" but does not work, can you help me please? i am a beginner in symfony and i have to make this University Proyect and finish my study, thanks for your answer
EDIT # 2
this is the change to my controller:
public function PorCriterioAction(Request $request){
if(!$request->isXmlHttpRequest())
{
throw new Exception("Error, NO ES AJAX");
}
$nombre=$request->request->get('nombre');
$em=$this->getDoctrine()->getManager();
$encontradas=$em->getRepository('FormulariosBundle:persona')->findBynombre($nombre);
if ($encontradas == null) {
$response = new Response("VACIO " . $nombre . " Sorry");
return $response;
}
else{
foreach ($encontradas as $Item){
$persona_encontrada = (array("id" => $Item->getId(),
"nombre" => $Item->getNombre(),
"apellido" => $Item->getApellido(),
"residencia" => $Item->getResidencia()
));
array_push($persona_encontrada,$Item);
}
$response= new JsonResponse($persona_encontrada);
return $response;
}
}
is this what you need? responseText
I believe $encontradas is a results set so try this:
foreach( $encontradas as $item){
$persona_encontrada = (array(
"id" => $item->getId(),
"nombre" => $item->getNombre(),
"apellido" => $item->getApellido(),
"residencia" => $item->getResidencia()
));
}
Let us know the result.
EDIT #2
I see the problem. Since it iterates through the array, you want $persona_encontrada to be an array and then use the PHP array_push to add array elements to it. You could do it like so:
$persona_encontrada = array();
foreach( $encontradas as $item){
$element = array(
"id" => $item->getId(),
"nombre" => $item->getNombre(),
"apellido" => $item->getApellido(),
"residencia" => $item->getResidencia()
);
array_push( $persona_encontrada, $element);
}
By the way, although this will work for you, it might not be the best way to do something like this. But it will work.
In my project I want to insert multiple rows of data at a single time using the foreach loop. I have a variable which has array of elements.
For instance if my array has say 3 different elements. I want to save all these 3 elements in the 3 different db table rows. I also have other columns which are same for all the 3 array elements.
I have put them inside foreach statement but only the 1st elements gets saved. Is there any method I can achieve this?
My code
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}
Only the productline_id is different other columns will have same data for all the prdouctline_id.
Thank You!!!
You have only one model object, and you are saving only to it.
Try this:
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model = new ProductlinesStorage();
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}
maybe you can modify my code
public function actionCreate()
{
$model = new SemesterPendek();
$model->user_id = \Yii::$app->user->identity->id;
$model->npm = \Yii::$app->user->identity->username;
$modelsNilai = [new Nilai];
if ($model->load(Yii::$app->request->post())){
$model->waktu_daftar = date('Y-m-d h:m:s');
$model->save();
$modelsNilai = Tabular::createMultiple(Nilai::classname());
Tabular::loadMultiple($modelsNilai, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Tabular::validateMultiple($modelsNilai) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsNilai as $indexTools =>$modelNilai) {
$modelNilai->id_sp = $model->id;
// $modelNilai->user_id = \Yii::$app->user->identity->id;
if (! ($flag = $modelNilai->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack(); \Yii::$app->session->setFlash('error','gagal');
}
}
} else {
return $this->render('create', [
'model' => $model,
'modelsNilai' => (empty($modelsNilai)) ? [new Nilai] : $modelsNilai,
]);
}
}
You need to create a different object to save in different rows. For loop executes 3 times but every time same object is being updated. You can define new object and save each time. Below code will work
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model = new ProductlinesStorage();
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}
I'm using $http.get to get some information from the server. First the controller calls the BackendServices, and in the service i call $http.get:
Controller:
app.controller('courseController', ['$scope', 'BackendServices', function ($scope, BackendServices) {
BackendServices.lookForCourses().then(
function (response) {
console.log(response);
},
function (response) {
}
);
$scope.addCourse = function (courseName) {
console.log(courseName);
};
}]);
Service:
app.service('BackendServices', function ($http) {
var backendServices = {};
backendServices.lookForCourses = function () {
return $http.get('app/backend/lookForCourses');
}
return backendServices;
});
The PHP files works under cakePHP framework.
lookForCourses:
public function lookForCourses () {
$this->autoRender = false;
$cursosFind = $this->Curso->find('all', array('fields' => array('nombreCurso')));
$cursos = array();
foreach($cursosFind as $index => $curso) {
$cursos[$index]['nombre'] = $curso['Curso']['nombreCurso'];
}
echo json_encode($cursos);
}
Doing this i get as a response on the console:
Object{data: "", status: 200, config: Object, statusText: "OK"}
If I do this:
var_dump($cursos);
I get the following:
array (size=3)
0 =>
array (size=1)
'nombre' => string 'Tecnologias de la informacion' (length=29)
1 =>
array (size=1)
'nombre' => string 'Propedeutico' (length=12)
2 =>
array (size=1)
'nombre' => string 'Lectura y redaccion' (length=19)
However, if i do the following:
$test = array(array('nombre' => 'Propedeutico'), array('nombre' => 'Tecnologias'));
echo json_encode($test);
I do get that array as a response...
What am I missing? I know this might be a silly mistake, but I haven't been able to solve it so far...
Thanks a lot!!
I made it work doing a little modification, since the result of the request brings back a string with accents, example: "TecnologĂa", i had to utf8_encode each one of the elements like this:
public function lookForCourses () {
$this->autoRender = false;
$cursosFind = $this->Curso->find('all', array('fields' => array('nombreCurso')));
$cursos = array();
foreach($cursosFind as $index => $curso) {
$cursos[$index]['nombre'] = utf8_encode($curso['Curso']['nombreCurso']);
}
echo json_encode($cursos);
}
Adding ut8_encode did the trick.
Based on the information here: Using a custom renderer with Exception.renderer to handle application exceptions
I'm creating a custom error renderer that renders in XML format.
Below is the sample code for the render function in app/Lib/Error/AppExceptionRenderer:
public function render() {
if (isset($this->controller->request->params['xml'])) {
$this->controller->viewClass = "MyXml";
$error = array(
'app' => array(
'error' => 'An unexpected error has occured.'
)
);
$this->controller->set('error', $error);
$this->controller->set('_serialize', 'error');
}
}
However nothing gets returned. I have done some echo within the if condition and that shows.
So is it because the viewClass is not initialized while its in AppExceptionRenderer::render() stage?
There were no errors either.
"MyXml" viewClass works perfectly in normal controllers too.
So apparently I was missing the render and send methods.
Here's the full working example.
<?php
class AppExceptionRenderer extends ExceptionRenderer {
public function __construct($exception) {
parent::__construct($exception);
}
public function render() {
// Handle errors
if (isset($this->controller->request->params['xml'])) {
Cakelog::error($this->error->getMessage());
$this->controller->viewClass = "MyXml";
$error = array(
'app' => array(
'error' => 'An illegal operation has been detected.'
)
);
$this->controller->set('error', $error);
$this->controller->set('_serialize', 'error');
$cakeResponseObject = $this->controller->render();
$this->controller->response->send($cakeResponseObject);
} else {
if ($this->method) {
call_user_func_array(array($this, $this->method), array($this->error));
}
}
}
}
In my controller i have 2 actions e.g
action1() {
//code
SomeArray=();
//code
}
How can i pass all the SomeArray data to action2?
I have tried to create a public array variable in my class and pass it but with no luck.
i have tried to pass as an argument to the action2...
e.g in action1, $this->action2(SomeArray) and then action2($param) with no luck again.
function doExam($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid exam', true));
$this->redirect(array('action' => 'index'));
}
$this->Exam->recursive=1;
$conditions_question = array('Question.exam_id' => $id);
$questions = $this->Exam->Question->find('all',array('conditions' => $conditions_question));
foreach ($questions as $question) {
**$this->questionsByExam[]** = $question['Question']['qst'];
}
//OK PASSED
echo debug($this->questionsByExam);
//OK $exam_id
$this->exam_id = $id;
}
i have another action validate_answer, and i want to pass the questionsByExam in here
any help?
Thanks in advance
I have tried to create a public array variable in my class and pass it but with no luck.
Can you show the code for this? It should work fine as class variable...
E.g:
class FooController extends AppController {
var $someArray = array();
function doExam() {
// Populate the array here
$this->someArray = array(1,2,3);
}
function bar() {
// Use it here, no need to pass it as an argument
print_r($this->someArray);
}
}