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
Related
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
]);
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.
So here is my code for ajax
i think the ajax code is right .
$(document).ready(function(){
$('.add-comment').click(function(){
var comment_data = $('.comment-form').serialize();
$.ajax ({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST',
url: '/comment',
data: comment_data,
success: function(data) {
console.log(data);
$('.all-comment').append(data);
},
error: function(data) {
console.log('error');
}
})
})
});
here is my controller
public function store(Request $reqeust) {
$comment = Comment::create([
'body' => request('body'),
]);
return view('welcome',compact('comment'))->render();
}
i think the problem is in controller btw i am new in development so .. yeah
and yes i am getting error
POST http://localhost:8000/comment 500 (Internal Server Error)
If you are doing an AJAX call, you probably don't need to return the whole welcome view. What's easiest is to return true if the comment was successfully saved, otherwise false.
Also, you aren't attaching your comment to anything. I'm guessing you have other fields that need to be filled in on the comments table, such as post_id. If that is the case, you can pass the post_id as another parameter with the request and do:
public function store(Request $request)
{
$post = Post::findOrFail( $request->post_id );
Comment::create([
'post_id' => $post->id,
'body' => $request->body
]);
return true;
}
This verifies that there really is a post to link to.
Better yet, you can use Route Model Binding and relationships to do:
public function store(Request $request, Post $post)
{
$post->comments->create([
'body' => $request->body
]);
return true;
}
This will do the same thing and it's a bit cleaner. Also, it will automatically add the post_id because of the relationship (assuming you set that up).
I need help: I do not know how to edit two tables of the database from the same form. I'm using cakephp3.
I'm trying to use ajax
Thanks for your help
Data to save in a different driver, there the script
This script is in a controller called carsController
**<script type="text/javascript">**
function editarCliente(a, b ){
var parametros = {
"clasificacionC" :a,
"descripcion": b,
};
$.ajax({
data: parametros,
url: '<?php echo router::url(array('controller'=>'Clientes','action'=>'editarcliente',$cliente->id));?>',
type: 'post',
dataType: 'json',
success: function (response) {
$("#nomCliente").val(response.uno+" "+response.dos);
$("#telCliente").val(response.tres);
$("#celCliente").val(response.cuatro);
}
});
}
**</script>**
This method is in a controller called clientesController.
public function editarcliente($id = null)
{
$cliente = $this->Clientes->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$cliente->clasifi_cliente=$_POST("clasificacionC");
$cliente->descripcion=$_POST("descripcionC");
if ($this->Clientes->save($cliente)) {
$this->Flash->desactivar(__('Cliente desactivado'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The cliente could not be saved. Please, try again.'));
}
}
$this->set(compact('cliente'));
$this->set('_serialize', ['cliente']);
}
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]);
}