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.
Related
I have js code which gets results from a query and pastes table to a div.So table is created in js and set with js.how do I apply datatables filter in such a case?
if you are using ajax request filter ,So url parameter filter may help :
for example :
This is your ajax get request url :
$.get(root_url+'index/user?id='+id+'&name='+name+'&gender='+gender, function(response){
console.log(response);
});
And this how you can caught those parameter in cakephp
public function user(){
if ($this->request->is('ajax')) {
$id = $this->request->getQuery('id');
$name = $this->request->getQuery('name');
$gender = $this->request->getQuery('gender');
$condition = [];
if ($id){
$condition = ['Users.id' => $id];
}
if (name) {
$condition = ['Users.name' => $name];
}
if (gender) {
$condition = ['Users.gender' => $gender];
}
$user = $this->Users->find()
->select([
'Users.id',
'Users.name',
'Users.gender',
'Users.create_date',])
->where(condition);
response = ['user' => $user];
return $this->response->withType('application/json')
->withStringBody(json_encode($response));
} else {
return $this->redirect(['controller' => 'pages','action' => 'error404']);
}
}
I am working on my first app, based on Ionic and Angularjs connected to Wordpress REST Api.
I need to display the category name, but the WP-API V2 post list (example.com/wp-json/wp/v2/posts) has only the category ids.
In order to get the categories I need to make a second http request to example.com/wp-json/wp/v2/categories
This is my function in the controller to load all posts and it works fine.
var postsApi = $rootScope.url + 'posts';
$scope.loadPosts = function() {
// Get all of our posts
DataLoader.get( postsApi ).then(function(response) {
$scope.posts = response.data;
$log.log(postsApi, response.data);
}, function(response) {
$log.log(postsApi, response.data);
});
but how do I achieve to parse the category id, that i get from example.com/wp-json/wp/v2/posts with example.com/wp-json/wp/v2/categories to get the category name without making a http request every single loop?
You maybe need to use register_new_field() to modify the response from the api.
Modify response from wp-api v2
In your custom function, you will able to retrieve the post categories in one api call and embed it in the json response.
EDIT:
Here is a working example, to add post category and tag link to the api response, only for the get request:
add_action( 'rest_api_init', 'wp_rest_insert_tag_links' );
function wp_rest_insert_tag_links(){
register_rest_field( 'post',
'post_categories',
array(
'get_callback' => 'wp_rest_get_categories_links',
'update_callback' => null,
'schema' => null,
)
);
register_rest_field( 'post',
'post_tags',
array(
'get_callback' => 'wp_rest_get_tags_links',
'update_callback' => null,
'schema' => null,
)
);
}
function wp_rest_get_categories_links($post){
$post_categories = array();
$categories = wp_get_post_terms( $post['id'], 'category', array('fields'=>'all') );
foreach ($categories as $term) {
$term_link = get_term_link($term);
if ( is_wp_error( $term_link ) ) {
continue;
}
$post_categories[] = array('term_id'=>$term->term_id, 'name'=>$term->name, 'link'=>$term_link);
}
return $post_categories;
}
function wp_rest_get_tags_links($post){
$post_tags = array();
$tags = wp_get_post_terms( $post['id'], 'post_tag', array('fields'=>'all') );
foreach ($tags as $term) {
$term_link = get_term_link($term);
if ( is_wp_error( $term_link ) ) {
continue;
}
$post_tags[] = array('term_id'=>$term->term_id, 'name'=>$term->name, 'link'=>$term_link);
}
return $post_tags;
}
I believe that your only way is to change your API in a way that it returns in the first call everything you need and not only the ids, or create a new service in the API.
If you send an id and recieve the data of the post is not a way of doing that to various post in a single call.
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.
dunno if this is possible at all.. I'm trying to query a large set of data with relations like so:
Parent::with([
'child' => function($query) {
$query->('published', '=', true);
$query->with('child.of.child', 'some.other.child');
$query->chunk(400, function($childs) {
// how is it now possible to add the $childs to the parent result??
});
}
]);
$parent = [];
Parent::with(
[
'childs' => function ($query) use (&$parent) {
$query->where('STATUS', '!=', 'DELETED');
$query->with('some.child', 'some.other.child');
$parent['models'] = $query->getParent()
->getModels();
$query->chunk(
400, function ($result) use ($query, &parent) {
$query->match($parent['models'], $result, 'child-relations-name');
});
}
])
->get();
Now $parent['models'] contains the tree with all the nested child relations... Dunno if this is the smartest way to do so, but it works for now.
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);