Ajax get caused in 500 Internal Server Error - javascript

I have two Ajax Get Request:
$.get('/tutorials/rate', {id: {{$tutorial->id}}}, function (data) {
$ratingCount = data;
});
$.get('/tutorials/rateAverage', {id: {{$tutorial->id}}}, function (data) {
$averageRating = data;
});
in my Controller:
public function get_rate() {
$postId = Input::get('id');
$ratings = rating::where('tutorial_id', '=', $postId)->get();
return count($ratings);
}
public function get_rateAverage(){
$postId = Input::get('id');
}
in my routes:
Route::controller('tutorials', 'TutorialController');
First Request is workin like a charm, second one gives me a 500 Error...

On your second get request, try
$.get('/tutorials/rate-average', {id: {{$tutorial->id}}}, function (data) {
$averageRating = data;
});
Your function names should be getRate() and getRateAverage()
This is what Laravel expects as far as naming conventions. Please see http://laravel.com/docs/controllers#resource-controllers

Related

Laravel 500 Internal Server Error Ajax

I am developing a website using Laravel and Ajax. I have a problem when I try to return all messages (Messages model) that belong to specific user (User model) using hasMany method.
web.php
Route::get('/test', 'UserController#testFunction');
Route::post('/test', 'UserController#testFunction');
UserController.php
public function testFunction(Request $request) {
if ($request->isMethod('post')) {
$messages = User::find(1)->messages;
return $messages;
} else {
return 'get method';
}
}
User model
class User extends Authenticatable {
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function messages() {
$this->hasMany('App\Message', 'from');
}
}
Message model
class Message extends Model {
protected $fillable = [
'from', 'to', 'content'];
}
Then I have two buttons (just for testing - POST and GET). They are handled by this JavaScript code
window.onload = function() {
// AJAX Setup
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Post Method
$('#postMethod').click( function() {
$.post('test', function (data) {
console.log(data);
});
});
// Get Method
$('#getMethod').click(function() {
$.get('test', function(data) {
console.log(data);
});
});
}
Tables in the databse have a structure as shown below:
users table
messages table
When I click on POST button (handled by above javascript code), I receive this error in console: error in console
If I change $messages = User::find(1)->messages; to $messages = User::find(1)->name;, for example, I get the name of the user with ID 1 returned to the console normally.
I assume that something is wrong with messages() function in UserController.php. Maybe 'from' as foreign key? This is just my guess, maybe the error is somewhere else, please take a look yourself.
Here is your fix, you need to call messages like this messages() that will return relationship instance.
public function testFunction(Request $request) {
if ($request->isMethod('post')) {
$messages = User::find(1)->messages();
return $messages;
} else {
return 'get method';
}
}
Hope this helps.
test with /.
Try this
// Post Method
$('#postMethod').click( function() {
$.post('/test', function (data) {
console.log(data);
});
});
// Get Method
$('#getMethod').click(function() {
$.get('/test', function(data) {
console.log(data);
});
});

Single Angular Controller w/ multiple $HTTP Get request

I have two mongoose schemas running in on my server end. I would like to add two $http.get request in my app.js and eventually display two tables from my collection in MongoDB on a webpage. Only one get function is called without errors.
server.js
//Data Schema
var tempSchema = new mongoose.Schema({
topic: String,
message: Number,
when: Date
}, {collection: "temperature"});
var humiditySchema = new mongoose.Schema({
topic: String,
message: Number,
when: Date
}, {collection: "humidity"});
var temperature =mongoose.model('temperature', tempSchema);
var humidity =mongoose.model('humidity', humiditySchema);
app.js
app.controller("FormController", function ($http, $scope){
$http.get("/api/temperature")
.then(function (response) {
$scope.temperatures = response.data;
});
})
app.controller("FormController", function ($http, $scope){
$http.get("/api/humidity")
.then(function (response) {
$scope.humiditys = response.data;
});
})
Also thinking of how I can display both collections on the webpage. Using ng-repeat. Unfortunately I cannot paste my HTML code here.
I would appreciate any help I can get. Thanks
Another way you could handle the $http requests is by creating an Angular Factory.
angular.module('myApp.services',[])
add.factory('ApiService', function($http) {
return {
getHumidity: function() {
return $http.get("/api/humidity");
},
getTemperature: function() {
return $http.get("/api/temperature");
}
}
})
Then inside your controller, you should do the following (Note that you must inject the factory as a dependency for the controller)
angular.module('myApp.controllers',[])
.controller("FormController", function (ApiService, $scope){
function getHumidity() {
var promise = ApiService.getHumidity();
promise.then(
function(response) {
$scope.humiditys = response.data;
},
function(errorPayload) {
console.log(errorPayload);
});
};
function getTemperature() {
var promise = ApiService.getTemperature();
promise.then(
function(response) {
$scope.temperatures = response.data;
},
function(errorPayload) {
console.log(errorPayload);
});
};
getHumidity();
getTemperature();
})
then where you define your angular App (app.js in most of the cases):
angular.module('myApp', ['myApp.controllers','myApp.services'])
.run(...)
.config(...)
...

Didn't get json array in App js file

My service code look like belowed :-
data.service('SmartLearnerService', function ($http) {
//Get Single Records
this.get = function (id) {
return $http.get("/api/Category/");
}
});
Here is my controller code for App.js:-
$scope.questionlist = SmartLearnerService.get();
$scope.questionlist.then(function (pl) {
var res = pl.data;
$scope.que = res.QuestionLabel;
},
function (errorPl) {
console.log('failure loading Employee', errorPl);
});
console.log($scope.questionlist);
Here is Controller code for web api controller :-
public class CategoryController : ApiController
{
CommonDb db = new CommonDb();
public JsonResult Get()
{
var Result = db.GetQuestionById().ToList();
string message = "No Data Found";
if (Result.Count() != 0)
{
return new System.Web.Mvc.JsonResult()
{
Data = Result,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
}
else
{
return new System.Web.Mvc.JsonResult()
{
Data = message,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
}
}
}
}
And here is div tag where i want to bind questions from json result using ng-repeat directive.
<div class="question" align="center">{{Questions.QuestionLabel}}</div>
i am facing problem while binding json array in controller's $scope.questionlist and i am successfully getting json result from web api controller.
Ok, if I had to guess (and that's exactly what I'm doing), you want something like this in your controller...
SmartLearnerService.get().success(function(questions) {
$scope.questionList = questions;
});
or, if you're not a fan of the add-on success / error callbacks
SmartLearnerService.get().then(function(response) {
$scope.questionList = response.data;
});
and in your template
<div ng-repeat="question in questionList">
<div class="question" align="center">{{question.QuestionLabel}}</div>
<!-- and so on -->
</div>
This is totally assuming your C# controller returns JSON that looks something like...
[{
"QuestionID": "1",
"QuestionLabel": "Why are mirrors often slightly curved (convex) ?",
"Image": "zibra-crossing.jpg",
"Correct": "two",
"Explaination": "Question one explaination is goes here"
}, {
...
}]
Can you try this?
SmartLearnerService
.get()
.success(function (data, status) {
if (status === 200) {
//your code to process data is here
}else{alert(status)}
})
.error(function (data, status) {
//TODO: Use nice alert.
alert('Server request failed with status ' + status + ' while getting area in the ' + $item.Name);
});
You will get the status code that you are receiving and then you can change the code accordingly.
The approach that I took in my case was to serialize using JsonConvert from NewtonSoft and then return the string of Json object instead of Json object itself to improve the speed.

How to pass an object to AngularJS factory?

I am in edit state i am trying to update riskDto but i am getting an error about some object i dont know what i am doing wrong please help.
Code tried so far...
ctrl.js
RiskService.saveAllignRiskToProcess($scope.riskDTO,$stateParams.processKey).then(function (response) {
if ($scope.editMode) {
$scope.hideYesBtn = true;
$scope.hideNoBtn = true;
$scope.showOkBtn = true;
$scope.messageText = 'Updated Risk Within Process successfully';
$scope.confirmationWin.open().center();
$scope.okCallback = $scope.riskAlignToProcessBack;
}
}
});
facotry.js
saveAllignRiskToProcess: function(processKey) {
return $http.post('app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey);
}
state.js
.state('createAndAlignRisk', {
url: '/risk/cnaRsk/:processKey',
templateUrl: 'views/risk/createNewRisk.html',
controller: 'RiskCtrl',
data: {
authenticate: true
}
})
consoleError
/riskTocontrol/saveCreateAndAlignNewRiskToProcess/[object%20Object]
If you want to pass both object $scope.riskDTO , $stateParams.processKey to service then the your service method needs to be change along with caller method code
Code
RiskService.saveAllignRiskToProcess($scope.riskDTO,$stateParams.processKey)
.then(function (response) {
//..code here
});
Service
saveAllignRiskToProcess: function(processKey, riskDTO) {
var url = 'app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey
return $http.post(url ,JSON.stringify({ 'serverSideParamName': riskDTO}) );
}
From angularjs doc
post(url, data, [config]);
data - Request content
The Data parameter is necessary that you can see from a documentation. You missed it in:
saveAllignRiskToProcess: function(processKey) {
return $http.post('app/risk/rest/riskTocontrol/saveCreateAndAlignNewRiskToProcess/' + processKey);
}

Angularjs $http.get not working

on my server side (ASP.ne MVC) I have method which looks like this:
[HttpGet]
public JsonResult GetTrenings(string treningId)
{
var tempId = Guid.Parse(treningId);
var trening = TreningService.GetTreningById(tempId);
_trenings = TreningService.GetAllTreningsForUser(trening.UserId);
return Json(_trenings, JsonRequestBehavior.AllowGet);
}
And I have Angular service :
publicApp.angularModule.factory('feedSingleTreningService', function ($q, $http) {
return {
getTrenings: function (data) {
var input = $http.get("/Feed/GetTrenings", { params: { treningId: data } });
var deferred = $q.defer();
deferred.resolve(input);
return deferred.promise;
},
};
});
And In my Controller I call this service like this:
feedSingleTreningService.getTrenings(data).then(function(results) {
console.log("test", results);
});
But nothing is shown in console, I've debugged server side and request reaches it, and it returns _trenings, also service returns promise, but nothing happens.
I've changed then to finally, and in console "test" was shown but results were undefined.
Why is this happening ?
You don't need to defer your call to $http because it already returns a promise.
Just return
return $http.get("/Feed/GetTrenings", { params: { treningId: data } });
then anything that calls your function can do:
getTrenings(myData).then(function(data) { do something }).fail(function() { error });

Categories