AJAX Laravel Update Database - ajax

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

Related

Larave/Ajax PUT 500 internal server error possible reasons

My console shows this error whenever I try to update my form using my ajax code:
PUT http://127.0.0.1:8000/clinical/bbr-category-configuration-update/1 500 (Internal Server Error)
Route:
Route::put('/bbr-category-configuration-update/{category_id}', [BBRCategoryConfigurationController::class,'update']);
Ajax:
$(document).on('click', '.update_category', function (e){
e.preventDefault();
var cat_id = $('#edit_cat_id').val();
var update_data = {
'category_name' : $('#edit_category_name').val(),
'category_description' : $('#edit_category_description').val(),
}
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "PUT",
url: "/clinical/bbr-category-configuration-update/"+cat_id,
data: update_data,
dataType: "json",
success: function (response){
// console.log(response);
if(response.status == 400) {
$('#category_formCheckUpdate').html("");
$('#category_formCheckUpdate').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheckUpdate').append('<li>'+err_values+'</li>');
});
} else if(response.status == 404) {
$('#category_formCheckUpdate').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
} else {
$('#category_formCheckUpdate').html("");
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#editCategoryModal').modal('hide');
fetchcategory();
}
}
});
});
Controller:
public function update(Request $request, $category_id) {
$validator = Validator::make($request->all(), [
'category_name'=>'required|max:191',
'category_description'=>'required|max:191',
]);
if($validator->fails()) {
return response()->json([
'status'=>400,
'errors'=>$validator->messages(),
]);
} else {
$category_update = HmsBbrCategory::find($category_id);
if ($category_update) {
$category->category_name = $request->input('category_name');
$category->category_description = $request->input('category_description');
$category->update();
return response()->json([
'status'=>200,
'message'=>'Category Edited!',
]);
} else {
return response()->json([
'status'=>404,
'message'=>'Category Not Found',
]);
}
}
}
Things to note:
As you can see, my category_id is being read properly in: url: "/clinical/bbr-category-configuration-update/"+cat_id,. Also, I went ahead and did a console.log to show in my console that the whole table is getting retrieved. My main issue is this 500 internal server error. Not sure if it is by the PUT.
I also tried to change the PUT to POST or GET just to see if there is any change or other errors, but it's still the same 500 internal server issue. PS, my form has csrf.
Your problem is surely $category, you are using $category_update, not $category

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 if id exist then update record

i want to set condition, if teacher already exist in database then update record, if id doesn't exist then add record in database. how can i achieve it using ajax in laravel?
Update.js:
jQuery(document).ready(function($) {
$('#update-data').on('click',function(){
alert("ok");
$.ajax({
type: "POST",
url: "teachers/" + $('#update-data').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
beforeSend: function() {
},
success: function (data) {
alert("ok");
},
});
});
});
Store.Js:
jQuery(document).ready(function($) {
$("#add-data").submit(function (e) {
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
data.responseJSON;
refreshTable();
},
});
});
});
Update Controller:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
Store Controller:
public function store(Request $request)
{
$teacher = new Teacher;
$teacher=teacher::create($request);
}
There's a custom method for this
$teacher = Teacher::firstOrCreate($id, [
// Pass data here
]);
And if you want to check manually and traverse the request to another method
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if (is_null($teacher)) { // If model not found, pass request to store method
$this->store($request);
}
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
From the docs
Hope this helps
Eloquent provides a updateOrCreate method so you can update or create a record.
$teacher = Teacher::updateOrCreate([
// attributes to search for
'name' => 'Test Teacher',
], [
// values
'grade' => 6,
]);
This would find a teacher with name 'Test Teacher' and update grade to 6 or create a new teacher with name 'Test Teacher' and grade set to 6.
"You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model ..." - Laravel 6.0 Docs - Eloquent - Other Creation Methods - updateOrCreate

The Ajax pagination to my account not run

I would like to create an Ajax pagination of my articles in my account, here is my code that I created but it does not work I do not know how to do.
MyaccountController
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
return view('site.user.account', [
'user' => $user,
'articles' => $user->articles()->orderByDesc('created_at')->paginate(4),
]);
}
I would like to have the javascript code
$(document).ready(function () {
$(document).on('click','.pagination a',function(e){
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
var url = $(this).attr('href');
$.ajax({
url: url,
method: 'GET',
data: {},
dataType: 'json',
success: function (result) {
if (result.status == 'ok'){
$('#userListingGrid').html(result.listing);
}else{
alert("Error when get pagination");
}
}
});
return false;
})
});
I would have a check on your controller for an ajax request like so:
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
if(request()->ajax()){
return response()->json(['user' => $user, 'articles' => $user->articles()->orderByDesc('created_at')->paginate(4);
}
return view('site.user.account', [
'user' => $user,
'articles' => $user->articles()->orderByDesc('created_at')->paginate(4),
]);
}
Then you don't have to load your view every time and you can let your javascript functions take care of the DOM manipulating of the results. Not sure if that's what you are looking for. I know that you would probably need a {{$articles->links()}} at the end of your view to go through each page.

Auth session data flush after redirect laravel 5.4

I am using laravel 5.4 and login user with auth
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "./post_xing_res",
data: {user_data:response},
success: function(msg){
console.log(msg);
if(msg == 1)
{
location.href='http://192.168.1.12/maulik_proj/studicash_new/public/welcome';
}
}
});
}
as you can see above my ajax call in post_xing_res i am using auth as below
$created_at=$updated_at=time();
/if(Request::ajax()) {/
$data = Input::all();
$check_acc_first = DB::table('users')
->where('login_with',3)
->where('xing_id',$data['user_data']['user']['id'])
->first();
if ($check_acc_first) {
Auth::loginUsingId($check_acc_first->user_id);
echo "<pre>";print_r(Auth::user());
}
else {
$insert_user = DB::table('users')->insertGetId(
array('login_with' => 3, 'xing_id' => $data['user_data']['user']['id'], 'profile_pic' => $data['user_data']['user']['photo_urls']['maxi_thumb'],'first_name' => $data['user_data']['user']['first_name'],'last_name' => $data['user_data']['user']['last_name'],'email' => $data['user_data']['user']['active_email'],'created_at'=>$created_at,'updated_at'=>$updated_at)
);
$user_data = DB::table('users')
->where('user_id',$insert_user)
->get();
//echo "<pre>";print_r($user_data);
Auth::loginUsingId($user_data->user_id);
}
if (Auth::check()) {
echo 1;
exit;
}
as you can see i am able to get user data as well as Auth::user data when print Auth::user and getting 1 as response also
But when i redirect to welcome page Auth::user data returns blank
Below is my route file
Route::middleware('guest')->group(function () {
Route::post('/post_xing_res','SocialAuthController#postXingRes');
});
Route::get('/welcome',function(){
return view('welcome');
});
Can you please help me to get out of this problem
Thanks in advance

Resources