Backbone.js model.save() function unsuccessful - php

I am newbie at Backbone and REST api. Here is my save function code:
this.model.save(this.model.attributes,
{
success: function (model) {
app.menuItems.add(model);
app.navigate('/w/backbone/', {trigger: true});
}
}
);
and here is my model:
var MenuItem = Backbone.Model.extend({
urlRoot: '/w/backbone/rest/items',
idAttribute: 'taskId',
defaults: {
category: 'Entreés',
imagepath: 'no-image.jpg',
name: ''
}
});
and here is my restful Api POST function :
function items_post()
{
// add an existing user and respond with a status/errors
$array=array(
'item_id'=>$this->post('id'),
'item_url'=>$this->post('url'),
'item_name'=>$this->post('name'),
'item_category'=>$this->post('category'),
'imagepath'=>$this->post('imagepath')
);
$this->main_model->add_item($array);
}

At the very least your API call needs to return the id of the newly created model and any attributes that were changed by the server.

Related

use dynamic params for axios requests

axios.get("/api/session/" + this.roomId)
Above is a snippet from my axios call that uses my api.php route ('/api/session/{id} that loads through the controller the requested specific room => /api/session/3 is room 3).
Currently, this snippet is harcoded and always uses integer 1 for 'this.roomId'.
I did that, in oder to check if my vue is even working fine.
My question is now, how am I able to use a dynamic param for my prop roomId?
so I can always say something like
.get/.post('url', $id) ?
If you're passing the roomId as a prop into the component then you need to handle the change in the parent component. For that I'd need a bit more context on where the room-ids come from and how you select the room-id there.
If you have this part down, then you'll want to watch changes on the roomId prop and re-fetch the data when ever it changes. You can do something like this in your room component:
<script>
import axios from 'axios'
const props: {
roomId: {
type: Number,
required: true
}
}
export default {
props,
data() {
return {
room: null
}
},
methods: {
async fetchRoom() {
try {
const response = await axios.get(`/api/session/${this.roomId}`)
this.room = response.data
} catch (err) {
// - handle error
}
}
},
watch: {
roomId: {
immediate: true // so it's executed when component is created
handler: function () {
this.fetchRoom()
}
}
}
}
</script>

Laravel 4.1.* AJAX response method

I'm trying to setup a simple POST method with AJAX, posting to a Laravel controller and processed.
The issue I am having is returning a response that the AJAX call understand and can use.
routes.php
Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController#processSupplierApplication');
AJAX stuff to get form data:
$('#supplierChainCheckForm').submit(function( event ) {
event.preventDefault();
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// As we're using the "csfrUnsafeMethod" of POST - we'll need to setup the csfr token to be passed between client and server:
$.ajaxSetup({
// This is standard before send method for the ajaxSetup() function:
beforeSend: function(xhr, settings) {
// If settings.type in $.ajax method is unsafe i.e., if it is 'POST' then we'll need to set X-CSRFToken in the xhr Request Header: omitted && sameOrigin(settings.url) currently;
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", $('meta[name="csrf-token"]').attr('content'));
}
}
});
// Get all the form inputs into an array:
var $inputs = $('#supplierChainCheckForm :input');
// We can now loop over all of the input names & values of the form:
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
$.ajax({
type: 'POST', //This will always be a post method for the supplier chain check form.
url: 'supply-us/application', //URL endpoint for the post form method: we'll set this to the controller function we're targeting.
data: { 'companyName': values['companyName'] ,'_token': '{{ csrf_token() }}'}
}).done(function(response) {
console.log(response.companyName);
});
});
ApplicationController.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication() {
if (!Input::get('companyName') == null) {
$company = Input::get('companyName');
return Response::json([ 'companyName' => $company ], 200);
} else {
$company = "No compnay specified";
return Response::json([ 'companyName' => $company ], 200);
}
}
}
However, combining all of the above gives me
console.log(response.companyName) as "undefined"
Please advise. Please note, I am using Laravel 4.1.*
Update function parameter as below;
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $request) {
if (!$request->input('companyName') == null) {
$company = $request->input('companyName');
return Response::json([ 'companyName' => $company ], 200);
} else {
$company = "No compnay specified";
return Response::json([ 'companyName' => $company ], 200);
}
}
}

Understanding API response from Laravel 5 Dingo/Api Using AngularJs; What's the correct JSON Format

I am building an API for a Laravel 5 Web application using AngularJs App as API consumer.
Everything works perfectly except for the response returned from the API when a call is made from AngularJS.
Here is what I have in AngularJs App which also uses Satellizer
var app = angular
.module('app', [
'ngResource',
'ui.bootstrap',
'dialogs.main',
'ui.router',
'satellizer',
'ui.router.stateHelper',
'templates'
]);
app.config(['$httpProvider', '$locationProvider', '$stateProvider', '$urlRouterProvider', 'modalStateProvider', '$authProvider',
function($httpProvider, $locationProvider, $stateProvider, $urlRouterProvider, modalStateProvider, $authProvider)
{
var modalInstance,
modalExit = function() {
if (modalInstance) {
//alert('modalInstance exit');
modalInstance.close();
}
};
// Satellizer configuration that specifies which API
// route the JWT should be retrieved from
$authProvider.loginUrl = '/api/authenticate';
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
$stateProvider
.state('profile',{
url: '/profile',
views: {
'contentFullRow': {
templateUrl: 'ng/templates/profile/partials/profile-heading-one.html',
controller: function($scope, profile){
$scope.profile = profile;
}
},
'contentLeft': {
templateUrl: 'ng/templates/profile/partials/profile-body-one.html',
controller: function($scope, profile){
$scope.profile = profile;
}
},
'sidebarRight': {
templateUrl: 'ng/templates/profile/partials/todo-list-one.html',
controller: function($scope, profile){
$scope.profile = profile;
}
}
},
resolve: {
profile: function($http){
return $http.get('/api/profile').then(function(data){
//This is the issue, I am doing this because of the response returned
return data.data.profile;
});
}
}
});
if(window.history && window.history.pushState){
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
};
}]);
In my Laravel Controller
<?php namespace App\Http\Controllers\Profile;
use App\Http\Controllers\Controller;
use App\Models\Profile;
class ProfileController extends Controller
{
public function __construct()
{
$this->middleware('api.auth');
}
public function getIndex(){
$user = $this->auth->user();
return Profile::find($user->id);
}
}
Response from Laravel
The challenge I have is in the response above.
As you can see in the resolve method of Angular Ui Router,
To get the profile object from the returned JSON, I had to do this:
return $http.get('/api/profile').then(function(data){
return data.data.profile;
});
How do I make the API to return only profile object without config, header and other objects sent along? Are they really necessary? I would like to simply do this:
return $http.get('/api/profile').then(function(data){
return data; //which contains only profile object
});
Edited:
I think my question is; Is this the right JSON response Format from Dingo Api?
{
"config",
"data": {
"id": 1001,
"name": "Wing"
},
"headers",
"status",
"statusText"
}
Have you tried to return a response from the controller, not an Eloquent object:
http://laravel.com/docs/master/responses.
You can specify what exactly you need there (like profile).

How to call custom action in controller(laravel) using AngularJS

I am using laravel 5.
I have a custom action in my controller. By custom I mean it is not used by the resource object in angular. The following is the code of my controller.
class ServicesController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function extras()
{
// code here
}
}
This is my service code in the angular script.
(function() {
'use strict';
angular
.module('bam')
.factory('myservice', myservice);
function myservice($resource) {
// ngResource call to the API for the users
var Serviceb = $resource('services', {}, {
update: {
method: 'PUT'
},
extras: {
method: 'GET',
action: 'extras'
}
});
function getExtras(){
return Serviceb.query().$promise.then(function(results) {
return results;
}, function(error) {
console.log(error);
});
}
}
})();
Now, the query() here will send the request to the index method in the laravel controller. How will I access the extras() action in the getExtras() method?
It looks like you're almost there try out the example below I tried to use what you have in your question, and added a few other custom endpoints as examples. You'll want a base URL set up similarly to the example so you can feed it an id out of your payload so $resource can set up your base CRUD. Otherwise to make custom routes using the same resource endpoint you can add some extra actions like you have in your question, but apply your customization on the base endpoints URL.
.factory('ServicesResource', ['$resource',
function ($resource) {
// Parameters used in URL if found in payload
var paramDefaults = {
id: '#id',
param: '#param'
}
// Additional RESTful endpoints above base CRUD already in $resource
var actions = {
custom1: {
method: 'GET',
url: '/api/services/custom',
},
custom2: {
method: 'GET',
url: '/api/services/custom/:param',
},
extras: {
method: 'GET',
url: '/api/services/extras'
}
update: {
method: 'PUT'
}
}
// Default URL for base CRUD endpoints like get, save, etc
return $resource('/api/services/:id', paramDefaults, actions);
}])
Now you can dependency inject the factory and use it like this:
var payload = {param:'someParam'};
ServicesResource.custom(payload).$promise.then(function(response){
// handle success
}, function(reason) {
// handle error
});
Or for Extras:
ServicesResource.extras().$promise.then(function(response){
// Handle success
}, function(reason) {
// Handle error
});
In Laravel you're route might be something like this:
Route::get('services/{param}/custom', 'ServicesController#custom');
Or for extras like this:
Route::get('services/extras', 'ServicesController#extras');
I got what I wanted using $http.
function getExtras(){
return $http.get('/services/extras').success(function (results) {
return results;
});
}
But, that would be nice if anyone suggest me how to do it with Serviceb.query().$promise.then.

Angular ui-router resolve, http success, stateParams

My goal to achieve is:
first to insert new database record with http post, resolve with stateProvider and grab the new id and change view and stateParams.
i have this code for my http post service
myApp.service('postService', ['$http', function($http) {
this.insertNew = function() {
$http.post('create_new.php')
.success(function(data) {
return data;
});
};
create_new.php returns the ID like this (it works, proved with console)
return json_encode($data);
and the stateProvider looks like this (section)
$stateProvider
.state('newRecord', {
resolve: {
newArtID: ['postService',
function(postService) {
return postService.insertNew();
}]
},
params: {
artID: <-- new ID from DB
},
i did tests with stateParams in serval variations (in resolve and by params). how can i bring the new ID to stateParams, so i can access from the views?
Thanks for any help!
I'm not so sure your oder of operations is correct. params is for when you already have that data. You should return the data from your resolve, then you can access it in your scope, for ex:
Service:
.service('postService', function ($http) {
this.insertNew = function () {
return $http.post('create_new.php').then(function (data) {
return data;
});
}
})
Route:
$stateProvider
.state('newRecord', {
views: {
"main": {
controller: 'SomeCtrl',
templateUrl: '...'
}
},
resolvedId: {
newArtID: function (postService) {
return postService.insertNew().then(function (response) {
return response;
});
}
}
})
Controller:
.controller('SomeCtrl', function (resolvedId) {
var newID = resolvedId.id; //depending on what is returned
});

Categories