Getting Error with result - php

success: function(response){
$('#ul').html("");
var obj = JSON.parse(response);
public function autocomplete(){
$search = $this->input->post('search');
$query = $this->get_apartments($search);
echo json_encode ($query);
}
public function get_apartments($search)
{
$query = [
'val' =>'*',
'table' => 'tbl_apartments as apt',
'where' => [],
'orderby' => 'apt.id',
'orderas' => 'desc',
'in_value'=> '',
'like' => ['likeon' => 'apt.apt_no', 'likeval' => $search]
];
$datasss = [
['table' => 'coach as bd' , 'on' => "bd.bd_code = apt.bd_code", 'join_type'=>'inner']
];
$result = $this->common->datasss_with_in($query,$multijoin);
}
When I am Using To print_r($result); exit; to see the result it
showing me the result but when i commented this line its showing me
that obj is null... why this happening

get_appartments() should return something:
return $result;
so $query will get a value.
check what you receive in javascript using
console.log(response);
success: function(response) {
$('#ul').html('');
for(var $i=0;$i<$response.rows.length;$i++) {
$('#ul').append('<li>' + response.rows[$i].building_name + '<li>');
}
}

i found the answer i need to return $result['rows]; simple solution cos json not accepting complete inm y case

Related

Looping through validation data received from Ajax in laravel controller

I am sending a json request through Ajax, this request contains multiple objects,I am trying to find a way to validate the request to fail if at least one particular attribute fails the rule(min 5 characters in "value"); but dosent seems to work, can anyone help ?
I tried to loop data , I feel I am close but still dosent work.
my Ajax:
-------
< script >
function ajaxUpdate() {
var formdata = document.getElementsByTagName('input');
var formT = [].map.call(formdata, function(input) {
if (input.style.textDecoration === "line-through") {
input['completed'] = "1"; //add key value pairs
} else {
input['completed'] = "0"; //add key value pairs
}
return {
'value': input.value,
'id': input.id,
'completed': input.completed
}; //determine what keys to show.
});
formT.shift(); // Removes the first element from an array, because it contains token
formT = formT.filter(function(e) {
return e != null; //remove null elements.
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// e.preventDefault();
$.ajax({
url: "/updateAddTask",
dataType: "json",
contentType: "application/json",
data: {
objJSON: JSON.stringify(formT),
},
success: function(response) {
if ($.isEmptyObject(response.error)) {
if (response.success === true) {
successSweetAlert();
} else {
alert(JSON.stringify(response.errors.value.toString()));
}
}
},
// location.reload();
})
}
</script>
My controller:
--------------
public function loopData(Array $data)
{
foreach ($data as $key => $jsons) {
foreach ($jsons as $key1 => $value) {
return $jsons;
}
}
}
public function ajaxUpdateTasks(Request $request)
{
$data = json_decode($request->objJSON, true);//this will give an array of all the input elements
// dd($data);//output is below:
// array:3 [
// 0 => array:3 [
// "value" => "kilo"
// "id" => "55"
// "completed" => "0"
// ]
// 1 => array:3 [
// "value" => "new123"
// "id" => "793"
// "completed" => "1"
// ]
// 2 => array:3 [
// "value" => "ef4"
// "id" => "794"
// "completed" => "0"
// ]
//]
$rules = [
'value' => 'required|max:255|min:5', //value is
];
$messages = [
'value.max' => 'Todo title should be less than 255 characters',
'value.min' => 'Todo title should be more than 4 characters'
];
$validator = Validator::make($this->loopData($data),$rules, $messages);// ?????
if ($validator->fails()) {
$errors = $validator->getMessageBag()->toArray();
$result = ['success' => false, 'errors' => $errors];
return response()->json($result);
} else {
$result = ['success' => true, 'errors' => null];
$count = count(json_decode($request->objJSON, true));
$id = json_decode($request->objJSON, true)[0] ['id'];
$value = json_decode($request->objJSON, true)[0] ['value'];
$completed = json_decode($request->objJSON, true)[0] ['completed'];
-----remaining of the code --------
}
Thanks for any help.
I solve it by simply changing rules and messages: $rules = [ " *.value" => 'min:4', ]; $messages = [ " *.value.max" => 'Todo title should be less than 255 characters', " *.value.min" => 'Text should be more than 4 characters' ]; $validator=Validator::make($data, $rules,$messages);

Change response format of REST API

I'm working on my REST API responses with PHP.
Here is my backend that generates the responses:
$query = $this->db->query("SELECT some_params from some_table ");
$result = $query->result();
foreach($result as $row){
$obj[] = array(
'title' => $row['title'],
'price' => $row['price'],
);
}
print_r(json_encode($obj));
and with that I have the following response: an array of json objects
[
{
"title":"Marketing",
"price":"0"
},
{
"title":"SAP B1",
"price":"10"
}
]
What I would like to do is return a new object, something like this:
{
"apiVersion": "2.0",
"data": {
{
"title":"Marketing",
"price":"0"
},
{
"title":"SAP B1",
"price":"10"
}
}
}
Does anyone have any idea how I could implement this? thanks!
You can easily have a class or function to do that for you. Some thing like below should help,
// provided you are using php > 7 . otherwise parmas
// can become $data, $apiversion ( without typecasting )
function api_reponse(array $data, string $apiVersion)
{
return json_encode([
'apiVersion' => $apiVersion,
'data' => $data
])
}
You can then use,
$query = $this->db->query("SELECT some_params from some_table ");
$result = $query->result();
foreach($result as $row){
$obj[] = array(
'title' => $row['title'],
'price' => $row['price'],
);
}
print_r( api_response($obj, '2.0') );

Laravel: Add Pagination to Json Response

I have an array for showing users' contacts list to each other.
I want to add ->paginate(10) features for json response but I could not find where I must put it.
My index function:
public function index()
{
$contacts = [];
$user = request()->user();
// Loop through the contacts and format each one
Contact::for($user->id)->get()->each(function ($contact) use ($user, &$contacts) {
$friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1;
$contacts[] = $friend->toArray() + ['room' => $contact->room->toArray()];
});
return response()->json($contacts);
}
You can create a collection for the contact and use LenfthAwarePaginator
class ContactResourceCollection extends ResourceCollection
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request
* #return array
*/
public function toArray($request)
{
$response = [
'data' => $this->collection,
];
if($this->resource instanceof LengthAwarePaginator)
{
$response['pagination'] = [
'total' => $this->resource->total(),
'lastPage' => $this->resource->lastPage(),
'perPage' => $this->resource->perPage(),
'currentPage' => $this->resource->currentPage(),
'nextPageUrl' => $this->resource->nextPageUrl(),
'previousPageUrl' => $this->resource->previousPageUrl(),
];
}
return $response;
}
}
In the controller method add this line:
return new UserResourceCollection($users);
Here is the total code
$contacts = Contact::where('user_id', $user->id)->paginate(12);
if($contacts->count()){
$pageIndex = array();
$lastPage = $contacts->lastPage();
$user = request()->user();
for($i= 2; $i<=$lastPage; $i++){
array_push($pageIndex, $i);
}
return response()->json([
'contacts' => $contacts->map(function ($contact) use ($user) {
if($contact->user1_id === $user->id){
return [
'friend' => $contact->user2,
'room' => $contact->room,
];
} else {
return [
'friend' => $contact->user1,
'room' => $contact->room,
];
}
})->toArray(),
'per_page' => $contacts->perPage(),
'on_first_page' => $contacts->onFirstPage(),
'last_page' => $contacts->lastPage(),
'first_page_url' => $contacts->url(1),
'next_page_url' => $contacts->nextPageUrl(),
'prev_page_url' => $contacts->previousPageUrl(),
'last_page_url' => $contacts->url($contacts->lastPage()),
'total' => $contacts->total(),
'pageIndexArray' => $pageIndex,
'errors' => false,
]);
} else {
// Do Nothing
}
Call
GET 'URL?page='+Page_index to get the response in JS (AJAX)
I am not sure but try : replace get() to paginate(10)
Contact::for($user->id)->paginate(10)->each(function ($contact) use ($user, &$contacts) {
$friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1;
$contacts[] = $friend->toArray() + ['room' => $contact->room->toArray()];
});
Can you change the query into:
$contacts = Contact::for($user->id)->paginate(10);
Then after this query you can use for loop for $contact;
foreach ($contacts as $key => $contact)
{
$friend = $contact->user1_id === $user->id ? $contact->user2 : $contact->user1;
$contacts[] = $friend->toArray() + ['room' => $contact->room->toArray()];
}
Paginate first before get into loop/each.

How to return the fetched data back to my view?

How to return the fetched data (in this case: $arr) back to my view
(which I can manipulate like displaying in a table).
If I have this in my controller action processed via ajax:
public function actionFetchregularload(){
$criteria = new CDbCriteria;
$criteria->limit = 15;
$criteria->condition='semester = 2';
$criteria->select = array('subjCode','subjDesc','lec','lab','units');
$criteria->addSearchCondition('yrLvl', $_GET['yrlevel']);
$data = CompeProspectusA::model()->findAll($criteria);
$arr = array();
foreach ($data as $item){
$arr[] = array(
'subjcode' => $item->subjCode,
'subjdesc' => $item->subjDesc,
'lab' => $item->lab,
'lec' => $item->lec,
'units' => $item->units,
);
}
}
Make a view with your table or something else and use renderPartial() in your actionFetchregularload() like this:
$this->renderPartial('_table', array('arr'=>$arr), false, true);
In your main view you can use CHtml::ajaxLink with options (where "#contentdiv" is id of your table div):
CHtml::ajaxLink(
"Update table",
Yii::app()->createUrl('controller/fetchregularload'),
array( //ajaxOptions
'type' => 'POST',
'beforeSend' => "function(request) {
$('#contentdiv').addClass('loading'); //add .loading class while loading - you can add background image
}",
'success' => "function(data) {
$('#contentdiv').removeClass('loading');
document.getElementById('contentdiv').innerHTML=data;
}",
),
//htmlOptions
array('href' => Yii::app()->createUrl('controller/fetchregularload'));
);

How to use PHP function parameter inside array?

I am trying to declare a function parameter inside my array, but I'm having trouble getting it to work. I've trimmed it down for simplicity purposes, and I have something like:
function taken_value($value, $table, $row, $desc) {
$value = trim($value);
$response = array();
if (!$value) {
$response = array(
'ok' => false,
'msg' => "This can not be blank."
);
} else if (mysql_num_rows(
mysql_query(
"SELECT * FROM $table WHERE $row = '$value'"))) {
$response = array(
'ok' => false,
'msg' => $desc." is already taken."
);
} else {
$response = array(
'ok' => true,
'msg' => ""
);
}
echo json_encode($response);
}
Notice the function parameter $desc trying to be used in the array here:
'msg' => $desc." is already taken.");
The whole function works fine EXCEPT when I try to add the $desc to the array results.
How could this be done?
Do you have an open resource handle to your database? You are not passing one to the query function.

Categories