Laravel: Ajax update to database - ajax

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

Related

laravel- request empty in controller using ajax

I am using laravel 6.0 and i am building crud application. I have following jquery code in view file
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/'+id,
method: 'post',
success: function (res) {
console.log(res);
}
})
});
}
And this is the code in controller
public function update(Request $request, $id='') {
$country = $request->input('countryname');
$sortname = $request->input('sortname');
$phonecode = $request->input('phonecode');
//return $country.$sortname.$phonecode;
return $request;
// DB::table('countries')->where('id',$id)->update(
// [
// 'name' => $country,
// 'sortname' => $sortname,
// 'phonecode' => $phonecode,
// ]);
}
The problem is $request returns empty.
If I don't use ajax then I am getting all input values. But I dont know why its not working for ajax request. Also I have added this line in view file
headers: {
'X-CSRF-TOKEN': '{!! csrf_token() !!}'
}
});
Please help me to solve this problem
You are not passing your form data. Try this:
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: $(this).serialize();
success: function (res) {
console.log(res);
}
})
});
}
laravel by default does not send raw data , you have to convert your data to json, the best practice is :
return response()->json([
'data' => $request
]);
Just try this code for example and see if you get any hint.
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: {'countryname' : 'India','sortname' : 'Sort Name', 'phonecode' : '022'};
success: function (res) {
console.log(res);
}
})
});
}
See if you are getting any response.

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

Symfony ajax form need reload page to show results

I have a product page where users can write comments, this works fine but i would like to implement ajax form with no page refresh.
The code call ajax and persist, but need press f5 to show new comment.
what am I doing wrong?
Thanks, and sorry for my english.
In product view, render a controller that call the form:
<div class="comments">
{{ render(controller('AppBundle:Comment:newComment',{'media': selected.id})) }}
</div>
Controller:
class CommentController extends Controller
{
/**
* #Route("/media/{media}/", name="create_comment", options={"expose"=true})
* #Method("POST")
* #ParamConverter("media", class="AppBundle:Media")
*/
public function newCommentAction(Request $request, $media)
{
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$data = $form->getData();
$data->setUser($this->getUser());
$data->setMedia($media);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
return new JsonResponse('Success!');
}
return $this->render('comment/newComment.html.twig', array(
'media' => $media,
'form' => $form->createView()
));
}
}
newComment.html.twig
<form method="POST" id="commentForm" action="{{path('create_comment', {'media': media.id})}}">
{{ form_row(form.comment) }}
<button type="submit" id="submitButton" class="btn btn-xs btn-danger">{{ 'btn.send' |trans }}</button>
app.js
$('body').on('click','#submitButton', function(e){
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function(response){
$(".ajaxResponse").html(response);
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
This should work for you to reload the element with class="comments" after your POST:
$('#submitButton').on('click', function (e) {
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function (response) {
$('.comments').load(window.location + ' .comments > *');
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
Edit:
As far as your second question regarding $request->isXmlHttpRequest() -- this method just looks for the X-Requested-With header with value of XMLHttpRequest. Are you testing for it on the first request or on the second request or on both requests? Can you take a look in Firebug or Chrome Tools and see if the header is on both requests?

AJAX Laravel Update Database

My issue is that I'm doing a simple AJAX Post to update a database record, but I'm not getting any error and it's still not updating the record. What am I overlooking?
Thanks!
JS:
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
if ($('.abc-status').css('display') == 'block')
{
abc.api({method: 'user'}, function(error, user) {
var userId = $('.oath_id').text();
var username = user.display_name;
console.log(username);
$.ajax({
type: "POST",
url: "oauth_authorization/abc/"+username,
data: {abc_username: username},
error: function(data){
console.log(data);
}
});
});
}
Controller:
public function postabcOAuth(Request $request, $username)
{
Auth::user()->update([
'abc_username' => $username,
]);
}
Route:
Route::post('/oauth_authorization/abc/{username}', [
'uses' => '\abc\Http\Controllers\OAuthController#postAbcOAuth',
'middleware' => ['auth'],
]);
You can change the post method in route path and also in ajax function
Using the following in the Controller, I was able to get it to work.
public function postAbcOAuth(Request $request, $username)
{
DB::table('users')
->where('id',Auth::user()->id)
->update(['abc_username' => $username]);
}

Categories

Resources