Ajax data not getting into controller - ajax

I am using an ajax request to show some information, on my local development version it works perfectly, but on the production server (Ubuntu 16.04 LEMP) it fails in validation, because there is no data in the request.
Checks
The url is correctly showing (e.g. example.com/employeeInfo?employeeId=1)
Ajax itself is working: when I hard-code the controller's response everything is fine.
I cannot figure out why this happens in production, but not on the local version... Huge thanks for any clues!
View
<script>
(function ($) {
$(document).ready(function() {
$(".team-pic").off("click").on("click", function() {
var employeeId = $(this).data('id');
// Get data
$.ajax({
type: "GET",
url: "employeeInfo",
data: {employeeId:employeeId},
success: function(data){
var obj=$.parseJSON(data);
$('#team-info-title').html(obj.output_name);
$('#team-info-subtitle').html(obj.output_role);
$('#resume').html(obj.output_resume);
$('#linkedin').html(obj.output_linkedin);
$("#team-info-background").show();
$("#team-info").show();
}
});
});
});
}(jQuery));
</script>
Route
Route::get('/employeeInfo', 'EmployeeController#getInfo');
Controller
public function getInfo(Request $request) {
if($request->ajax()) {
$this->validate($request, [
'employeeId' => 'required|integer',
]);
$employee = Employee::find($request->employeeId);
$output_linkedin = '<i class="fab fa-linkedin"></i>';
$data = array("output_resume"=>$employee->resume,"output_linkedin"=>$output_linkedin, "output_name"=>$employee->name, "output_role"=>$employee->role);
echo json_encode($data);
}
}

If you want to pass a get data employeeId you have to pass a slug through your route either you should pass the data by POST method.
Route::get('/employeeInfo/{slug}', 'EmployeeController#getInfo');
And Get the slug on your function on controller .
public function getInfo($employeeId)

Related

Laravel Ajax on Update data getting Success Message on same Page

i am trying to update data using Ajax in Laravel, my data is being updated successfully but when i click on update it's success message is showing on next page, i want it to show message and updated data on same Page without loading page.
Laravel Controller:
public function update(Request $request, $id)
{
$teacher = Teacher::find($id);
$teacher->efirst = $request->efirst;
$teacher->esecond = $request->esecond;
$teacher->save();
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
AJAX function: Update.Js,
jQuery(document).ready(function($) {
$("#update-form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers/" + $('#update-id').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
success: function (data) {
let teacher = Object.entries(data.teacher);
teacher.forEach(item => { $(`[name=${item[0]}]`).val('item[1]'); });
},
});
});
});
view:
it contains table to show list of teacher with edit, and form under table with update button.
My data is being updated, but i don't want page reload. maybe something to do with append?
if you want to refresh the data
you can make this
var table = $('#tableId');
table.DataTable().ajax.reload();
this command can reload the data,
also in your view,
you can make the button
type="button"
or add to the form
onsubmit="return false;"

Redirecting to different view after an AJAX call Laravel

I am trying to activate my user by doing an AJAX call. I have this jQuery code for that:
$(document).ready(function(){
$(document).one('click','.continue-button',function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var id = $(this).data('id');
$.ajax({
url: '/activate',
type: 'POST',
data: {id : id},
success: function(res){
}
});
});
});
It takes the data-id attribute of my button, which is the user's id and sends an AJAX call. This is how my route looks like:
Route::post('/activate','ActiveController#activate');
My function:
public function activate(Request $request)
{
$id = $request->input('id');
User::where('id',$id)->update([
'active' => '1'
]);
return redirect('/loadDashboard');
}
It activates the user and then redirects to '/loadDashboard' route. This is how the route looks like:
Route::group( ['middleware' => 'auth' ], function()
{
Route::get('/loadDashboard','ActiveController#loadDashboard');
});
And finally my loadDashboard function:
public function loadDashboard()
{
return view('dashboard')->with('title','Dashboard');
}
I want to redirect the user to my dashboard view in aforementioned function, but it seems to return the view to my AJAX call. I can see the view in Inspect->Network. How can I fix this problem?
Instead of this
return redirect('/loadDashboard');
put this
return response()->json(['url'=>url('/loadDashboard')]);
and in your ajax success function put this:
success: function(res){
window.location=res.url;
}

Getting value from request in Laravel using ajax

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

ajax not getting any response from cakephp code

I am using CakePHP 2.9 to send data on the URL using ajax and get the related response.
I tried may method to get the response, I also want to know why this //URL:'/Pages/dropdownbox/'+id is not working.
bellow are ajax code which I wrote in the index.ctp.
$("#certificatedetail").on('change',function() {
var id = 'subcribe';
$("#usertype").find('option').remove();
$("#certificateclass").find('option').remove();
$("#certificatetyp").find('option').remove();
if (id) {
$.ajax({
type: 'POST',
url:'<?= Router::url(array('controller' => 'Pages', 'action' => 'dropdownbox','id')); ?>',
//url:'/Pages/dropdownbox/'+id,
dataType:'json',
cache: false,
async:true,
success: function(html)
{
$('<option>').val('').text('select').appendTo($("#usertype"));
$('<option>').val('').text('select').appendTo($("#certificateclass"));
$('<option>').val('').text('Select').appendTo($("#certificatetyp"));
$.each(html, function(key, value)
{
$('<option>').val(key).text(value).appendTo($("#usertype"));
});
}
});
}
});
I have written this controller code in PagesController,PHP and I declared the dropdownbox in AppController.php
public function dropdownbox($id = null)
{
Configure::write('debug', 0);
$this->layout = null;
$this->autoRender = false;
$category = array();
switch ($id)
{
case $id == "subcribe":
if ($id == 'subcribe') {
$category = array(
'individual' => 'Individual',
'organization'=>'Organization',
'organizationgovt' => 'Organization-Govt',
'organizationbank' => 'Organization-Bank'
);
break;
}
}
}
/ bellow is the code where I specify the dropdownbox function in AppController.php
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(
'login','add','index','contact','dropdownbox',
'cityres','stateres','sectorres','productres',
'project','service','about','apply','tender',
'decregistration','search','searchresult',
'tenderdetails'
);
}
You are generating the URL on your server, and using the string literal 'id' in it. The JavaScript id variable is never referenced. What you probably want is:
url:'<?= Router::url(array('controller' => 'Pages', 'action' => 'dropdownbox')); ?>' + id,
You are not returning any response from the controller. Do few things to debug it
Check in Browser's Network tab whether the called URL is correct or not.
Check the parameters are correct or not.
This is how it looks in Firefox Developer Edition
If URL is correct. Add below code in the dropdownbox() method. (Before the closing of the method)
echo json_encode($category);
Check Response Tab in the Network tab. (Example image above).
Also, console the response in the javascript code. Maybe you will be getting some other response which is not JSON.
success: function(html) {
console.log(html);
...
}
Hope it helps.

Ajax jquery.min.js:4 POST 500 (Internal Server Error) laravel 5

I got this error from Ajax call ! it's get action from checkbox then send data by Ajax to controller method,
jquery.min.js:4 POST http://localhost:8000/listhotelregisration 500 (Internal Server Error)
Here's the code html part:
<div style="display:block">
<div>My hotel Lists</div>
#foreach($myLists as $key => $val)
{{ $val['name'] }
{!! Form::checkbox($val['name'], $val['id'].','.$value['id']) !!} <br>
#endforeach
</div>
Ajax part:
$(function() {
$("input[type='checkbox']").change(function() {
var smi = $(this).val();
// alert(smi);
$.ajax({
url: 'listhotelregisration',
type: "post",
data: {'checko':smi},
success: function(data){
//alert(data);
}
});
});
Route part:
Route::post('listhotelregisration', 'ListhotelController#create');
Controller part:
public function create(Request $request)
{
$listhotel = new listhotel;
$data = $request->all();
$dataPrim = explode(",", $data);
$listhotel->id_list= $dataPrim[0];
$listhotel->id_hotel= $dataPrim[1];
$listhotel->save();
$response = "ok";
return response ()->json ($response);
}
Ajax in Laravel 5
This is mainly due to The VerifyCSRFToken middleware that laravel provide us out-of-the-box. It responds an Internal Server Error (500) when token mismatch occur on our requests.
We need to send our AJAX request with token sent to our browser.
The CSRF token is mostly stored in the meta tag, you can put it any where though
$.ajaxSetup
Set default values for future Ajax requests
Solution
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
Hope this helps.
error 500 will mean this is a server error.
To know exactly what went wrong you need to check the response the server is returning.
In any case i would already adjust your following pieces:
Javascript:
$(function() {
$("input[type='checkbox']").change(function() {
var id_list = $(this).attr('id_list');
var id_hotel = $(this).attr('id_hotel');
$.ajax({
url: 'listhotelregisration',
type: "post",
data: {
'id_list': id_list,
'id_hotel':id_hotel
}
}
});
});
Controller:
public function create(Request $request)
{
$data = $request->only(['id_list', 'id_hotel']);
$listhotel = listhotel::firstOrCreate($data)
return response ()->json ("OK");
}

Resources