I want to save some var to my session, and when i make the request with ajax this dont work.
This is the service:
function HuntService( $http ) {
this.hunts= {
draws : null,
hunters: null
};
this.saveToSession = function( hunts) {
var hunts = this.hunts;
return $http.post('saveToSession', {
hunts: hunts
});
};
}
HuntService.$inject = ['$http'];
module.exports = HuntService;
and the controller:
class HuntController extends \BaseController {
public function saveItems() {
Session::put('hunts', Input::get('hunts'));
return Response::json(array('saved' => true), 200);
}
public function destroy($id) {
Session::forget('hunts');
}
public function getHunts() {
return Session::get('hunts') // dont exits
}
}
And when im trying as test to get to this with regular request and no ajax its working.
The problem is here:
var hunts = this.hunts;
Here, this.hunts does not exist.
NOTE:
Use Inspect Element/Debug tool for inspecting the request & check whether it is sending any value for hunts attribute in post method or just blank. The laravel part looks ok.
Related
in my application I have my JS file that reads some info filled in the html page. What I want to do now I passing these info to my controller. So in my script I have:
function addNewEmployee() {
var newEmployeeName = document.getElementById("newEmployeeName").value;
var newEmployeeSurname = document.getElementById("newEmployeeSurname").value;
var newEmployeeDateOfBirth = document.getElementById("newEmployeeDateOfBirth").value;
var newEmployeeRole = document.getElementById("newEmployeeRole").value;
var newEmployeeEmail = document.getElementById("newEmployeeEmail").value;
var newEmployee = {
name : newEmployeeName,
surname: newEmployeeSurname,
dateOfBirth: newEmployeeDateOfBirth,
role: newEmployeeRole,
email : newEmployeeEmail
}
$.post("api/addemployees", {'newEmployee': newEmployee}, function(result) {
});
}
I would like to know if passing an object in this way is correct and then how can I receive it on my controller side:
[HttpPost]
[Route("api/addemployees")]
public bool AddEmployee (Object newEmployee)
{
return true;
}
Unfortunately by debugging on the controller side I realized that this way is not correct because nothing arrives. How can I solve this? Thanks in advance.
Just pass the object like
$.post("api/addemployees", JSON.stringify(newEmployee), function(){
})
I have a page where I want to display user's posts paginated. For back-end I use Laravel's resource controllers and on the front-end Restangular services.
So back-end implementation looks like this:
// url is /users/0/posts
public function index(Post $post)
{
return $post->whereUserId(\Auth::id())->paginate(20);
}
Front-end looks like this:
/*
* posts.service.js
*/
angular.module('app.services')
.service('posts', Posts);
Posts.$inject = ['Restangular'];
function Posts(Restangular) {
return Restangular.service('posts', Restangular.one('users', 0));
}
/*
* posts.controller.js
*/
angular.module('koodzo.controllers')
.controller('PostsController', PostsController);
ContentController.$inject = ['posts'];
function PostController(posts) {
var vm = this;
vm.posts = posts.getList()
.then(function(response) {
vm.pagination = response;
vm.posts = response.data;
});
}
So, obviously, this doesn't work, because Restangular's getList expects to receive an array from the server to restangularize it, but Laravel's paginator returns an object and the array is in the data field of the object.
The question is how to make Restangular see that response.data is the array that it needs?
In order to make Laravel's paginated response work with Restangular's getList(), you need to register a response interceptor that will return whatever you get in response.data as response.
The following code will do the trick:
app.module('yourModule').config(function(RestangularProvider) {
RestangularProvider.addResponseInterceptor(parseApiResponse);
function parseApiResponse(data, operation) {
var response = data;
if (operation === 'getList' && data.data) {
response = data.data;
response.metadata = _.omit(data, 'data');
}
return response;
}
});
Your calls to getList() will give you the data object directly. Additionally, you'll be able to access the pagination metadata that Laravel returns - it will be stored in metadata property of your response.
I have a SharePoint App that is built with AngularJS.
I have a controller that is calling a function in a service and it is not returning a value. I am pretty new at angularJS so I am a bit lost.
My Service:
App.factory('uploadAppService', function () {
return {
currentUserPic: function (myProfileProp) {
GetUserProfileInfo(myProfileProp).done(function (data) {
//The large thumbnail pic.
var picUrl = data.d.PictureUrl;
var largePicUrl = picUrl.replace('MThumb', 'LThumb');
console.log(largePicUrl) //the log here is correct. I want to return the largePicUrl back to my controller.
return largePicUrl;
});
}
My Controller call, I want to populate .imageUrl with the url from the service:
$scope.imageUrl = uploadAppService.currentUserPic("PictureUrl");
Thank you in advance.
To me, your currentUserPicfunction doesn't seem to return a value. GetUserProfileInfo indeed returns your largePicUrl, but this value is not used anywhere (if I correctly understand your code).
Shouldn't you use return GetUserProfileInfo(myProfileProp).done(...); ?
Edit: But as RaviH pointed, if the call is asynchronous, you'll still have to handle it in your controller.
I don't see implementation of your GetUserProfileInfo service, but i suppose it's a Deffered object.
So after code
$scope.imageUrl = uploadAppService.currentUserPic("PictureUrl");
finished working - you don't have anything in you variable $scope.imageUrl because your factory function does not return anything.
So, at first you need to modify your factory:
App.factory('uploadAppService', function () {
return {
currentUserPic: function (myProfileProp) {
return GetUserProfileInfo(myProfileProp).done(function (data) {
// ^
// Here - #ababashka's edit
//The large thumbnail pic.
var picUrl = data.d.PictureUrl;
var largePicUrl = picUrl.replace('MThumb', 'LThumb');
console.log(largePicUrl) //the log here is correct. I want to return the largePicUrl back to my controller.
return largePicUrl;
});
}
Return Deffered Object, so after it finished working, you could save your image URL by getting it in the response.
After you need to write next code:
uploadAppService.currentUserPic("PictureUrl").done(
function (response) {
$scope.imageUrl = response;
}
);
to store your URL in $scope's variable.
I currently have an issue with a webapi call. I want to download and open a logfile with my ApiController.
I use a javascript function to post a filename to my controller.
Here is a helper function to post the parameter (answer from dystroy):
How to replace window.open(...) with a POST
Now when I use a simple string as parameter in my controller I can’t get the parameter, it is always null.
public HttpResponseMessage PostDownloadLogFile([FromBody]string psFileName)
{
//psFileName is always null
But if I use HttpReqeustMessage as parameter and read the form data from my request it is no problem and it works.
public HttpResponseMessage PostDownloadLogFile(HttpRequestMessage poRequest)
{
var loFormData = poRequest.Content.ReadAsFormDataAsync().Result;
string psFileName = loFormData["psFileName"]; //psFileName is set correct
Is there a solution to get the parameter with a simple parameter in my controller?
Update
This is my javascript helper function:
var loOpenWindow = function (psMethode, psUrl, poData, psTarget) {
var loForm = document.createElement("form");
loForm.action = psUrl;
loForm.method = psMethode;
loForm.target = psTarget || "_self";
if (poData) {
for (var lsKey in poData) {
var loInput = document.createElement("textarea");
loInput.name = lsKey;
loInput.value = typeof poData[lsKey] === "object" ? JSON.stringify(poData[lsKey]) : poData[lsKey];
loForm.appendChild(loInput);
}
}
loForm.style.display = "none";
document.body.appendChild(loForm);
loForm.submit();
};
Call it:
helper.openWindow("POST", apiRoutes.URLS.ApiPostDownloadLogFile, { "psFilename": $scope.data.showLogEntry.FullName });
There should be no problem from the client side code, because the controller methode with HttpReqeustMessage works without problems.
Here is the browser request:
Probably the problem is in your client code sending the data.
[FromBody] parameters must be encoded as =value
then, this does not work:
// Value will be null.
$.post('api/values', value);
// Value will be null.
$.post('api/values', { key: value });
But this work:
$.post('api/values', "=" + value);
Try to change your client code to send just =/path/to/your/file in the body.
Reference: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
Ok I found a solution.
If I use a class as parameter and a property with the given name, it seems to work.
public class Param
{
public string psFileName { get; set; }
}
And
public HttpResponseMessage PostDownloadLogFile(Param poParam)
{
string psFileName = poParam.psFileName; //psFileName is set correct
This is not really a simple parameter but I can live with this solution.
I am quite new to SignalR.
My first assignment is to make simple chat app.
I have been browsing and reading and finally made a page where you come and chat and it works fine.
Now I need to show a list of connected clients. To achieve this I have wrote the following code.
This is my HUB.
public class ChatHub: Hub
{
chatEntities dc = new chatEntities();
public void Send(string message,string clientName)
{
Clients.addMessage(message,clientName);
}
// I want to save the user into my database, when they join
public void Joined(string userId,string userName)
{
CurrentChattingUsers cu = new CurrentChattingUsers();
cu.ConnectionId = userId;
cu.UserName = userName;
dc.CurrentChattingUsers.AddObject(cu);
dc.SaveChanges();
Clients.joins(userId, userName);
}
// This will return a list of connected user from my db table.
public List<ClientModel> GetConnectedUsers()
{
var query = (from k in dc.CurrentChattingUsers
select new ClientModel()
{
FullName = k.UserName,
UserId = k.ConnectionId
}).ToList();
return query;
}
}
And thats it...Now what??
Am I going to the right direction? If, I am then how to call this methods from the view?
Some good suggestions will really help me out.
cheers
EDIT:
I have added the following script when the hub start
$.connection.hub.start(function () {
chat.getConnectedUsers();
});
This is the method that returns the client names in my Hub
public List<ClientModel> GetConnectedUsers()
{
var data = (from k in dc.Users
select new ClientModel()
{
FullName = k.UserName
}).ToList();
Clients.loadUsers(data);
return data;
}
in firebug i can see it returns something as follows;
{"State":{},"Result":[{"FullName":"mokarom","UserId":null}, {"FullName":"aka8000","UserId":null},{"FullName":"johnnyno5","UserId":null},{"FullName":"reza","UserId":null},{"FullName":"amyo","UserId":null},{"FullName":"rezatech","UserId":null}],"Id":"0","Error":null,"StackTrace":null}
But, how would I display that in my view??
EDIT:
this the complete view so far
<script type="text/javascript">
var chat;
var myClientName
$(document).ready(function(){
myClientName = '#Request.Cookies["ChatterName"].Value';
// Created proxy
chat = $.connection.chatHub;
// Assign a function to be called by the server
chat.addMessage = onAddMessage;
// Register a function with the button click
$("#broadcast").click(onBroadcast);
$('#message').keydown(function (e) {
if (e.which == 13) { //Enter
e.preventDefault();
onBroadcast();
}
});
// Start the connection
$.connection.hub.start(function () {
chat.getConnectedUsers();
});
chat.loadUsers = function (data) {
loadUsers(data);
};
});
function onAddMessage(message,clientName) {
// Add the message to the list
$('#messages').append('<div class="chatterName">' + clientName + ' </div><div class="chatterMessage"> ' + message + '</div><div class="clear">');
}
function onBroadcast() {
// Call the chat method on the server
chat.send($('#message').val(), myClientName);
$('#message').val('');
}
function loadUsers(data) {
$('#clientList').html(data.Result[0].FullName);
}
</script>
Problem: don't see anything here: $('#clientList').html(data.Result[0].FullName);
firebug says 'data is not defined'
JavaScript
var chats = $.connection.chatHub;
chats.loadUsers = function (data) { loadUsers(data); };
var connectedUserCount = 0;
$.connection.hub.start(function ()
{ chats.getConnectedUsers(); });
function loadUsers = = function (data) {
console.log(data); //so you can see your data in firebug.etc
//which signal r will have converted to json so you could try
var numberOfUsers = data.length;
}
Once hub is started chats would have all the public functions of your hub available as javascript functions. This is what the signalr/hubs creates using the best available connection method between client and server.
In reverse your C# hub will have access to any javascripts functions you setup, e.g.
Clients.loadUsers(query);
//add this to you server side just before you return query
ps - you might also consider using OnConnectedAsync, though of course you might still persist these. I'm also waiting for full support for web farm support using sql, which is in the pipeline.