I am using MEAN JS, i am trying to edit the list items on the list page, but it shows the error as below. i have initiated the data using ng-init="find()" for the list and ng-init="findOne()" for individual data.
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
HTML
Below i the form inside the controller where it initiates the find() and findOne().
<div ng-controller="OrdersController" ng-init="find()">
<div>
<div class="order-filter">
<div ng-repeat="order in orders">
<form ng-init="findOne()" name="orderForm" class="form-horizontal" ng-submit="update(orderForm.$valid)" novalidate>
<input type="text" class="" ng-model="order.title">
<input type="text" class="" ng-model="order.content">
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
Controller
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'orderForm');
return false;
}
var order = $scope.order;
order.$update(function () {
$location.path('orders/' + order._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function () {
Orders.query(function loadedOrders(orders) {
orders.forEach(appendFood);
$scope.orders = orders;
});
};
$scope.findOne = function () {
$scope.order = Orders.get({
orderId: $stateParams.orderId
});
};
You need to check your Orders Service which probably is using $resource to provide your API requests (Orders.query)
It should look something like this:
function OrdersService($resource) {
return $resource('api/orders/:orderId', {
orderId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
The style may be different depending on which version of mean you're using. By default, the $resource query will expect an array of results, but if for some reason you've set "isArray" to false then it will expect an object.
https://docs.angularjs.org/api/ngResource/service/$resource
Related
I am new to js and would like to convert my JQuery-based js to Vue. I want to send a get request and output back the data. What is the best way of doing this?
Here is the html:
<div>
<div>
<input type="text" id="var1" placeholder="Search...">
</div>
<div>
<button id="submit">Submit</button>
</div>
</div>
<div>
<p>Results</p>
<p id="results"></p>
</div>
Below is my js:
$(document).read(function() {
$('#var1').keypress(function(e) {
if (e.keyCode == 13)
('#submit').click();
});
});
$(document).ready(function() {
$("#submit").click(function() {
var var1 = document.getElementById("var1").value
// sends get request to URL
$.getJSON("URL" + var1, function(search, status) {
console.log(search);
// cont.
$("#results").text(search.results);
});
});
});
EDIT: Here is what I have so far with axios:
function performGetRequest() {
var var1 = document.getElementById('var1').value;
axios.get('URL', {
params: {
id: var1
}
})
.then(function (response) {
console.log(search);
})
}
I am not sure if the above code is correct or how to factor in keypress and click-- is there a simple way to do that?
Well, I am not sure what you want to do with this ajax call, but hopefully this may help you. Vue is data driven, so I always try to focus on that aspect. So this is an example of how you can access and input and send the data using axios.
<div>
<div>
<input v-model='input' type="text" placeholder="Search...">
</div>
<div>
<button #click="searchInput()">Submit</button>
</div>
</div>
<div>
<p>Results</p>
<p >{{ result }}</p>
</div>
you must have those models in your data
// Your data
data() {
return {
input: '',
result: '',
}
}
and your method will look something like this.
searchInput() {
axios({
method: 'GET',
url: url + this.input,
}).then(response => {
this.result = response.data;
}).catch(error => {
//handle error
})
}
So this is a very basic example. you can do the same process in different ways, you could pass the input to the method or loop over the results, but the idea is taking advantage of Vue.js data driven system and think data first.
Hopefully this will help you, remember to escape your input and add necessary validations. Good luck
Struggling to get http:get to pull a request from a API server in an Ionic app, can anyone help with the code. Here is what I have:
<form ng-submit="getOrders()">
<label class="item item-input item-stacked-label">
<span class="input-label">Search Order #</span>
<input type="text" name="order number" placeholder="enter order number" ng-model="query">
</label>
<input class="button button-block button-positive" type="submit" name="submit" value="Submit">
</form>
$scope.getOrders= function(){
$http.get('http://example.com/api/booking/orders/'+ $scope.query).success(function(data) {
$scope.orders = [ data.data ];
$scope.query = query;
console.log(query);
})
}
Here are a few http get code blocks I have tried without success
//$http.get('http://example.com/api/booking/get/orders/').success(function(data) {
//$http({ url: 'http://example.com/api/booking/orders/', method: "GET", params: {query} }).success(function(data) {
//$http.get('http://example.com/api/booking/get/orders/+ $scope.query').success(function(data) {
//$http.get('http://example.com/api/booking/get/orders/121137').success(function(data) {
//$http.get('js/121137.json').success(function(data) {
Also, here is an example of some working POST code to an API which may provide some extra clues in performing a successful GET query from an API server:
https://plnkr.co/edit/w0cyfzGij8SgcsnbXqsj?p=catalogue
use promise as follows
.then(function(success){
//handle success
})
.catch(function(error){
//handle error
})
this is currect code.
$scope.getOrders= function(){
$http.get('http://example.com/api/booking/orders/'+$scope.query).success(function(data) {
$scope.orders = data.data;
console.log(data);
console.log($scope.query);
})
}
i am new to angularJS and trying to figure out, how to post data to my server, problem is that my post to server is successful and it create new record but all is empty(null).
Thanks for any advice
JS:
$scope.addChannel = function () {
var channels = [];
//var newChannel = {
// Name: $scope.Name
//};
//clearing error message
$scope.errorMessage = "";
$http.post("api/Channel/channels", newChannel)
.success(function (newChannel) {
//on success
$scope.channels.push({ "Name": $scope.Name });
console.log("data added");
// newChannel.push(response.data);
newChannel = {};
}, function () {
//on failure
$scope.errorMessage = "Failed to save data";
})
}
HTML:
<div ng-controller="ChannelController">
<div class="col-md-4 col-lg-4 col-sm-4">
<form novalidate name="newUser"ng-submit="addChannel()">
<div class="form-group">
<label for="name">Channel</label>
<input class="form-control" type="text" id="Name" name="Name" ng-model="newChannel.Name" />
</div>
<div class="form-group">
<input type="submit" value="Add" class="btn btn-success" />
</div>
</form>
<a ng-href="/Dashboard#/channels">Return to dashboard</a>
</div>
<div class="has-error" ng-show="errorMessage">
{{errorMessage}}
</div>
Channel Controller
[HttpPost("channels")]
public async System.Threading.Tasks.Task Create(Channel channel)
{
await _channelRepository.CreateChannel(channel);
}
Repository
public async System.Threading.Tasks.Task CreateChannel(Channel channel)
{
_context.Channel.Add(channel);
await _context.SaveChangesAsync();
}
Check if you name properties correctly in object that you send to server, property names are case sensitive. Looks like you have in js
var customer = {name: 'foo', lastName: 'bar'};
and on server you try to deserialize your JSON to this entity
class Customer {
public Name {get;set;} //note prop names are capitalized
public LastName {get;set;}
}
I am using angularFire and trying to save data from a form to firebase with $add. Any help would be greatly appreciated. The console logs all work, I am able to retrieve the data in the console. Sorry for all of the code... I wanted to be sure I provided all the material needed.
app.js:
var creativeBillingApp = angular.module('creativeBillingApp', ['ngRoute', 'firebase']);
creativeBillingApp.constant('FIREBASE_URI', "https://XXXX.firebaseIO.com/");
creativeBillingApp.controller('MainCtrl', ['$scope', 'groupsService', function( $scope, groupsService, $firebase ) {
console.log('Works')
$scope.newGroup = {
name: '',
status: ''
};
$scope.addGroup = function(newGroup){
console.log(newGroup);
groupsService.addGroup();
$scope.newGroup = {
name: '',
status: ''
};
};
$scope.updateGroup = function (id) {
groupsService.updateGroup(id);
};
$scope.removeGroup = function(id) {
groupsService.removeGroup(id);
};
}]);
creativeBillingApp.factory('groupsService', ['$firebase', 'FIREBASE_URI',
function ($firebase, FIREBASE_URI) {
'use strict';
var ref = new Firebase(FIREBASE_URI);
return $firebase(ref).$asArray();
var groups = $firebase(ref).$asArray();
var getGroups = function(){
return groups;
};
var addGroup = function (newGroup) {
console.log(newGroup)
groups.$add(newGroup);
};
var updateGroup = function (id){
groups.$save(id);
};
var removeGroup = function (id) {
groups.$remove(id);
};
return {
getGroups: getGroups,
addGroup: addGroup,
updateGroup: updateGroup,
removeGroup: removeGroup,
}
}]);
index.html:
<form role="form" ng-submit="addGroup(newGroup)">
<div class="form-group">
<label for="groupName">Group Name</label>
<input type="text" class="form-control" id="groupName" ng-model="newGroup.name">
</div>
<div class="form-group">
<label for="groupStatus">Group Status</label>
<select class="form-control" ng-model="newGroup.status">
<option value="inactive">Inactive</option>
<option value="active">Active</option>
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
This is the error I am getting:
TypeError: undefined is not a function
at Scope.$scope.addGroup (http://localhost:9000/scripts/app.js:35:19)
and the app.js line 35 is in reference to groupsService.addGroup(); from the app.js code given above.
Firstly, you are returning in your service after you create your $FirebaseArray. You are also creating another $FirebaseArray after that.
return $firebase(ref).$asArray();
Remove that return statement. That is causing your service to return early and none of the attached methods will apply to your service.
In groupService.addGroup() you are calling push, which is not a function on $asArray. You need to call .$add(). The newGroup argument is also not being passed in the controller.
The $.push method is available on the base of the $firebase binding. When you using a $FirebaseArray the $add method pushes a new record into Firebase.
See the docs for more info.
Plunker Demo
var addGroup = function (newGroup) {
console.log(newGroup)
groups.$add(newGroup);
};
Then in your controller you can simply call:
$scope.addGroup = function(newGroup){
groupsService.addGroup(newGroup);
$scope.newGroup = {
name: '',
status: ''
};
};
Hi i've got a durandal app that send data trought ajax but i dont know how to implement the loading indicator , here is the codes:
this is the view that loads the data
loadinbox.html
<div class="modal-content messageBox">
<div class="modal-header">
<h3>LOGIN</h3>
</div>
<div class="modal-body">
<h3>Entre com suas credenciais.</h3>
<form data-bind="submit: ok">
<input type="text" data-bind="value: login" placeholder="CPF" class="form-control autofocus" />
<input type="text" data-bind="value: senha" placeholder="Senha" class="form-control autofocus" />
</form>
</div>
<div data-bind="if: $parent.loading">
<img src="img/loading.gif"/>
</div>
<div class="modal-footer">
<button class="btn btn-success" data-bind="click: ok, active: $parent.loading">Login</button>
</div>
</div>
this is the model that loads the data
loginBox.js
define(function (require) {
var dialog = require('plugins/dialog');
var loading = ko.observable();
var loginBox = function(){
this.login = '';
this.senha = '';
this.loading = false;
};
loginBox.prototype.ok = function () {
this.loading =true;
$.ajax({
type: "post",
data: { "LoginForm[cpf]" : this.login, "LoginForm[password]" : this.senha , 'ajax':'login-form' },
url: localStorage['baseurl']+localStorage['router']+'site/login',
success: function (data){
console.log(data);
},
error: function (request, status, error){
console.log(request.status);
console.log(status);
console.log(error);
},
complete: function (data) {
alert('hqweuiqhioehqio');
this.loading =false;
}
});
};
loginBox.show = function() {
return dialog.show(new loginBox());
};
return loginBox;
});
On the surface, your approach is sound, but your approach to modules in Durandal is a little muddled. For example, you've declared loading twice, once as a scalar and once as an observable.
So, let's create an instance module (which means that we're going to return a constructor function):
loginBox.html (view)
<div class="modal-content messageBox">
<div class="modal-header">
<h3>LOGIN</h3>
</div>
<div class="modal-body">
<h3>Entre com suas credenciais.</h3>
<form data-bind="submit: ok">
<input type="text" data-bind="value: login" placeholder="CPF" class="form-control autofocus" />
<input type="text" data-bind="value: senha" placeholder="Senha" class="form-control autofocus" />
</form>
</div>
<div data-bind="if: $parent.loading()">
<img src="img/loading.gif"/>
</div>
<div class="modal-footer">
<button class="btn btn-success" data-bind="click: ok, active: $parent.loading()">
Login
</button>
</div>
</div>
Notice that I changed your if binding to this:
"if: loading()"
referencing loading with parentheses. This performs an immediate eval using the default value supplied to the observable, and then a re-eval when the observable changes.
Also, it may be necessary to change "click: ok, active: $parent.loading()" to click: $parent.ok.bind($parent), active: $parent.loading(). Check your context using the debugger when the #ok function is entered.
A note on logic: It seems to me that what you might mean in the modal footer is
active: !$parent.loading()
Should the OK button really be active when the form is loading data?
loginBox.js (module instance approach)
define (
[
'plugins/dialog',
'knockout'
],
function (
dialog,
ko) {
var LoginBox = function () {
this.login = '';
this.senha = '';
this.loading = ko.observable(false);
};
LoginBox.prototype.ok = function () {
var _vm = this;
this.loading(true);
$.ajax( {
type: "post",
data: { "LoginForm[cpf]" : this.login, "LoginForm[password]" : this.senha , 'ajax':'login-form' },
url: localStorage['baseurl']+localStorage['router']+'site/login',
success: function (data) {
console.log(data);
},
error: function (request, status, error) {
console.log(request.status);
console.log(status);
console.log(error);
},
complete: function (data) {
alert('hqweuiqhioehqio');
_vm.loading(false);
}
});
};
LoginBox.prototype.show = function() {
dialog.show(this);
};
return LoginBox;
};
);
Take note of my treatment of this.loading. It is an observable, and observables are updated using the approach I show above (remember, they are functions). When you assign true in this manner--this.loading = true--you override the observable itself and turn it into a non-observable scalar. So, when the value later changes (from false to true to false), the view is not updated.
Also note that you must import KnockoutJS.
Another issue: you have a this reference issue in your #complete function. Note that I do this at the top of your #Ok function:
var _vm = this; //Some people are inclined to this format: var that = this;
and, then, in your #complete function, I do this:
_vm.loading(false);
Using this in your #complete function references the #complete function itself, not the viewModel. We have to save a reference to this outside the #complete function.
There was another problem: #show was not on the prototype.
I use a utility called Block UI
in my App JS file I call it like this using the Global Ajax setup.
By doing it this way you only do it once and then every Ajax call will show your loading gif and hide when any Ajax calls starts and finishes
HTML:
in the index.html page(your main page)
<div id="throbber" style="display:none;">
<img src="/images/gears.gif" />
</div>
Javascript
$(document).ready(function () {
$.blockUI.defaults.css.border = 'none';
$.blockUI.defaults.css.backgroundColor = 'transparent';
$.blockUI.defaults.message = $('#throbber');
$.blockUI.defaults.showOverlay = true;
$.blockUI.defaults.overlayCSS.backgroundColor = "#fff";
$(document).ajaxStart(function () {
$.blockUI();
}).ajaxStop(function () {
$.unblockUI();
});
});
CSS:
#throbber{
border:1px solid #346789;
padding: 15px;
background-Color: #fff;
-moz-border-radius:0.5em;
border-radius:0.7em;
opacity:0.8;
filter:alpha(opacity=80);
color: #000 ;
width:133px;
height:133px;
left: 50%;
top: 40%;
position: fixed;
}