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:
Related
I have a trouble when to upload img using ajax in laravel. I have an error in getClientOriginalExtension() I think that trouble in enctype in ajax because the controller can not read the upload file.
this is my view :
<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$('body').on('click', '#saveBtn', function(){
var url;
var registerForm = $("#data-form");
var formData = registerForm.serialize();
$(this).html('saving...');
$('#saveBtn').attr('disabled',true);
$.ajax({
enctype: 'multipart/form-data',
url: '{{ route('blog.store') }}',
type:'POST',
data:formData,
success:function(data) {
console.log(data);
if(data.errors) {
}
if(data.success) {
}
$('#saveBtn').html('Save Data');
$('#saveBtn').attr('disabled',false);
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Save Data');
}
});
});
});
</script>
and this is my controller
$name_file = time().'.'.$request->img_thumbnail->getClientOriginalExtension();
$request->img_thumbnail->move(public_path('images'), $nama_file);
create.blade.php
#section('content')
<form id="submitform">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name">
</div>
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="photo" id="photo">
</div>
<button class="btn btn-primary" id="submitBtn" type="submit">
<span class="d-none spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
<span class="">Submit</span>
</button>
</form>
#endsection
#push('custom-scripts')
<script src="{{ asset('js/upload.js') }}"></script>
#endpush
upload.js
$(function () {
$('#submitBtn').on('click', (e) => {
e.preventDefault();
var formData = new FormData();
let name = $("input[name=name]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
var photo = $('#photo').prop('files')[0];
formData.append('photo', photo);
formData.append('name', name);
$.ajax({
url: 'api/store',
type: 'POST',
contentType: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
data: formData,
success: (response) => {
// success
console.log(response);
},
error: (response) => {
console.log(response);
}
});
});
});
Controller
class MyController extends Controller
{
use StoreImageTrait;
public function store(Request $request)
{
$data = $request->all();
$data['photo'] = $this->verifyAndStoreImage($request, 'photo', 'students');
Student::create($data);
return response($data, 200);
}
}
StoreImageTrait
<?php
namespace App\Traits;
use Illuminate\Http\Request;
trait StoreImageTrait
{
public function verifyAndStoreImage(Request $request, $filename = 'image', $directory = 'unknown')
{
if ($request->hasFile($filename)) {
if (!$request->file($filename)->isValid()) {
flash('Invalid image')->error()->important();
return redirect()->back()->withInput();
}
return $request->file($filename)->store('image/' . $directory, 'public');
}
return null;
}
}
<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready( function () {
$("form#data-form").on("submit",function (e) {
e.preventDefault();
var formData = new FormData(this);
//Ajax functionality here
$.ajax({
url : '{{route('blog.store')}}',
type : "post",
data : formData,
dataType : 'json',
success:function (data) {
console.log(data);
if(data.errors) {
}
if(data.success) {
}
$('#saveBtn').html('Save Data');
$('#saveBtn').attr('disabled',false);
}, // success end
contentType: false,
processData: false
}); // ajax end
}); // form submit end
}); //document end
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
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!');
}
I am trying to send some data from a modal dialog to my controller with Ajax. But my modelfields are always null, but I enter my actionmethod in the controller.
This is a shortend version of my cshtml-file.
#model anmespace.MyModel
<form method="post" id="formID">
...
<div class="row">
<div class="col-md-5">#Resource.GetResource("MyModal", "Firstname")</div>
<div class="col-md-7"><input type="text" class="form-control" id="firstname" value="#Html.DisplayFor(model => model.FirstName)"></div>
</div>
...
<input type="submit" class="btn btn-primary" value="Submit" />
</form>
<script>
$("#formID").on("submit", function (event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("ActionName", "Controller")",
data: frmValues,
success: function (data) {
alert(data);
}
});
});
</script>
Sorry MVC/Ajax are really new for me.
If you want to bind the form data to model then, the names of HTML elements should match with Model properties.
Note: name attribute value of html input field should match to the property of a model.
When you use form and submit button then it will try to reload the page by posting data to the server. You need to prevent this action. You can do this by returning false on onSubmit event in the Form element.
When you use jquery, do not forget to keep the ajax call/events inside the $(document).ready(function(){}) function.
I have written a simple code which takes First Name as input and makes an ajax call on clicking on submit button.
Html & Jquery Code:
<script>
$(document).ready(function() {
$("#formID").on("submit", function(event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("PostData", "Home")",
data: frmValues,
success: function(data) {
alert(data.FirstName);
}
});
});
});
</script>
<div>
<form method="post" id="formID" onsubmit="return false;">
<input id="FirstName" name="FirstName"/>
<input type="submit" value="submit" />
</form>
</div>
My Model :
public class Person
{
public string FirstName { get; set; }
}
Action Method:
public ActionResult PostData(Person person)
{
return Json(new { Success = true, FirstName = person.FirstName });
}
Output:
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>