jquery with boxy plugin - load and submit a form via ajax - jquery-plugins

I am using JQuery with Boxy plugin.
When a user clicks on a link on one page, I call Boxy.load to load a form onto the pop-up. The form loads and is displayed inside the pop-up without problems.
However, I can't bind the form to a submit event, since I can't select the form element.
This is the event handler:
$('#flag-link a.unflagged').click (function(e) {
url = $(e.target).attr('href');
Boxy.load(url, {behaviours: function(r) {
alert ($("#flag-form").attr('id'));
}
});
});
The alert reads "undefined" when it is displayed.
And this is the form:
<form id="flag-form" method="POST" action="somepage">
<table>
<tr><td><input type="text" name = "name"></td></tr>
<tr><td><input type="submit" value="OK"></td></tr>
</table>
</form>
What am I doing wrong?

First (a minor point, but a potential source of trouble), it should be id="flag-form" not id = "flag-form" (no spaces).
Second, you shouldn't need r.find(). Just do $("#flag-form").attr("id")

As far as I understand, live() method must be used to bind an element to an event in this case:
$("#flag-form").live("submit", function(){ ... }
Presently, live method is documented to be not supporting the submit event. However, I could work it out with Chrome and FF. On the other hand, I couldn't get it working in IE. A better way for cross-browser compatibility seems to be binding the submit button of the form to the click event.
$("#flag-form-submit").live("click", function(){

I learnt that declaring methods in behaviours: function (e) {} works, in addition to using live() methods.
E.g.:
$('#flag-link a.unflagged').click (function() {
Boxy.load(this.href, {
behaviours: function(r) {
r.find('#flag-form').bind('submit', function() {
// do on submit e.g. ajax calls etc.
});
}
});
return false;
});

Boxy opens the URL (url = $(e.target).attr('href');) in an iframe. So you cannot find the form from the opening page(parent page). Your code to bind the form should be in the child page (ie, the Boxy iframe). You can check the iframe URL using your code, url = $(e.target).attr('href');

Related

Send form to server in jquery

I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})

How can I change the style of a div on return from a form submit action in Razor MVC3?

I have a Razor/ASP/MVC3 web application with a form and a Submit button, which results in some action on the server and then posts back to the form. There is often some delay, and it's important that users know they should wait for it to complete and confirm before closing the page or doing other things on the site, because it seems users are doing that and sometimes their work has not been processed when they assume it has.
So, I added a "Saving, Please Wait..." spinner in a hidden Div that becomes visible when they press the Submit button, which works very nicely, but I haven't been able to find a way to get the Div re-hidden when the action is complete.
My spinner Div is:
<div id="hahuloading" runat="server">
<div id="hahuloadingcontent">
<p id="hahuloadingspinner">
Saving, Please Wait...<br />
<img src="../../Content/Images/progSpin.gif" />
</p>
</div>
</div>
Its CSS is:
#hahuloading
{
display:none;
background:rgba(255,255,255,0.8);
z-index:1000;
}
I get the "please wait" spinner to appear in a JS method for the visible button, which calls the actual submit button like this:
$(document).ready(function () {
$("#submitVisibleButton").click(function () {
$(this).prop('disabled', true);
$("#myUserMessage").html("Saving...");
$("#myUserMessage").show();
$("#hahuloading").show();
document.getElementById("submitHiddenButton").click();
});
});
And my view model code gets called, does things, and returns a string which sets the usermessage content which shows up fine, but when I tried doing some code in examples I saw such as:
// Re-hide the spinner:
Response.write (hahuloading.Attributes.Add("style", "visibility:hiddden"));
It tells me "hahuloading does not exist in the current context".
Is there some way I am supposed to define a variable in the view model which will correspond to the Div in a way that I can set its visibility back from the server's action handler?
Or, can I make the div display conditional on some value, in a way that will work when the page returns from the action?
Or, in any way, could anyone help me figure out how to get my div re-hidden after the server action completes?
Thanks!
Is this done with ajax? I would assume so because the page is not being redirected. Try this:
$(document).ready(function () {
$("#submitVisibleButton").click(function () {
$(this).prop('disabled', true);
$("#myUserMessage").html("Saving...");
$("#myUserMessage").show();
$("#hahuloading").show();
document.getElementById("submitHiddenButton").click();
});
$("#hahuloading").ajaxStop(function () {
$(this).hide();
});
});
As an aside, you no longer need runat=server.

Show div if validation fails

I want this div to show if the form validation is unsuccessful.
<div class="alert">
<strong>Warning!</strong> #Html.ValidationSummary(false, "Fix these errors:")
</div>
I tried to wrapped it inside
if(! ViewData.ModelState.IsValid)
but div is not displayed when submitting the form. Probably because there is not post back due jquery validation. The validation logic seems alright, if i remove the if-statement validation summary list all incorrect input fields.
How can I toggle the visibility of the div based on the validation?
Update
I rewrote the accepted answer. If the server connection is slow the error div will be visible during the server request. Even if there is no errors. I changed it to check if the form is valid when submitting the form. This code snippet assumes you have one form.
$(document).ready(function () {
$(".alert").hide(); //hides the div on page load
$("form").submit(function () {
if (!$(this).valid()) {
$('.alert').show();
}
});
});
You can apply this simple script. It's not very sophisticated, but it should do the trick
$(document).ready(function () {
$('.alert').hide(); //hides the div on page load
$('#submit').click(function () { //assumes your submit button has id="submit"
$('.alert').show(); //shows the div when submit is clicked
});
});
As you can see, this doesn't actually care about the validation. It simply makes the 'alert' div visible when the submit button is clicked. If there are validation errors, the div will show with your warnings. If the form is valid, I'm assuming a refresh, or redirect, so the div will never actually have a chance to show.

MVC button click to action [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Mvc Html.ActionButton
With ASP.NET MVC 3 I know how to create a link to an action method very easily but what I'd like to know is how do you make a button (when clicked) call a particular action method?
Sachin,
If you're using jquery (which you don't mention but I'll show as it's fairly standard with mvc), you'd do the following:
$('#buttonId').click(function(){
document.location = '#Url.Action("MyAction","MyController")';
});
of course, you'd probably want to use ajax, but this is a basic example.
You could use an html <form>:
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Get))
{
<input type="submit" value="Click me" />
}
How do you do it?
The same way you would if not using MVC.
<INPUT TYPE="BUTTON" VALUE="Home Page" ONCLICK="window.location.href='/Controller/Action'">
As well as Darin's answer about using a form GET method, you can also call javascript functions that will then in turn call an action.
You can intercept the button click event when clicked and run your own code. That code can call an action asynchronously using Ajax or just simply navigate to an action method
Here's sample javascript that intercepts the button click event
$(document).ready(function () {
myButton.onclick = function (event) {
// in here you can call an ajax method or just navigate to an action
return false;
}
// or using jQuery
$('#myButton').click(function (e) {
// do whatever here
e.preventDefault;
});
});
Or you can intercept a button that has an href attribute
$(function () {
$("#myButton").click(function () {
var href = $(this).attr("href");
var route = href + "?paramName=" + $('#SomeValue').val();
$(this).attr("href", route);
});
});
This adds parameter information that you may have stored in another input on the page and appends it to the Url and then navigates to the action

jQuery.validate stops my form from being submitted

jQuery.validate stops my form from being submitted. I would like it to just show the user what is wrong but allow them to submit anyway.
I am using the jquery.validate.unobtrusive library that comes with ASP MVC.
I use jquery.tmpl to dynamically create the form and then I use jquery.datalink to link the input fields to a json object on the page. So my document ready call looks something like this.
jQuery(function ($) {
// this allows be to rebind validation after the dynamic form has been created
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($("form"));
// submit the answers
$("form").submit(function(e) {
$("input[name=jsonResponse]").val(JSON.stringify(answerArray));
return true;
});
}
I note that there is an option
$("form").validate({ onsubmit: false });
but that seems to kill all validation.
So just to recap when my form is rendered I want to show all errors immediately but I don't want to prevent the submit from working.
So after some research (reading the source code) I found I needed to do 2 things
add the class cancel to my submit button
<input id="submitButton" type="submit" class="cancel" value="OK" />
This stops the validation running on submit.
To validate the form on load I just had to add this to my document ready function
$("form").valid();
Hope this helps someone else

Resources