MVC use jquery instead of submit button - javascript

On my page I have a section like this:
using (Html.BeginForm("AddSubTor", "Maintor", FormMethod.Post, htmlAttributes: new { ID = "frmSubTors" }))
{
#Html.AntiForgeryToken()
#Html.Partial("_SublistPartial")
<div class="row" style="margin-top: 15px;">
<div class="col-sm-12 col-md-12 col-lg-12 text-center ">
#* submit button here *#
<input type="submit" class="btn btn-default" value="Add" />
</div>
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
}
Instead of using the submit button, I would replace it then with an image that looks like a button, could I also do the same submit in a jquery function. Like in the click event of that button-like image? Would the data I'm submitting still be submitted?
The reason I want to do this is that in the partial I have two radio buttons. On both I have some Jquery code for retrieving data and other stuff.
If I use a simple submit button I can set the radiobuttons but there is no click event thus the data is not retrieved and other stuff is not done.
So if I can use Jquery, then I can simple call the functions that the radiobutton-click events call and so get my data.
[edit]
I'm kind of looking for something like this:
$.Ajax({
url: 'controller/action',
type: 'POST',
success: function(data) {
$('#frmSubTors').html(data);
}
}).done(function() {
// do my other stuff here
});
Would this work too?

Yes, you can use jQuery to submit the form when the image is clicked.
Replace the submit button with the image and give it an id.
<div class="col-sm-12 col-md-12 col-lg-12 text-center ">
#* submit button here *#
<img id="myImage" src="blah.jpg" />
</div>
Then have jQuery respond to a click event:
$(document).ready(function() {
$("#myImage").click(function() {
$("#frmSubTors").submit();
}
}
More click event info for jQuery: http://www.w3schools.com/jquery/event_click.asp

Yes, If you use $('#frmSubTors').submit(), The form will be submitted wit all the fields.

You could submit the form using your image event.
$('img').on("click", function () {
$('#frmSubTors').submit();
});

You can submit form with ajax like following.
$("#your_img_id").click(function () {
$.ajax({
type: 'POST',
url: '/Maintor/AddSubTor',
data: $(this).serialize(), //serializes the form's elements.
success: function (data) {
// do your other stuff here after succesful form submit
}
});
});
If your form has <input type="file"> then do like following.
$("#your_img_id").click(function () {
var formData = new FormData($('#frmSubTors')[0]);
$.ajax({
type: 'POST',
url: '/Maintor/AddSubTor',
data: formData,
cache: false,
contentType: false,
processType: false,
success: function(data) {
// do your other stuff here after succesful form submit
}
});
});
Hope this will help you.

Related

get all form data by jquery/js input fields ajax

Meanwhile I'm getting stuck on this issue. Normally, it's pretty simple but somehow it doesn't work for what I'm trying to do. I want to get all data from my form input fields by either Jquery or JS and then send them through AJAX to the server sided script (PHP). Even by using append or do it by serialize, I only obtain the object from input field with ID #file. I'm not using a submit button to confirm the uploaded image - only select the file and send it off.
I already tried too add
formdata.append("_token", document.getElementById('_token').val());
but whenever I try to append another element to the formdata the entire script stops working
By using $('#picUploadForm').serialize(); I do not get the any result from the input element with ID #file.
HTML:
<form enctype="multipart/form-data" id="picUploadForm">
<input type="file" name="file" id="file" style="display:none;" >
<input type="hidden" name="_token" id="_token" value="<?php echo $_SESSION['_token']; ?>" />
</form>
<!-- Default Avatar Image -->
<div class="click-slide overlay">
<!-- Profile Image-->
<img src="<?php if(isset($avatar['filelink']) && $avatar['filelink'] !='') { echo $avatar['filelink']; } else { echo "assets/images/avatars/default_avatar_large.png"; }?>" alt="" class="img-full-width-tight" id="imagePreview" />
<!-- Image update link -->
<div id="editLink" >
<span>
<a href="javascript:void(0);" class="pop-inline ti ti-image" ></a>
</span>
</div>
</div><!--/ click-slide-->
JS:
//On select file to upload
$('#file').on('change', function(e){
e.preventDefault();
var formdata = new FormData();
// any other code here....
} else {
// Upload Image to backend
formdata.append("file", document.getElementById('file').files[0]);
// formdata.append("_token", document.getElementById('_token').val()); // does not work!!!
// $('#picUploadForm').serialize(); // only returns data from input #_token
$.ajax({
url: "./serversided.php",
type: "POST",
data: formdata,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$("#statusav").removeClass().html('');
$('.overlay').LoadingOverlay("show");
HideLoadingOverlay();
},
success: function(data){
if(data.status === true){
// alert(data.imgURL);
setTimeout(function(){$("#statusav").removeClass('alert alert-danger').addClass('alert alert-success').html(data.reply)}, 2000);
$("#imagePreview").attr('src', data.imgURL);
} else {
// alert(data.error);
setTimeout(function(){$("#statusav").removeClass('alert alert-success').addClass('alert alert-danger').html(data.error)}, 2000);
}
}
});
}
});
.val() is a jQuery method - it is not a vanilla JS method, so it doesn't work when called on a plain element. document.getElementById will return an element (or null); $('selectors here') will return a jQuery object, on which you can use jQuery functions.
Try this instead, with vanilla JS:
formdata.append("_token", document.querySelector('#_token').value);
Or select the element with jQuery and use the jQuery method:
formdata.append("_token", $('#_token').val());

Perform validation in js as it is done in on submint

In my .Net core MVC app I am trying to post form from js ($.ajax)
Before posting from JS I am trying to validate inputs.
When I do submit from button
<input type="submit" class="btn-primary col-lg-6" value="Knjiži" />
My form return nicely formatted validation errors.
But when I try to validate my form inside JS on event bidden to click buuton like
<button id="knjiziDugme" class="btn-primary col-lg-6">Knjiži KO - Povrat</button>
$("#knjiziDugme").on("click", function (event) {
if ($("#formaKnjizi").valid()) {
var url = "../../PovratniceMpo/Knjizi"
var formData = $('#formaKnjizi').serialize();
$.ajax({
url: url,
type: "POST",
data: formData,
dataType: "json",
success: function (resp) {
console.log(resp);
}
});
};
});
My form be validated but messages are ugly
How I can preform validation inside JS as it does form automatically on Submit?

Jquery submit form on form input type 'file' change

I am submitting a form on the base of image selection, So file input change will submit the form, The issue is that it redirects me back to the same route as i am using laravel,
Jquery Code :
$('#profile-image-upload').change(function(e){
var profileImageForm = $("#profileImageForm");
profileImageForm[0].submit(function(e){
e.preventDefault();
var file_data = $('#profile-image-upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "/freelance/change-profilePic",
data: form_data,
type: 'POST',
success: function (data) {
console.log('Success');
},
error: function (xhr, status, error) {
console.log('error');
}
});
});
});
HTML :
<div class="profile__img">
<form id="profileImageForm" method="post" enctype="multipart/form-data">
<input id="profile-image-upload" class="" name="file" type="file">
</form>
<img src="{{asset('freelance/img/demo/people/3.jpg')}}" alt="" id="profile-image">
</div>
Note: var profileImageForm = $("#profileImageForm") returns an array which i have no idea how a form can be an array, So i am submitting form like profileImageForm[0].submit(function(e){}
Got idea why form submit redirecting ?
You are submitting your form but not listening submit event. form.submit() and form.on('submit', function(){ }) are different. form.submit() will only submit your form and doesn't accept any parameters. So your function in submit is ignored. Instead of using
profileImageForm[0].submit(function(e){ });
use
profileImageForm.on('submit', function(e){
e.preventDefault();
//
// your uploader code goes here;
//
}).submit();
The problem is probably in your Laravel controller. Please check the return action of your controller.
you can prevent this by adding e.stopPropagation()

How do I close javascript popup box after validation is successful with php ajax call

In my html form, a popup window appears for registration. It validates data with an ajax/query call with regProcess.php page. This page is passing data to html form with json_encode. Well, when all validation is successful I want to close the html popup box after few second. How can I do this?
<script>
$('#form1').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'backup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#info1').html('');
$.each( data, function( key, value ) {
$('#info1').append('<p>'+value+'</p>');
});
}
});
});
</script>
The popup window appears with following div call.
<div id="register">
<a class="big-link" data-reveal-id="myModal">
<button type="button" name="" value="" class="css3button">Join the campaign</button>
</a>
</div>
You can put a jquery function in the success function with the setTimeout()
http://www.w3schools.com/jsref/met_win_settimeout.asp

Javascript/JQuery: On form submit, don't reload full page (only a div), and still submit form data

I've got the following code that I use on my links. This prevents the page from reloading and loads the content from the href tag in a div.
$("a[rel='right']").click(function(e){
e.preventDefault();
pageurl = $(this).attr('href');
$.ajax({url:pageurl.replace('index.php', 'rightcolumn.php')+'&rel=right',success: function(data){
$('#WMS_NEW_right').fadeOut(500, function(){ $('#WMS_NEW_right').html(data).fadeIn(1000); });
}
});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
My Question:
I need the use the same concept behind this, except on form submit, it needs to not reload the page, but submit the form only inside a div #WMS_NEW_right. How can I do this? I don't need push state or anything, just need to be able to control that form with class="formrelright" to only reload a div and get the url from the form action. I will also need all data from the form method="POST" on the new page (inside div)
From my understanding, you want to use ajax to post a form without reloading the page during the form submission. So I would consider the following:
$('.formrelright').submit(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: 'POST',
data: $(this).serialize(),
success: function(data) {
// Whatever you want
}
});
});
Either use target and an IFrame, or JQuery to submit the form in the background. The latter is preferable if you want to use the contents of the response.
JQuery post()
Maybe try it like this:
HTML:
<!-- Notice there is no 'form' element -->
<div id="myform">
<input type="text" name="firstName"><br>
<input type="text" name="lastName"><br>
<button type="button" id="submit_myform">Submit</button>
</div>
<div id="resultArea"></div>
<!-- the biggest critique about this method might be that
yes, it is not very semantic. If you want to use a form,
just throw in an 'e.preventDefault()' in your jQuery -->
jQuery:
$('#submit_myform').on('click',function() {
var firstName = $('input[name="firstName"]').val(),
lastName = $('input[name="lastName"]').val();
$.ajax({
type: "POST",
url: 'form.php',
data: {
firstname: firstName,
lastname: lastName
},
//the success function is automatically passed the XHR response
success: function(data) {
$('#resultArea').html(data);
},
});
});

Categories

Resources