Laravel Ajax on Update data getting Success Message on same Page - ajax

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;"

Related

Laravel: Ajax update to database

i just want to update my data via ajax i am getting error.
Error Console:
POST http://abc.local/teachers/users/1 404 (Not Found)
here is my controller:
public function policyupdate(Request $request, $id)
{
$user = DB::table('users')->find($id);
$user->update($request->all());
return response()->json([
'status' => 'success',
'msg' => 'has been updated'
]);
}
web.php:
Route::post('users/{user}','TeachersController#policyupdate') ;
js:
jQuery(document).ready(function(e) {
alert(1);
$('#update-policy').on('click', function(e) {
console.log('Update policy clicked!')
e.preventDefault(e);
$.ajax({
type: "POST",
url: "users/" + $('#update-policy').attr("value"),
data: $(this).serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
alert(updated);
},
});
});
});
I only notice a couple of issues.
url: "users/" + $('#update-policy').attr("value"),
In the url of the ajax call you don't have a slash at the beginning, so the url will be relative to the url of the page where the function is located, instead of the base url. to solve it just add that slash at the beginning
url: "/users/" + $('#update-policy').attr("value"),
The other one is that you have an input with the put method,
<input type="hidden" name="_method" value="put" />
so the Laravel route should be put (it makes sense if it takes into account that it is a route to update)
Route::put('users/{user}','TeachersController#policyupdate') ;
Well, and as you yourself discovered, with query builder, the update() method works if you query with where() instead of find()
$user = DB::table('users')->where('id', $id)->update( $request->all() );

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

Ajax data not getting into controller

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)

ajax datatables can't reload

i have made function where i can add a row after confirming. the problem is, after submit button, the tables dont reload and show error function alert.actually data success saved and i have to refresh the page so that the table can reload.
here is my ajax jquery code:
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('activity/save')?>";
} else {
url = "<?php echo site_url('activity/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form-input').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#myModal').modal('hide');
reload_table();
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
my controller:
public function save() {
$actype = $this->input->post('actype');
$activity_name = $this->input->post('activity_name');
$project = $this->input->post('project');
$portion = $this->input->post('portion');
$activity = $this->input->post('actid');
$data = array(
'activity_type_id' =>$actype,
'activity_name' =>$activity_name,
'project_id' =>$project,
'portion' =>$portion,
'activity_id' => $activity
);
$this->activity->insertactivity($data);
echo json_encode(array("status" => TRUE));
}
how can i automatically reload only the datatables and show alert success.

Passing an Ajax variable to a Codeigniter function

I think this is a simple one.
I have a Codeigniter function which takes the inputs from a form and inserts them into a database. I want to Ajaxify the process. At the moment the first line of the function gets the id field from the form - I need to change this to get the id field from the Ajax post (which references a hidden field in the form containing the necessary value) instead. How do I do this please?
My Codeigniter Controller function
function add()
{
$product = $this->products_model->get($this->input->post('id'));
$insert = array(
'id' => $this->input->post('id'),
'qty' => 1,
'price' => $product->price,
'size' => $product->size,
'name' => $product->name
);
$this->cart->insert($insert);
redirect('home');
}
And the jQuery Ajax function
$("#form").submit(function(){
var dataString = $("input#id")
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/home/add",
data: dataString,
success: function() {
}
});
return false;
});
As always, many thanks in advance.
$("#form").submit(function(){
var dataString = $("input#id")
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/home/add",
data: {id: $("input#id").val()},
success: function() {
}
});
return false;
});
Notice data option in the ajax method. Now you could use $this->input->post('id') like you are doing in the controller method.
Why not slam it to the end of
url: "/home/add",
like
url: "/home/add/" + $("input#id").val(),
Then I guess codeigniter will treat it like a normal parameter ... ?

Resources