ajaxForm (malsup) doesn't work on the first submit - ajaxform

I'm using jquery ajaxform malsup to submit my form. My form is file.php and when submitted, it will be processed in process.php.
The problem :
The submission doesn't work on the first attempt. I have to refresh the page again and reinput the data to submit it in order for it to work...
And here is the submission code :
$(document).ready(function() {
var options = {
success: function() {
$('.loadergif2').remove();
var self = $(this);
noty({
text: 'Save Successful!',
type: 'success',
dismissQueue: true,
timeout: 3000,
layout: 'bottomRight'
});
}
};
$('#Frm006').submit(function() {
$(this).find('.webblock-btn-area').append('<div class="loadergif2"></div>');
tinymce.triggerSave()
$(this).ajaxSubmit(options);
return false;
});
});
</script>
And the form
<form action="process.php" id="Frm006" method="post" class="general-form" enctype="multipart/form-data">
..............//rest of form code
</form>
Do I missing something?
Thanks for your help~~~

Related

Using dropzone.js in vue, calling function with image file name

I'm having a hard time getting anything to work with this the way I need it, but I have a working dropzone instance in my Vue project.
I can upload the image and call functions within the dropzone code, however, I need to call a function directly from the form in the html in order to send the 'card' object.
All I need to do is call a function when a file is added through the dropzone form, with the filename.
My code:
<div class="uk-width-3-10">
<form v-on:change="imageChange(card)" method="post" action="{{url('product/parts/upload/store')}}" enctype="multipart/form-data"
class="dropzone" v-bind:id="'dropzone-'+i">
</form>
</div>
...
imageChange(Card){
console.log('working');
},
addCard(){
Vue.nextTick(function () {
new Dropzone("#dropzone-"+cardIndex, {
maxFilesize: 12,
renameFile: function (file) {
var dt = new Date();
var time = dt.getTime();
return time + file.name;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
removedfile: function (file) {
console.log(file.upload.filename);
var name = file.upload.filename;
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
},
init: function() {
this.on("addedfile",
function(file) {
instance.imageZoneNames.push({name: file.upload.filename});
console.log(file);
console.log(instance.imageZoneNames);
});
}
});
});
}
Dropzone has many events, You used removedfile() event! there is another event called addedfile() and executes when a file is added to the dropzone list
imageChange(card) {
console.log(card)
},
addCard() {
Vue.nextTick(() => {
new Dropzone('#dropzone-` + cardIndex, {
addedfile(file) {
this.imageChange(file);
}
}
}
}

jQuery Form plugin submit several forms but wait until previous has ended

Users are abled to add new forms which are all submited with one button click and "jQuery Form plugin". To submit each form I iterate over forms which have a certain class.
As the users can submit images and the server has to do some work with each Image I´d like to wait until the previous submit has finished with a success statusText. Currently (I just do a timeout of 2000 which is nothing more than a "hackish" solution.)
I think I can use success function for this but do not know how I connect my submit loop with the returned success statusText. Here is a fiddle.
Here what I have:
var userform = '<form class="myForm" action="up.php" method="post"> ' +
'Name: <input type="text" name="name" />' +
'file: <input type="file" name="img[]" multiple />' +
'Comment: <textarea name="comment"></textarea>' +
'<input type="submit" value="Submit Comment" />' +
'</form>';
function showResponse(responseText, statusText, xhr, form) {
if (statusText === "success") {
console.log("the submit ended with success");
//submit next form should happen
}
}
var options = {
success: showResponse
};
$('#add').click(function() {
$(userform).appendTo('.append').each(function() {
$('.myForm').ajaxForm(options);
});
});
$("#all").click(function() {
var collection = $('.myForm');
if (collection.length > 0) {
var i = 0;
var fn = function() {
var element = $(collection[i]);
$(element).submit().addClass('done').hide("slow");
if (++i < collection.length) {
setTimeout(fn, 2000);
}
};
fn();
}
});
Thanks!
The submit handler simply does a std POST/GET so you aren't going to get a response back. You are going to want to change your code to use ajax and then have the server return a response of success = true/false or whatever you prefer
https://jsfiddle.net/mj9dbLh1/3/
Change this...
var element = $(collection[i]);
$(element).submit().addClass('done').hide("slow");
if (++i < collection.length) {
setTimeout(fn, 2000);
}
To something like...
var element = $(collection[i]);
$(element).addClass('done').hide("slow");
$.post("ajax/test.html", function( data ) {
fn(); // DO SUCCESS ACTION HERE
});
Keep in mind this will execute on each success SO you may want to first get a count of the number of forms (which gives you the number of ajax calls). Then increment that count for each success action. Once you get your total you can Display ALL SUCCESS.
Take a look at these docs for more clues on how to handle errors and what not.
http://api.jquery.com/jquery.post/

MVC4 Ajax enabled WebGrid Jquery dialog not working when paging

I have an Ajax enabled WebGrid and inside this grid I have a column which generates an ActionLink, this ActionLink has a "class" added so I can catch it with jQuery and open a Dialog based on the URL passed -> this URL is a call to a method which returns a PartialView.
This is working for all buttons on first page, as soon as I change the paging the script is not called and my partial view is displayed without a layout. So the action is executed but not through javascript (where I put return false; so I don't get double postbacks).
Code:
#Code
Dim grid As New WebGrid(Model,
rowsPerPage:=10,
canSort:=True,
canPage:=True,
ajaxUpdateContainerId:="ajaxGridClientBookingWL",
fieldNamePrefix:="ajaxGridClientBookingWL",
pageFieldName:="ajaxGridClientBookingWL")
End Code
<div id="ajaxGridClientBookingWL">
<script type="text/javascript">
$(document).ready(function () {
$(".popup-button").click(function () {
//debugger;
var href = $(".popup-button").attr('href');
InitializeDialog($("#modPop"), href);
$("#modPop").dialog("open");
return false;
});
function InitializeDialog($element, href) {
$element.dialog({
autoOpen: false,
width: 400,
resizable: true,
draggable: true,
title: "Department Operation",
modal: true,
closeText: '[Zapri]',
dialogClass: 'no-close normalpopup-dialog',
closeOnEscape: true,
open: function (event, ui) {
$element.load(href);
},
close: function () {
$(this).dialog('close');
}
});
}
});
</script>
<div id="modPop">
</div>
<table cellpadding="3px">
<tr>
<td>#grid.GetHtml(tableStyle:="gridTable", headerStyle:="gridHeader", rowStyle:="gridRowStyle", alternatingRowStyle:="gridAlternatingRow",
columns:=grid.Columns(
grid.Column(header:="Datum", columnName:="DateInserted", canSort:=True, format:=##<text>#NiRISHelpers.SpanDateToShort(item.DateInserted)</text>),
grid.Column(header:="", format:=##<text>#Html.ActionLink("Izberi", "KomitentBookingWLPreveril", "Pregled", New With {.area = "Komitent", .ID = item.IDrec}, New With {.class = "popup-button"})</text>)
))</td>
</tr>
</table>
</div>
You can see I set a debugger which catches my action if on first page, it does not when I page this grid.
I put everything inside the div which is designated as ajaxUpdateContainerId, tried to put it outside of it but nothing seems to work.
The partial view is just a simple #Html.DisplayFor(....).
Edit - solution:
As per #JoeJoe87577 accepted answer below, here is my new code (the rest is the same as above only scripts and grid.column are changed):
<script type="text/javascript">
function readyTheButton() {
var href = $(".popup-button").attr('href');
InitializeDialog($("#modPop"), href);
$("#modPop").dialog("open");
return false;
}
function InitializeDialog($element, href) {
$element.dialog({
autoOpen: false,
width: 400,
resizable: true,
draggable: true,
title: "Department Operation",
modal: true,
closeText: '[Zapri]',
dialogClass: 'no-close normalpopup-dialog',
closeOnEscape: true,
open: function (event, ui) {
$element.load(href);
},
close: function () {
$(this).dialog('close');
}
});
}
</script>
And the grid.Column:
grid.Column(
header:="",
format:=##<text>#Ajax.ActionLink(
"Izberi",
"KomitentBookingWLPreveril",
"Pregled",
New With {.area = "Komitent", .ID = item.IDrec},
New AjaxOptions With {
.HttpMethod = "GET",
.InsertionMode = InsertionMode.Replace,
.UpdateTargetId = "modPop",
.OnBegin = "readyTheButton()"})</text>)
Pretty simple, the $(document).ready(function () { }); event is only fired when the page is loaded and everything is ready. But when you page the grid, all the buttons are reloaded by ajax and non of them has the click event attached.
1fst Solution:
Look in the documentation for the paging event of your grid (usually every grid has such an event), attach the click event to your actionlinks everytime the grid has changed the page.
2nd Solution:
Apply an onclick attribute to your actionlinks on the server, this onclick can lead to your InitializeDialog function.
(Edit) Addition: You could try not to use a javascript event handler, but the built in Ajax Actionlink. This will keep your page clean and you don't have to deal with javascript event handling.

MVC How to handel submit button on dynamically added partialview

Hi I have just started MVC Programming, so pls excuse my noob question.
I have a Index View with dropdown. And According to the dropdown value, I have added a partial view '_create' in ContentDiv of Index using jquery.
$('#CreateButton').click(function (e) {
$("#ContentDiv").load('/Controller/_Create?Id=' + $("#DropDownList1").val());
});
So, now I am not sure how to handel submit button inside that partialview (_Create)
My _create form looks like:
#using (Html.BeginForm("_Create","controller", FormMethod.Post,
new { id = "addFormData", name="addFormData" }))
{
----------
----------
<p>
<input type="submit" value="Create" />
</p>
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult _Create(WorkFieldModel entity, FormCollection p_form)
{
addFormValuetoDB();
return PartialView();
}
And One more thing; how to maintain viewstate of dynamically added partial view after postback.
Any Help will be highly appreciated.
You could use an AJAX request to submit the form to avoid performing a full postback to the server and loosing the context:
$('#CreateButton').click(function (e) {
var data = { id: $("#DropDownList1").val() };
$("#ContentDiv").load('/Controller/_Create', data, function() {
$('#addFormData').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
alert('Thanks for submitting the form');
}
});
return false;
});
});
});
Since your HttpPost controller action returns a PartialView you could use this information in the success callback of the form submit and inject the result somewhere in the DOM.

How to pass textbox input value and dropdownlist selected value as input parameters to Controller in mvc4 using jquery?

I need to pass textbox input value and dropdownlist selected value to Controller in MVC4 ????????? For Eg : I have a Form with Textbox and Dropdownlist and a ( PartialView For Webgrid) . When i give datetime input to Textbox and Selected the "DoctorName" in Dropdown . Then i need to pass textbox input value and dropdownlist values as parameters to the controller ??????? My Controller is used to bind the webgrid in PartialView... The Code i tried which is not working......#doctortype is dropdownlist,#AppointmentDate is Textbox input datetime.
jquery:
<script type="text/javascript">
$(document).ready(function () {
$('#doctorType').change(function (e) {
e.preventDefault();
var url = '#Url.Action("Filter")';
$.get(url, { doctorname: $(this).val() }, { AppointmentDate: $('#AppointmentDate').val() }, function (result) {
$('#FilterWebgrid').html(result);
});
});
});
</script>
is not
$.get(url, `{ doctorname: $(this).val() }, { AppointmentDate: $('#AppointmentDate').val() }`, function (result) {
$('#FilterWebgrid').html(result);
});
You are sending two object. You have to send a single object like this:
$.get(url, { doctorname: $(this).val(), AppointmentDate: $('#AppointmentDate').val() }, function (result) {
$('#FilterWebgrid').html(result);
});
2) check the console and network tab and check if there is any error.
3) The value you are passing must be the same type as the parameter expected in the Action
This is just simple method to post data. If your controller returns data back to view, try $.getJSon();
<input type="text" value="doctor name" id="txtDoctor"/>
<select id="ddlDoctor"><option>SomeSelectedData</option></select>
<script>
$(document).ready(function() {
var txtValue = $('#txtDoctor').val();
var ddlValue = $('#ddlDoctor').val();
$.ajax({
url: '/controller/action',
data: { doc: txtValue, name: ddlValue },
traditional: true,
success: function(result) {
alert(result.status);
}
});
});
</script>
to know more about getJSon and JSON Result, check these links.
GetJson with parameters
JSON result in view