I have already searched the web but most 500 Errors tend to be for the "POST" ajax type.
I am trying to get some data from my server using Ajax method.
My script is as follows
<script type="text/javascript">
function getuserinfo(id) {
var userID = id;
console.log(userID);
if(userID) {
$.ajax({
url: '/guestinfo/ajax/'+userID,
type: "GET",
dataType: "json",
success:function() {
$('#infoModal').modal('show');
}
});
}
};
</script>
My Route is as follows
Route::get('/guestinfo/ajax/{guest_id}','Controller\Control#getInfo');
My controller is as follows
public function getInfo($id)
{
if($request->ajax())
{
$guestid = $id;
$guest = Guest::where('id', '=', $guestid)->firstOrFail();
return json_encode($guest);
}
}
Error log from console
Any help or guidance will be appreciated.
You should use return response()->json($guest); to return json data instead of return json_encode($guest);
And the error is because of the $request is not defined that should be an instance of Request $request in your method.
public function getInfo(Request $request, $id)
{
if($request->ajax())
{
$guestid = $id;
$guest = Guest::where('id', '=', $guestid)->firstOrFail();
return response()->json($guest);
}
}
You should be checking your log files so you can actually see what is causing the 500 error, always.
Just by going off of your code that you have pasted you are trying to use an undefined variable as an object:
$request->ajax()
That variable, $request, is undefined in the scope of that method.
Related
I have this ajax method in PostsController
public function ajax(Request $request)
{
//dd($request);
$this->authorize('view', Post::class);
$posts = Post::orderBy("created_at","desc")->paginate(5);
$comments = Comment::all();
return response()->json(array("posts"=> $posts, "comments"=> $comments), 200);
}
which works great when you just getting data and sending it.
So i tried besides requesting data by ajax, to send some data alongside ajax request. How can i access that data inside controller?
Here is a method which resides inside certain blade:
function ajax(){
let var1 = "gg";
let var2 = "bruh";
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let url = '/posts';
$.ajax({
type: "POST",
url: url,
headers:
{
'X-CSRF-TOKEN': token
},
data: {
'var1': var1,
'var2': var2
},
success: function(data) {
console.log(data);
}
});
}
To simplify: How can i, dd() or dump(), given data(var1 & var2) by ajax function from blade in PostsController?
Here is route:
Route::post('/posts', "PostsController#ajax");
And here is some "gibberish" when i try to dd() it:
dd() is a laravel function and dump()for php. so you cannot use them from javaScript.
You cannot dd() or dump() from direct ajax request or JavaScript.
What you can do is, console log your data, or check from browser developer portion, network tab to see which data you are getting from the ajax response. You can find browser developer portion in,
for chrome:
Insepect > Network
for mozila:
Insepect Element > Network
If you are telling about get var1 and var2 on controller, you can just get them by $request->var1 and $request->var2.
Hasan05 was right. Just needed to know right direction. So to get data parameter of ajax request i modified ajax controller method:
public function ajax(Request $request)
{
$var1 = $request->input('var1');
$var2 = $request->input('var2');
$this->authorize('view', Post::class);
$posts = Post::orderBy("created_at","desc")->paginate(5);
$comments = Comment::all();
return response()->json(array("posts"=> $posts, "comments"=> $comments, "var1"=> $var1, "var2"=> $var2), 200);
}
I'm trying to set axios request but always getting missing argument, but not sure how can I pass it can someone explain why this wont work?
my route: (web.php)
Route::post('/api/setSuccessMessage', 'API\SessionsController#setSuccessMessage');
my controller: (Controllers/API/SessionsController.php)
class SessionsController extends Controller
{
public static function setSuccessMessage($key, $value)
{
session()->put($key ,$value);
}...
and my vueJS axios call (resources/assets/components/Login.vue)
created: function () {
// check is user logged out
axios.post('/api/setSuccessMessages', {message: 'message',message2: 'message2'}).then((response)=> {
console.log(response);
})
},
Use :
public static function setSuccessMessage(Request $request)
{
$key = $request->get('message');
$value = $request->get('message2');
session()->put($key ,$value);
}
If you want to send the data as a part of your request body you can do so like
axios.post('/api/setSuccessMessages', {message: 'message',message2: 'message2'})
.then((response)=> {
console.log(response);
}
)
//you then accept them as such
Route::post('/api/setSuccessMessage/{message}/{message2}', 'API\SessionsController#setSuccessMessage');
If you wish to send the data as a request params (everything after ? in the url) you can do so like this
var params = {
message1: message1,
message2: message2
};
axios.post('/api/setSuccessMessages', {}, {'params': params})
.then((response)=> {
console.log(response);
}
)
//you then accept them as such
Route::post('/api/setSuccessMessage', 'API\SessionsController#setSuccessMessage');
//You can further use them as such in controller
function public test(Request $request) {
$request->get('message1');
$request->get('message2');
}
I'll reference axios official docs for the axios request params
I can not get the response from the controller with Ajax,what should I do?:
$("document").ready(function(){
$("#send").click(function(e){
e.preventDefault();
var question = $("input[name=question]").val();
$.ajax({
type: "POST",
url : "/Admin/question/store?token={{$t}}",
data : {'question':question},
success : function(data){
alert(data);
console.log(data);
}
});
});
});
and in the controller I just want to return a string for testing:
public function store(Request $request)
{
return "success";
}
For you to get the response in AJAX you must print the data, is it being print after the return? if not, try :
public function store(Request $request)
{
echo "success";
}
I solved it,
First problem was URL,I changed it to:
{!! route('store') !!}
And did not know to write my route in api!!!! instead of web
I'm new here :). I have a problem with my code. I'm working with laravel 5.1 and Blade. In my view I have:
function getNumber(){
values = [];
values[0] = $('#receipt_type_id').val();
values[1] = $('#provider_id').val();
$.ajax({
url: "{{{ url('receipts/showByNumber') }}}",
type: "get",
data: {ids: values},
dataType: "json",
success: function (data) {
//i do something
}
});
}
In my route:
Route::get('receipts/showByNumber', ['as' => 'receipt.showByNumber', 'uses' => 'ReceiptsController#showByNumber']);
And in my controller:
public function showByNumber($values){
$receipt_type_id = $values[0];
$provider_id = $values[1];
//Find the receipt to edit
...
...
}
The error is GET http://manchego.app/receipts/showByNumber?ids%5B%5D=1&ids%5B%5D=2 500 (Internal Server Error). I read another topics with the same problem that I have but I can't understand where is my problem.
Thanks in advance! :)
You could type-hint the Request class (recommended):
public function showByNumber(\Illuminate\Http\Request $request)
{
$allParams = $request->all(); // returns an array
$provider_id = $request->get('provider_id');
}
Or you could use the Request facade:
public function showByNumber()
{
$allParams = \Request::all(); // returns an array
$provider_id = \Request::get('provider_id');
}
I have an ajax call in my code. What I want to achieve with the call works fine. I want to delete some records from the database which is actually deleted when the method is called via ajax but as in symfony method it must return a response and thats why when the method is executed its gives me the error
My Ajax call is
$.ajax({
type: "POST",
data: data,
url:"{{ path('v2_pm_patents_trashpatents') }}",
cache: false,
success: function(){
document.location.reload(true);
}
});
And the method that is executed is
public function trashpatentAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("pid");
$em = $this->getDoctrine()->getEntityManager();
$patent_group = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')->find($id);
if($patent_group){
$patentgroup_id = $patent_group->getId();
$em = $this->getDoctrine()->getEntityManager();
$patents = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')
->findBy(array('patentgroup' => $patentgroup_id));
if($patents){
foreach($patents as $patent){
if($patent->getIs_deleted()==false){
$patent->setIs_deleted(true);
$em->flush();
}
}
}
$patent_group->setIs_deleted(true);
$em->flush();
}
else{
$em = $this->getDoctrine()->getEntityManager();
$patent = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')->find($id);
if ($patent) {
$patent->setIs_deleted(1);
$em->flush();
}
}
return true;
}
}
How can I successfully return from this method ?
Any ideas? Thanks
Replace return true; with return new Response();. Also don't forget to write use Symfony\Component\HttpFoundation\Response; at the top.
You can also pass error code 200 and the content type like below.
return new Response('Its coming from here .', 200, array('Content-Type' => 'text/html'));
Here is the full example of the controller
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class WelcomeController extends Controller
{
public function indexAction()
{
return new Response('Its coming from here .', 200, array('Content-Type' => 'text/html'));
}
}