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']);
}
}
Related
i have taken the id and mobile_num from users table.i have to insert that id name in this table as user_id,mobile_num,and status(0,1) into another table(wc_sms_status).sendSMSFunction is working fine.
public function SendBulkSms()
{
$usersNumber = User::select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
}
elseif($userNumber->mobile_num == exist && status == 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
}
else{
}
}
}
Do this :
public function SendBulkSms()
{
//assuming there is a relationship between your model users and wc_sms_status called wcSmsStatus
$usersNumber = User::with('wcSmsStatus')->select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
'user_id' => $userNumber->id,
'mobile_num' => $userNumber->mobile_num,
'status' => 1,
]);
} elseif ($userNumber->mobile_num && $userNumber['wcSmsStatus']->status === 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
} else {
}
}
}
public function SendBulkSms()
{
$users = User::select('id','mobile_num')
->whereIn('id', [5,6,7,8])
->whereNotNull('mobile_num')
->get();
$bulkData = [];
foreach ($users as $user)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
$bulkData[] = [
'user_id' => $user->id,
'mobile_num' => $user->mobile_num,
];
}
if (!empty($bulkData)) {
WcSmsStatus::insert($education); // change to your model name
unset($bulkData);
}
}
try to use in this way, it will insert bulk data, dont fergot to mention protected $fillable[] in model
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 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.