Laravel Ajax Store Update data issue - ajax

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.

Related

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:

How to update data on a page using ajax script?

There is a script that needs to update the data on the page in a specific div. But instead of updating, the block with the div is simply hidden and in order for it to appear again, you need to reload the page. The data comes in data, but here is $ ("# userPost" + id) .html (data); something doesn't work.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.infinite-scroll').on('click', '#editPostButton', function(e) {
e.preventDefault();
var id = $(this).data('id');
var user_id = $('#userForm').val();
var form = document.getElementById('EditPostForm'+id);
var formData = new FormData(form);
// var formData = $('#EditPostForm'+id).serialize();
$.ajax({
url: "id"+user_id+"/"+id+"/edit",
type: "POST",
data: formData,
success: function(data) {
console.log(data);
$("#userPost"+id).html(data);
$("#closeButton"+id).click();
},
error: function() {
console.log('error');
},
processData: false,
contentType: false,
});
});
And div
<div id="userPost{{$post->id}}">
#if($post->img)
<div>
<img src="{{$post->img}}" class="img-fluid">
</div>
#endif
<br>
#if($post->title)
<div class=" mr-1 mb-3 titleleft">
<h5 style="color: black"><b>{{$post->title}}</b></h5>
</div>
#endif
#if($post->message)
<div class="text-muted text-small margins" style="white-space: pre-wrap;">{{mb_strimwidth($post->message, 0, 600, " . . . Read more")}}</div>
#endif
#if($post->videoPost)
<div class="embed-responsive embed-responsive-16by9 mt-4 mb-2">
<iframe class="embed-responsive-item" src="{{$post->videoPost}}" allowfullscreen></iframe>
</div>
#endif
</div>
Try doing this way:
$("#userPost"+id).load(url);
or
$("#userPost"+id).html(data).load(url);

Laravel Ajax update request is duplicating data

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

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!');
}

Integrating AJAX with mailchimp

I'm trying to integrate AJAX with a mailchimp form. I’ve followed another member’s answer but still cannot get it to work. Could you guys see what's wrong with my code?
Thank you.
Here is my code:
<form id="form">
<script>
$( "button" ).click(function() {
formData = {
u: "xxxxxxxxx",
id: "xxxxxxxxx"
};
$.ajax({
url: "http://xxxxxxxxxxxxxxxxxxxxxxx/post-json?",
type: "GET",
crossDomain: true,
contentType: 'application/json',
data: formData,
dataType: "json",
success: function(data) {
//action
},
error: function() {
//action
}
});
});
</script>
<fieldset>
<label for="email_input_id"><input placeholder=
"Type Your Email" type="email" /></label>
</fieldset><button type= "submit">Submit</button>
I finally got my code working.
<form id="form" action="https://xxxxx.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="GET">
<input type="hidden" name="u" value="xxxx">
<input type="hidden" name="id" value="xxxx">
<input type="EMAIL" autocapitalize="off" autocorrect="off"
name="MERGE0" id="MERGE0" size="25" value=""
placeholder="Type your email and press enter">
<p id="response"> </p>
</form>
<script>
$('#form').submit(function(e) {
var $this = $(this);
var paragraph = document.getElementById('response');
$.ajax({
type: "GET",
url: "https://xxx.com/subscribe/post-json?u=xx&id=xx&c=?",
data: $this.serialize(),
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server."); },
success : function(data) {
if (data.result != "success") {
paragraph.innerHTML = data.msg;
} else {
paragraph.innerHTML = data.msg;
}
}
});
return false;
});
</script>

Resources