Laravel8 - after insert using Ajax - ajax

Hello every one I'm using laravel8 and using Ajax to insert records in database.
my problem is that after I insert record ,then it automatically goes to new page but it just contains an response as json object(screenshot of page below)
How can I prevent that and redirect in normal way.
my controller code :
public function store(Request $request){
$user = User::create($request->all());
return response()->json(['url'=>url('/users')]);
}
my view :
$.ajax({
type: "POST",
url: "{{route('users.store')}}",
data:{
name: $("#name").val(),
email : $("#email").val(),
image : $("#image").val(),
},
success: function(response){
if(response){
$("#userTable tbody").prepend(
'<tr><td>'+ response.id+'</td><td>'
+ response.name+'</td><td>',
+ response.email+'</td><td>',
+ response.image+'</td><td>'
)
window.location.href=response.url;
$("#userForm")[0].reset();
$("#userModel").model('hide');
}
here is the page
sorry for my bad english

The problem is here return response()->json(['url'=>url('/users')]);
You can just return per example return response()->json(data);
Here's an example :
Controller :
public function store(Request $request){
$user = User::create($request->all());
$data = collect();
//TODO: find a way to catch user data you created
$data->push([
'email' => (your attribute),
'name' => (your attribute),
'image' => (your attribute),
'id' => (your attribute),
'url' => (your url),
]);
return response()->json($data);
}
Ajax :
$.ajax({
type: "POST",
url: "{{route('users.store')}}",
data:{
name: $("#name").val(),
email : $("#email").val(),
image : $("#image").val(),
},
success: function(data){
if(data){
$("#userTable tbody").prepend(
'<tr><td>'+ data.id+'</td><td>'
+ data.name+'</td><td>',
+ data.email+'</td><td>',
+ data.image+'</td><td>'
)
window.location.href=data.url;
$("#userForm")[0].reset();
$("#userModel").model('hide');
}

Related

Ajax update field database field in laravel blade template

I have a list of hotels in a select I want update the database base on the hotel selected if it update the field I want to alert it on the home page.
this is the ajax function
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'{{ route('home', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert(data);
},
error: function (result) {
alert("Error occur in the update()");
}
});
}
}
my controller
public function update(Request $request, $hotel_plan_id)
{
$hotel=plan_hotel::where('hotel_plan_id', $hotel_plan_id)->first();
$hotel->hotel_name = $request->input('hotel_name');
//$hotel ->room_name = $request->input('room_name');
$hotel->save();
// return redirect('/home')->with('success', 'price updated');
}
my route
Route::post('home/{hotel_plan_id}', 'HomeController#update')->name('home');
my select form
{!! Form::select('hotel_name', array($item[4], $item[10]),'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onclick'=>"showRoom(this.value, $item[8])"));!!}
You have error with ajax url and you dont also pass the value of hotel name.
Check this changes.
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'/home/' + id,
data:{_token:'{{ csrf_token() }}', hotel_name: 'Your value here'},
});
}
Please return json response
return response()->json();
You have to return json object like this
return response->json([
'status' => 200,
'result' => true,
'error' => false,
'data' => $hotel
]);

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

Eloquent not removing record from database on AJAX call

I'm trying to implement a "like" system for posts and there's an animated button by CSS and three AJAX calls through post.
One that will check if the post is already liked and will apply certain style to the button.
One that will add a record to the table in case that an user clicks the button.
One that will delete the record in case the user click it again.
AJAX code:
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : '/like/alreadyLiked',
method : 'POST',
dataType : 'json',
data : {
slug : '{{Request::segment(2)}}',
user_id : '{{Auth::user()->user_id}}'
},
success : function (data) {
if(data.display === true){
$('#likelink').attr('class', 'like active')
}else{
$('#likelink').attr('class', 'like');
}
}
});
if($('#likelink').hasClass('like') && $('#likelink')[0].classList.length == 1){
$('#likelink').on('click', function(e){
e.preventDefault();
$.ajax({
url : '/like',
method : 'POST',
dataType : 'json',
data : {
slug : '{{Request::segment(2)}}',
user_id : '{{Auth::user()->user_id}}'
},
success : function(data){
if(data.display === true){
$('#likelink').attr('class', 'like');
}
}
});
});
}else{
$('#likelink').on('click', function(e){
e.preventDefault();
$.ajax({
url : '/dislike',
method : 'POST',
dataType : 'json',
data : {
slug : '{{Request::segment(2)}}',
user_id : '{{Auth::user()->user_id}}'
},
success : function(data){
if(data.display === true){
$('#likelink').attr('class', 'like');
}
}
});
});
}
});
PHP (Laravel code):
public function hasHeAlreadyLikedThisPost()
{
if(request()->ajax()){
$post = Post::where('slug', '=', request()->input('slug'))->first();
$post_id = $post->post_id;
$like = Like::where(['user_id' => request()->input('user_id'), 'post_id' => $post_id])->first();
if($like != null){
return response()->json(['display' => true]);
}else{
return response()->json(['display' => false]);
}
}
}
public function addLike()
{
if(request()->ajax()){
$slug = request()->input('slug');
$user_id = request()->input('user_id');
$post = Post::where('slug', '=', $slug)->first();
$like = Like::create(array(
'user_id' => $user_id,
'post_id' => $post->post_id
));
if($like->exists){
return response()->json(['display' => true]);
}else{
return response()->json(['display' => false]);
}
}
}
public function dislike()
{
$slug = request()->input('slug');
$user_id = request()->input('user_id');
$post = Post::where('slug', '=', $slug)->first();
$like = Like::where(['post_id' => $post->post_id, 'user_id' => $user_id])->delete();
return response()->json(['display' => false]);
}
The issue is that the "check" and the "insert" calls work but the "delete" one doesn't. In any case it will add a new record to the db and won't change the style.
I think that you have forgot to call first (or get)
$like = Like::where(['post_id' => $post->post_id, 'user_id' => $user_id])->first()->delete();
where() returns a query,but delete seems to work on eloquent model objects. So to get model object from query so you will call first() (like you did before), or get() to get an array and iterate through it applying delete() on each
Try by putting
$(document).on('click', '#likelink', function(e)
instead of $('#likelink').on('click', function(e)

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