Json return value show from Angular Js - json

Angular Js Script
this.http.post(url, body, options)
.subscribe((data) =>
{
if(data.status === 200)
{
this.hideForm = true;
this.sendNotification(console.log(data.meesage));
}
});
PHP Code
How to get json_encode success message through this.sendNotification()
$sql = "INSERT INTO eastcost_school_room(school_room_name, created) VALUES(:name, Now())";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
echo json_encode(array('message' => 'Congratulations the record ' . $name . ' was added to the database'));
}

map the response before subscribing
this.http.post(url, body, options)
.map((res:Response) => res.json());
.subscribe((data) =>
{
if(data.status === 200)
{
this.hideForm = true;
this.sendNotification(console.log(data.meesage));
}
});

Php code
$sql = "INSERT INTO eastcost_school_room(school_room_name, created) VALUES(:name, Now())";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$response["success"] = 1;
$response["message"] = 'Congratulations the record ' . $name . ' was added to the database';
// echoing JSON response
echo json_encode($response);
Post method in the api service class
Service
insert(parameters): Observable<any> {
return this.http.post('url', body, {
headers: headers
})
.map((res: any) => res.json())
}
And subscribe the response from your class
this.service.insert(parameters)
.subscribe(
response => {
console.log(response);
if (response.success == "1") {
console.log("Successfull login");
}
else {
alert(" Invalid user");
}
},
error => {
alert(error);
}
);

Related

can't post data to Laravel API from flutter dio pakage Formdata

i had a problem on my RESTAPI. i'm working with backend that makes the API, but i can't post data to the server. due to the error that appears on my debug console. here's the REST-API end-point source code.
`
class PeminjamanController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$data = Peminjaman::all();
return response()->json(['Data User : ', PeminjamanResource::collection($data) ], Response::HTTP_OK);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request, $id)
{
try {
//code...
$data = Request()->all();
if( $id == 1) {
$validator = Validator::make($request->all(),[
'dosen_id' => 'required',
'matkul_id' => 'required',
'spo_id' => 'required'
],[
'dosen_id.required' =>'Dosen Tidak Boleh Kosong',
'matkul_id.required' =>'Mata kuliah Tidak Boleh Kosong',
'spo_id.required' =>'Tindakan Tidak Boleh Kosong',
]);
if($validator->fails()){
return response()->json($validator->errors(),
Response::HTTP_UNPROCESSABLE_ENTITY);
}
$pinjam = new Permintaan();
$pinjam->id = Uuid::uuid4()->getHex();
$pinjam->kd_permintaan = $data['kd_peminjaman'];
$pinjam->user_id = Auth::user()->id;
$pinjam->dosen_id = $data['dosen_id'];
$pinjam->matkul_id = $data['matkul_id'];
$pinjam->spo_id = $data['spo_id'];
$pinjam->tgl_minta = Carbon::now();
$pinjam->diserahkan = NULL;
$pinjam->aprovals = "Belum";
$pinjam->status = "Menunggu Persetujuan";
// $pinjam->keterangan = NULL;
$pinjam->save();
foreach($request->barang_id as $key => $barang){
$stok = Barang::findOrFail($barang);
if ($request->jumlah[$key] > $stok->stok) {
return response('[200] - Maaf Stok Barang Melewati Batas');
}else{
DetailPinjam::create([
'id' => Uuid::uuid4()->getHex(),
'permintaan_id' => $pinjam->id,
'kondisi_id' => 2,
'barang_id' => $barang,
'jumlah' =>$request->jumlah[$key],
'fix_jumlah_kembali' =>$request->jumlah[$key],
]);
$stokpinjam = $stok->stok - $request->jumlah[$key];
$stok->update([
'stok' => $stokpinjam,
]);
$response = [
'success' => true,
'message' => 'Peminjaman Created',
'data' => $pinjam
];
return response()->json($response, Response::HTTP_CREATED);
}
}
}elseif ($id == 2 ){
Request()->validate([
'dosen_id' => 'required',
'matkul_id' => 'required',
'spo_id' => 'required',
'tgl_kembali' => 'required',
],[
'dosen_id.required' =>'Dosen Tidak Boleh Kosong',
'matkul_id.required' =>'Mata kuliah Tidak Boleh Kosong',
'spo_id.required' =>'Tindakan Tidak Boleh Kosong',
'tgl_kembali.required' =>'Tanggal Pengembalian Tidak Boleh Kosong',
]);
$data = Request()->all();
$pinjam = new peminjaman();
$pinjam->id = Uuid::uuid4()->getHex();
$pinjam->kd_peminjaman = $data['kd_peminjaman'];
$pinjam->user_id = Auth::user()->id;
$pinjam->dosen_id = $data['dosen_id'];
$pinjam->matkul_id = $data['matkul_id'];
$pinjam->spo_id = $data['spo_id'];
$pinjam->tgl_pinjam = Carbon::now();
$pinjam->tgl_kembali = $data['tgl_kembali'];
$pinjam->diserahkan = NULL;
$pinjam->aprovals = "Belum";
$pinjam->status = "Menunggu Persetujuan";
$pinjam->keterangan = NULL;
$pinjam->save();
foreach($request->barang_id as $key => $barang){
$stok = Barang::findOrFail($barang);
if ($request->jumlah[$key] > $stok->stok) {
return response('[200] - Maaf Stok Barang Melewati Batas');
}else{
DetailPinjam::create([
'id' => Uuid::uuid4()->getHex(),
'peminjaman_id' => $pinjam->id,
'barang_id' => $barang,
'jumlah' => $request->jumlah[$key]
]);
$stokpinjam = $stok->stok - $request->jumlah[$key];
$stok->update([
'stok' => $stokpinjam,
]);
$response = [
'success' => true,
'message' => 'Peminjaman Created',
'data' => $pinjam
];
return response()->json($response, Response::HTTP_CREATED);
}
}
}
} catch (QueryException $e) {
//throw $th;
return response()->json([
'message' => "Failed" . $e->errorInfo
]);
}
}
`
and here the dart dio push method.
`
Kirim() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var token = localStorage.getString('access_token');
try {
var data = FormData.fromMap({
'kd_peminjaman': kodepruduct,
'user_id': id_pengguna,
'dosen_id': dosendrop,
'matkul_id': matakuliahdrop,
'spo_id': spodrop,
//'tgl_minta': '${tanggal.day}.${tanggal.month}.${tanggal.year}',
'tgl_kembali':
'${tanggalkembali.day}.${tanggalkembali.month}.${tanggalkembali.year}',
'[barang_id][]': {
[id]
},
'[jumlah[]]': {
[jumlah]
},
});
var dio = Dio();
dio.options.headers['Authorization'] = 'Bearer $token';
//dio.options.headers['Content-Type'] = 'multipart/form-data';
dio.options.headers['Accept'] = 'application/json';
dio.options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
var response = await dio
.post('http://silk.polindra.ac.id/api/peminjaman/2', data: data);
print(response.statusMessage);
} catch (e) {
print(e);
}
}
`
and i got response from the rest-api method like this.
i have tried to change the atribute on the FormData. on the array
barang[]: [id], jumlah[]: [jumlah]
to jsonEncode method
barang[]: jsonEncode([id]), jumlah[]: jsonEncode([jumlah])
and these too
[barang[]]: [id]], [jumlah[]: [jumlah]]
and the last
barang[]: {[id]}, jumlah[]: {[jumlah]}
all of refactoring atrribut i made, doesn't give any effect, all of method give the same error message
can some one help me.. plz...
sorry for my bad english.. i'm not usually spoken english in my country.
actually, the reason you get this issue is related to your API code on line 164 it suppose to string but it's returning an array. to check which parameter making an issue you can simply diedump by
dd($request->all());
and test it from the postman

croogo 2 Request blackholed due to "auth" violation

I have a problem with my old website. Now I try to move it to new server (php5.6) and when i try to save data I have error:
Request blackholed due to "auth" violation.
I serach the place whose do it this error:
if ($this->Node->saveWithMeta($this->request->data)) {
Croogo::dispatchEvent('Controller.Nodes.afterAdd', $this, array('data' => $this->request->data));
$this->Session->setFlash(__('%s has been saved', $type['Type']['title']), 'default', array('class' => 'success'));
if (isset($this->request->data['apply'])) {
$this->redirect(array('action' => 'edit', $this->Node->id));
} else {
$this->redirect(array('action' => 'index'));
}
}
I think error do function saveWithMeta(). This function view like:
public function saveWithMeta(Model $model, $data, $options = array()) {
$data = $this->_prepareMeta($data);
return $model->saveAll($data, $options);
}
Can I replace/edit this function so that it starts to work?
edit
if (!$db->create($this, $fields, $values)) {
$success = $created = false;
} else {
$created = true;
}
These lines cause an error.

Send mail on actionCreate

I have a system that works by the intranet and I would like to know how best to send an alert email in actionCreate?
I did as below, the email is sent correctly, but if the internet is offline an unfriendly error message appears.
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
} else {
// error in saving model
}
}
return $this->render('create', [
'model' => $model,
]);
}
Try this (don't save model if email not sended)
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
$transaction = $model->getDb()->beginTransaction();
try{
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
}
}
catch(Exception $e)
{
$transaction->rollBack();
throwe $e;
//unlik savedFile if exist
}
}
return $this->render('create', [
'model' => $model,
]);
}
or use mail queue to save mail in databases and send via cron

Unable to make Ajax call in Symfony

I want to handle user registration via ajax call. So therefore I've created a registration class (defined as a service) which will be loaded in different controllers:
public function loadRegisterForm($request)
{
$user = new User();
$form = $this->createForm(RegistrationType::class, $user, array('attr' => array('class' => 'ajaxRegisterForm',)));
$form->handleRequest($request);
$errors = "";
$parametersArray['result'] = "";
if ($form->isSubmitted())
{
if ($form->isValid())
{
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$user->setIsActive(1);
$user->setLastname('none');
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$parametersArray['result'] = new JsonResponse(
array(
'message' => 'Success! User registered!',
'result' => $this->renderView('ImmoBundle::security/successlogin.html.twig')
), 400);
}
else
{
$errors = $this->get('validator')->validate($form);
$parametersArray['result'] = new JsonResponse(
array(
'message' => 'Failure! User not registered!',
'result' => $this->renderView('ImmoBundle::security/successlogin.html.twig'),
'errors' => $errors,
), 200);
}
}
$parametersArray['register_form'] = $form;
$parametersArray['errors'] = $errors;
return $parametersArray;
}
Then I've created a main controller, where registration form is being loaded:
/*
* #Route("/", name="MainPageNotPaginated")
*/
public function indexAction(Request $request)
{
/**
* Load register form
*/
$registerForm = $this->get('register_form_service');
$registerFormParameters = $registerForm->loadRegisterForm($request);
return $this->render(
'ImmoBundle::Pages/mainPage.html.twig',
array(
'register_form' => $registerFormParameters['register_form']->createView(),
'errors' => $registerFormParameters['errors'],
'result' => $registerFormParameters['result'],
)
);
}
Further I've added an ajax call to my javascript file:
$('.registerFormContainer').on('submit', '.ajaxRegisterForm', function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
})
.done(function (data) {
if (typeof data.message !== 'undefined') {
$('.registerFormContainer').html(data.result);
}
alert('success');
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof jqXHR.responseJSON !== 'undefined') {
$('.registerFormError').html(jqXHR.responseJSON.result);
} else {
alert("fail");
}
});
});
Now, when I submit the registration form without filling in data (which normally should return an error) I've got an 'success' alert. The same 'success' alert is visible when the submitted registration form is valid.
I've tried
console.log(data.message)
but console says 'undefined'.
What am I doing wrong here?
Ok, I've figured it out. I've just added this line to my main controller (not the service one):
if ( $request->isXmlHttpRequest() ) {
return $registerFormParameters['result'];
}

Kohana 3.2 select issue

I have table with 'servers' name in my db. So when I want to add there some data with that code it's just ok:
public function action_add()
{
$serverGameId = (int)Arr::get($_POST, 'serverGameId', '');
$newServerName = Arr::get($_POST, 'newServerName', '');
try
{
$server = new Model_Server();
$server->Name = $newServerName;
$server->GameId = $serverGameId;
$server->save();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "serverId" => $server->Id));
return true;
}
Here is a model:
class Model_Server extends ORM {
protected $_table_name = 'servers';
public function rules()
{
return array(
'Name' => array(
array('not_empty'),
)
);
}
}
But I have problem when I try to select it from the table:
public function action_servers()
{
$gameId = (int)Arr::get($_POST, 'gameId', '');
if($gameId == -1) return false;
try
{
$servers = ORM::factory('server')
->where('GameId', '=', $gameId)
->find_all();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "servers" => $servers, "gameId" => $gameId));
return true;
}
I already try to solve problem with change code inside of try block on:
$servers = DB::select('servers')->where('GameId', '=', $gameId);
Even when I try just get all my servers from db without '->where' it's doesn't work.
Any ideas?
Try print_r($servers); inside try block to see what you get from model.
And $servers is some class with results - use foreach to get result (one by one)
$results = array();
foreach($servers as $row) {
//echo $row->Name;
$results[] = $row->Name;
}
Or
$results = array();
foreach($servers as $row) {
//echo $row->as_array();
$results[] = $row->as_array();
}