Laravel Ajax update request is duplicating data - ajax

i am trying to update data using ajax, but my data is being duplicated,
due to ajax URL, i am not sure if i am passing correctly/
Ajax Code:
jQuery(document).ready(function($) {
$('#update-form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers/" + $('#update-id').attr("value"), //error is here
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
success: function (data) {
alert("updated");
},
});
});
});
view code:
i have table with list of teachers, and edit button for each teacher;
<button type="button" id="btn" value="{{ $teacher->id }}" class="btn btn-primary btn-block btn-sm edit-btn">Edit</button>
in form i have hidden field
<form method="post" id="update-form">
{{ method_field('PATCH') }}
<input type="hidden" id="update-id" value="{{$teacher->id}}" >
<div class="">
<label for="efirst">efirst</label>
<input type="text" class="form-control" name="efirst" id="update-efirst">
<textarea name="esecond" class="form-control" id="update-esecond" rows="6"></textarea>
</div>
<button type="submit" class="btn btn-success" id="update-submit">Update</button>
</form>
when i click on update, teacher ID's are being changed, one teacher id becomes another teacher id. is it correct way to pass teacher id from hidden field?

Write route name like below
At Web.php
Route::post("teacher/{id}/edit","YourController")->name("teacher.update");
At Blade File
$('#update-form').on('submit', function (e) {
e.preventDefault();
var id = $('#update-id').val(); // $('#update-id').attr("value") also ok
$.ajax({
method: "post",
url: "{{ route('teacher.update',id) }}",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
success: function (data) {
alert("updated");
},
});
});
Try this.
It will be work

Related

why laravel ajax returns json view page

i am using ajax to store the info but when i store or not store it returns a json page and i don't want it to return a json i want to add the item without relead the page and using calidation also
please help
here is my code
my route
Route::resource('products',App\Http\Controllers\ProductController::class);
my form
<form method="POST" id="productform">
#csrf
#method('POST')
<ul id="showerrors">
</ul>
<div class="form-group">
<label for="">name</label>
<input type="text" name="name" class="form-control">
</div>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
and my ajax code
<script>
$(document).ready(function(){
$('#productform').submit(function(e){
e.preventDefault();
var data = {
'name' : $("input[name='name']").val(),
'_token' : $("input[name='token']").val(),
}
// console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/products",
type : "POST",
data:data,
dataType:'json',
success:function(response){
console.log(response.status);
if(response.status == 400){
$('#showerrors').empty();
$('#showerrors').addClass('alert alert-danger');
$.each(response.errors,function(key,value){
$('#showerrors').append('<li>'+value+'</li>')
});
}
else{
$("#successmessage").empty();
$("#successmessage").addClass('alert alert-success');
$("#successmessage").text(response.message);
$('#exampleModal').modal('toggle'); //or $('#IDModal').modal('hide');
conssole.log(response.message);
return false;
}
},
});
});
});
Try this solution
add id to input field
<input type="text" name="name" class="form-control" id="name">
changes in script
$(document).ready(function(){
$('#productform').submit(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/products",
type : "POST",
data:{
name: name
},
dataType:'json',
success:function(response){
console.log(response.status);
if(response.status == 400){
$('#showerrors').empty();
$('#showerrors').addClass('alert alert-danger');
$.each(response.errors,function(key,value){
$('#showerrors').append('<li>'+value+'</li>')
});
}
else{
$("#successmessage").empty();
$("#successmessage").addClass('alert alert-success');
$("#successmessage").text(response.message);
$('#exampleModal').modal('toggle'); //or $('#IDModal').modal('hide');
conssole.log(response.message);
return false;
}
},
});
});
});
in your controller store function
suppose your model name is Product
public function store(Request $request)
{
...
$product = Product::create($request->only('name));
return response()->json([
'status' => 200,
'message' => 'Product created successfully.'
]);
}

Get value of submit button from Ajax call

The value of the submit buttons are always null in the Action.
What do I need to change to know which submit button has been clicked?
<form id="actionInvitation">
<div>
<ul>
<li>
#Model.TeamInviteBy
</li>
</ul>
</div>
<input type="submit" name="actionBtn" id="acceptBtn" value="Accept Invitation" />
<input type="submit" name="actionBtn" id="declineBtn" value="Decline Invitation" />
</form>
$('#actionInvitation').submit(function (e) {
e.preventDefault();
var formData = new FormData($('#actionInvitation')[0]);
$.ajax({
url: '#Url.Action("ActionInvitation", "Home")',
type: 'post',
cache: false,
processData: false,
contentType: false,
data: formData,
success: function (data) {
$("#invitationActionMessage").append('Invitation Accepted');
}
});
});
//Action
public async Task<IActionResult> ActionInvitation(UserViewModel userViewModel, string acceptBtn, string declineBtn)
Your formData will not contain the objects you need to pass.
You can change your code like below:
<form id="actionInvitation">
<div>
<ul>
<li>
#Model.TeamInviteBy
<input type="hidden" name="TeamInviteBy" value="#Model.TeamInviteBy">
</li>
</ul>
</div>
<input type="submit" name="actionBtn" onclick="Send(event,this)" value="Accept Invitation" />
<input type="submit" name="actionBtn" onclick="Send(event,this)" value="Decline Invitation" />
</form>
#section scripts{
<script>
function Send(ev,el) {
ev.preventDefault();
var data = $("input[name='TeamInviteBy']").val();
var value = $(el).val();
$.ajax({
url: '#Url.Action("ActionInvitation", "Home")',
type: 'post',
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: { TeamInviteBy: data, actionBtn: value},
success: function (data) {
$("#invitationActionMessage").append('Invitation Accepted');
}
});
}
</script>
}
Action:
public async Task<IActionResult> ActionInvitation( UserViewModel userViewModel , string actionBtn)
{
if(actionBtn="Accept Invitation")
{
//...
}
else
{
}
}
Result:

Script to delete Ajax record does not work correctly

I have an Ajax script that should delete entries. It basically works, but when you click the delete button, only the first one is deleted from the list of all records. Although, after reloading the page, the record that disappeared appears and the one I wanted to delete is deleted. How can this be fixed?
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (){
$("#textpostdata").remove();
},
});
});
});
And html
<div id="textpost">
#foreach($post->comments as $com)
<div id="textpostdata" data-id="{{$com->comment_id}}">
<p><b>{{$com->author_name}}</b> · <i>{{$com->created_at->diffForHumans()}}</i></p>
<p>{{$com->comment}}</p>
#if(Auth::check())
#if(Auth::user()->id == $com->author_id)
<form action="{{route('delMusicComment', ['comment_id' => $com->comment_id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $com->comment_id }}">Удалить</button>
</form>
#endif
#endif
<hr>
</div>
#endforeach
</div>
you used the same id for multiple elements
the id should be unique, if you use same id for other elements, the html just set that id to first element.
you can use className instead ID like this:
HTML:
<button type="submit" class="btn btn-sm btn-outline-danger py-0 mt-4 delete" data-id="{{ $com->comment_id }}">Удалить</button>
jquery:
$("body").on("click",".delete",function(e){
//other lines of your jquery is ok, because you used $(this) in this line: var id = $(this).data('id');
Jquery - remove the entry after ajax:success
var this_element = $(this); //get the active element, because you can not use $(this) in ajax:sucess!
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (){
this_element.closest("div").remove(); //remove selected button's whole div!
},
});
NOTE:
when you use className to access the element, you can find the element that event affected on with $(this)
for test use this code: console.log($(this));
Your html is not valid because if there is many comments you have many div with id #textpostdata. You can suffix it with the id of your comment
<div id="textpost">
#foreach($post->comments as $com)
<div id="textpostdata-{{$com->comment_id}}" data-id="{{$com->comment_id}}">
<p><b>{{$com->author_name}}</b> · <i>{{$com->created_at->diffForHumans()}}</i></p>
<p>{{$com->comment}}</p>
#if(Auth::check())
#if(Auth::user()->id == $com->author_id)
<form action="{{route('delMusicComment', ['comment_id' => $com->comment_id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $com->comment_id }}">Удалить</button>
</form>
#endif
#endif
<hr>
</div>
#endforeach
</div>
Furthermore your query selector should be modified and your delete method should return the deleted element
$.ajax({
url: "/post/delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (data){
$("#textpostdata" + data.comment_id).remove();
},
});

Laravel Ajax Store Update data issue

i have Form in which i want to update data or store data, right now it is updating data, when i click on update/add button.
<meta name="csrf-token" content="{{ csrf_token() }}">
<form id="update-form" enctype="multipart/form-data" >
#method('PUT')
//text fields
<button type="submit" class="btn btn-secondary btn-lg shadow-lg rounded" name="" value="" id="store-data" > <span class="fa fa-user-add "> </span> ADD</button>
<button type="submit" class="btn btn-secondary btn-lg shadow-lg rounded" name="id" value="{{#$teacher->id}}" id="update-data" > <span class="fa fa-user-edit "> </span> UPDATE</button>
</form>
ajax code for store:
jQuery(document).ready(function($) {
//Ajax store
$('#store-data').on('submit', function(e) {
e.preventDefault(e);
$.ajax({
type: "POST",
url: "teachers/store",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: new FormData(this),
success: function (data) {
alert("Added");
},
});
});
});
ajax code for update:
jQuery(document).ready(function($) {
$('#update-form').on('submit', function(e) {
e.preventDefault(e);
$.ajax({
type: "POST",
url: "teachers/" + $('#update-data').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: new FormData(this),
processData: false,
contentType: false,
beforeSend: function() {
},
success: function (data) {
alert("updated");
},
});
});
});
web.php:
Route::get('teachers/store', 'TeachersController#store')->name('add');
Route::resource('teachers', 'TeachersController');
required:
when i click on add button it should add data, and when i click on update it should update.

AJAX - upload image with ajax without form on laravel

i try to make upload image with ajax without form, when i am sent data without the image, data successfully submitted to the database, but when i am adding an image, when i try to submit, no response at all,
this is my template code :
<input type="hidden" name="lesson_id" value="{{-- $lessons->id --}}">
<input type="hidden" name="parent_id" value="0"> -->
<div class="form-group">
<label>Komentar</label>
<textarea rows="8" cols="80" class="form-control" name="body" id="textbody0"></textarea>
</div>
<ul class="right">
<input type="file" name="image" id="image" />
<img id="myImg" src="#" />
<button type="button" class="btn btn-primary" onClick="doComment({{ $lessons->id }},0)" >Kirim</button>
and this is my script for submit data :
function doComment(lesson_id, parent_id) {
var body = $('#textbody'+parent_id).val();
var image = $('#image').prop('files')[0];
if (body == '') {
alert('Harap Isi Komentar !')
}else {
var postData =
{
"_token":"{{ csrf_token() }}",
"lesson_id": lesson_id,
"parent_id": parent_id,
"image": image,
"body": body
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
}
});
$.ajax({
type :'POST',
url :'{{ url("lessons/coments/doComment") }}',
dataType: 'json',
data : postData,
beforeSend: function(){
// Show image container
swal({
title: "Sedang mengirim Komentar",
text: "Mohon Tunggu sebentar",
imageUrl: "{{ asset('template/web/img/loading.gif') }}",
showConfirmButton: false,
allowOutsideClick: false
});
{{-- $("#loader").show(); --}}
},
success:function(data){
if (data.success == false) {
window.location.href = '{{ url("member/signin") }}';
}else if (data.success == true) {
$('#textbody'+parent_id).val('');
swal({
title: "Komentar anda sudah terkirim!",
showConfirmButton: true,
timer: 3000
});
getComments();
}
}
});
}
}
Can any one help me?
postData = new FormData();
if(!!file.type.match(/image.*/)){
postData.append("image", file);
$.ajax({
type : 'POST',
url : '{{ url("lessons/coments/doComment") }}',
data : postData,
dataType: 'json',
processData: false,
contentType: false,
success: function(data){
alert('success');
}
});
}else{
alert('Not a valid image!');
}

Resources