Laravel 500 Internal Server Error Ajax - javascript

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);
});
});

Related

Show progress of controller action in HTML as text

I am building .NET Core application and I want to change the text on the website based on the progress of controller actions. I wrote a short example below showing what I want to achieve. Some things are written in pseudo-code.
HomeController.cs
public class HomeController : Controller
{
private readonly IHomeService _homeService;
public HomeController(IHomeService homeService)
{
_homeService = homeService;
}
public IActionResult Detail(int id)
{
_homeService.ShowInfo(id);
return View(model);
}
HomeService.cs
public void FirstFunction()
{
// write "Fetching results from database"
...
// write "Results fetched successfully"
}
public void SecondFunction()
{
// write "Parsing results"
...
// write "Results parsed successfully"
}
public string ShowInfo(int id)
{
FirstFunction();
SecondFunction();
return "Success!";
}
functions.js
$(document).ready(function() {
$.ajax({
'url' : 'Home/Detail',
'type' : 'GET',
'data' : {
'id' : 123
},
'success' : function(data) {
// update some html element based on "write" commands in
// FirstFunction() and SecondFunction()
}
});
}
How can I update HTML elements on web page with strings which FirstFunction and SecondFunctions "write"? The operations are quite long and I want to give the user some sort of information about what is happening right now.

How can I use c# asp.net to get data from url?

I'm trying to get some info I sent by form to angularJS in my c# asp.net backend, and I'm having trouble doing it.
Visual Studio won't let me compile because it says:
Error CS0120: an object reference is required for the nonstatic field, method, or property 'member'
That's is my controller
public class SearchController : ApiController
{
public string Get()
{
string test = HttpContext.Request.QueryString["txt_search"];
return test;
}
}
Here's what I got in my angularjs:
$scope.sendForm = function () {
console.log($scope.model.search);
$http({
method: 'GET',
url: '/api/search?txt_search=' + $scope.model.search
})
.then(function () {
console.log('sucesso a executar o post');
}, function () {
console.log('Erro ao executar o post');
});
};
As suggested in the comments, you should just be able to change your method definition and skip this altogether:
public string Get(string txt_search)
{
return txt_search;
}
Alternatively, to reference the current request, I believe you need to use the following (note the addition of .Current):
string test = HttpContext.Current.Request.QueryString["txt_search"];
The reason is that HttpContext defines Request as an instance property. The only public static property is Current, which returns an instance of HttpContext through which you can reach Request.
Welcome to Stack Overflow,
Your Angular code is correct
You need to pass a parameter on server side to collect txt_search value
Here it is:
[HttpGet]
[Route("/api/search")]
public string mySearchMethod(string txt_search)
{
//something here with txt_search
return "OK";
}
Both of the above solution will work, but for another approach as you are using asp.net web api and router you can make it as below as well
In your Angular code, simple pass the search as below
```
$scope.sendForm = function () {
console.log($scope.model.search);
$http({
method: 'GET',
url: '/api/search/'+ $scope.model.search
})
.then(function () {
console.log('sucesso a executar o post');
}, function () {
console.log('Erro ao executar o post');
});
};
```
Notice
url: '/api/search/'+ $scope.model.search
and change the Action method as below
```
[HttpGet]
[Route("/api/search/{txt_search}")]
public string mySearchMethod(string txt_search)
{
//something here with txt_search
return "OK";
}
```
by doing this you don't have to worry about the name of the parameter txt_search
whatever you mention in route [Route("/api/search/{txt_search}")], you will get the value in same parameter.

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.

sessions in Angularjs

Im building an login with angularjs and PHP. The problem I have is that the session not seem to have been set.
I have this controller that uses a service when I hit the login button:
Controller:
$scope.doLogin = function() {
loginService.login({username: $scope.username, password: $scope.password});
};
Here is my services:
'use strict';
angular.module('gameApp_services').factory('sessionService', ['$http', function($http) {
return {
set:function(key, value) {
return sessionStorage.setItem(key,value);
},
get:function(key) {
return sessionStorage.getItem(key);
},
destroy:function(key) {
$http.post('lib/destroy_session.php'); //Förstör sessionen
return sessionStorage.removeItem(key);
}
};
}]).factory('loginService', function($http,$location,sessionService) {
return {
login: function(data, scope) {
var $promise = $http.post("lib/action.php", data); //send data to action.php
$promise.then(function(msg) {
var uid = msg.data;
console.log(uid);
if(uid) {
//scope.msgtxt='Correct information';
sessionService.set('sess_id', uid);
$location.path('/game');
} else {
scope.msgtxt='Incorrect information';
$location.path('/firstpage');
}
});
},
logout:function() {
sessionService.destroy('sess_id');
$location.path('/firstpage');
},
islogged:function() {
var $checkSessionServer = $http.post('lib/check_session.php');
return $checkSessionServer;
/*if(sessionService.get('user')) {
return true;
}*/
}
}
});
As you can see, I'm making a call to my backend, where I check the username and password, and set's the session. The uid that is returned, contains the sessionID=1:
public function DoLogin($username, $password)
{
//Kolla så att användarnamn och lösenord är korrekt, returnera true eller false
$get_user = "SELECT id, username,password FROM users WHERE username='".$username."' AND password='".$password."'";
$user_result = mysql_query($get_user)
or die(mysql_error());
if(mysql_num_rows($user_result) == 1)
{
$_SESSION['sess_id'] = mysql_result($user_result, 0);
$_SESSION['sess_user'] = $username;
return $_SESSION['sess_id'];
}
else
{
return false;
}
}
This works, the correct data is returned back as expected, thus, the session id 1.
In my app.js I have code that prevents you from going to the /game page by typing it in the URL:
gameApp.run(function($rootScope, $location, loginService) {
var routespermission=['/game']; //route that require login
$rootScope.$on('$routeChangeStart', function() {
if(routespermission.indexOf($location.path()) !=-1)
{
var connected = loginService.islogged();
connected.then(function(msg) {
console.log(msg);
if(!msg.data) {
$location.path('/');
}
});
}
});
});
As you can see, Im using my loginService here, where I'm refering to islooged in the service. In islogged I make a call to my PHP backend, check_session.php, where I check if the session exists:
<?php
session_start();
if(isset($_SESSION['sess_id'])) {
echo "authentified";
}
?>
This returns an empty string, the session is not set. When I try var_dump($_SESSION), the result is NULL.
How can this be possible, when I set the session in my backend when I log in, and the resulting value is 1?
Are you sure you want to operate session with angular?
Session is store at browser and server,when you start a request by angular,session will be carried by request header automatically, and you can verify it with you php function at backend, so I think you should check your php code to confirm if session store is avaliable or your broswer can store session by cookies or session store

Ajax get caused in 500 Internal Server Error

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

Categories