I am building a ASP.NET MVC webapplication and have a question:
Say that I have a strongly typed view, when hitting submit the object(of the strongly type) will be filled and sent to the server.
Now say that one of the properties of the strongly typed is not used in the form, instead I need to set this with javascript if the user press a button (not submit button).
How do I do this?
As I understand it, you want to assign a value to the property when a button is pressed?
Add it as a hidden input (sample uses Razor view engine):
#Html.HiddenFor(model => model.TheProperty)
Create a small jquery script:
<script type="text/javascript">
$('document').ready(function(){
// this is the id of the button that the user presses.
// It must have a "ID" attribute
$('#someButtonId').click(function() {
$('#TheProperty').val('Value to set');
});
});
});
</script>
You could use AJAX to send a request to the server with javascript. jQuery has great methods for doing so such as $.ajax, $.post, $.get. Example:
$(function() {
$('#someButtonId').click(function() {
// when some button is clicked send an AJAX request:
$.ajax({
url: '/home/someaction',
data: { someField: 'some value to send' },
success: function(result) {
alert('value successfully sent to server');
}
});
});
});
Related
I have a form which is sending data to another script with AJAX post. Idea is to change this to GET, so I can submit form or trough form input where user click "Submit" or just hit "Enter", and form data is passed with AJAX to another script, and data is returned to origin script.
What I want is to make user able just to type parameter in url, like whois.com/domain.com, and just hit enter, so my form can be autopopulated with data in url and submitted, so my JS can be trigerred to make AJAX call.
<script>
$('#form1').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'GET',
url: 'check.php',
data: $(this).serialize(),
success: function (data) {
//console.log(data);
$('#response').html(data);
$("#myModal").modal();
}
});
});
</script>
Idea: Check if $_GET['variable'] is set in url yoursite.com?domain=domain.com, and then pass variable to form, and submit form by code?
You could use location hash instead of query string. For example, you can use format: http://yoursite.com/#domain=domainname.com
Then, you can register hashchange event listener, and in event handler you can extract domain and pass it to ajax function.
window.addEventListener('hashchange', function(ev){
doNewAjaxRequest(location.hash.replace('#domain=', ''));
});
Or, if you are using jQuery:
$(window).on('hashchange', function(ev){
doNewAjaxRequest(location.hash.replace('#domain=', ''));
});
Or, you can use just domain name after the hash, as: #domainname.com
$(window).on('hashchange', function(ev){
doNewAjaxRequest(location.hash.replace('#', ''));
});
Now your users can type different domain, and when they press enter, you can handle the change.
*Keep in mind that anything after the # is not sent to server in url, but you can access and use it from javascript.
I am using a Bootstrap modal to display an ASP.Net MVC5 form, the form is inserted dynamically into a div using a jquery ajax call to the relevant controller and then opened.
I need to intercept the submission of the form so I would like to bind to the submit event of the form in jquery but have so far only been able to bind to the submit event of all forms since the dynamic forms are of course not present when the main view is rendered e.g.
$('form').submit(...)
rather than
$('#serverForm').submit(...)
Whilst this sort of works, it has a problem in that I actually have 3 different dynamic forms in this view which can be shown using modal popups, thus I need to do one of 2 things:
A) (ideally)manage to intercept the submit event for each form.
B) in the global form event handler, identify which form has been submitted.
I have tried every option I can imagine to use option A including adding the binding to the code which pops the modal. all without success.
I am currently trying to go with option B so that I can then decide where to post the form. This does at least get called when a form is submitted but my problem is that I cannot get the id or name of the form which has been submitted and thus have no way of knowing which one it is.
I have the following handler:
<script>
$(function () {
$('form').submit(function(e) {
// this is always null
var id = $(this).attr('id');
$.ajax({
url: '#Url.Action("EditServer", "AccountAdmin")',
data: new FormData(this),
...
});
});
});
</script>
Within this handler I have tried the following (plus a few more!) to get the form's id:
this.id
$(this).id
$(this).attr('id');
$(this).prop('id');
I have tried adding the handler after the ajax call to populate the modal like this:
$(".server-link").click(function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("href"),
cache: false,
type: "GET",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
$('#serverDiv').html(data);
$('#serverModal').modal('show');
$('form').submit(function (e) {
var id = $(this).attr(id);
// test to see if handler called
alert(id);
});
},
error: function (jgXHR, textStatus, errorThrown) {
//The commented out message is full of Html but includes compilation errors etc from the server
//alert('An error occured: ' + jgXHR.responseText);
alert(textStatus + ':' + errorThrown);
}
});
});
It's driving me bonkers! I have tried every combination of ideas from various posts with no joy. I need to post using FormData (in one case at least) because there is a file upload (an image) involved. Any assistance is much appreciated.
The problem is that your JavaScript code is running before the form has actually been added to the page. When using AJAX, you need to run whatever JavaScript you need in the callback:
$.get('/some/url', function (result) {
$('#whatever').html(result);
$('form').submit(function(e) {
var id = $(this).prop('id');
// do whatever with id
});
});
Use this instead:
var id = $(e.target).attr('id');
I am doing ajax cross domain request to my php page on server.
I am posting form from html via ajax to my php page on server.
Have problem with validation in client side.
I don't know how to do validation in client side before send form.
html form is standard form, posting input fields: name, last name, message....
My html form, client side:
<script type="text/javascript">
var output = $('.nesa');
$(document).ready(function(){
$("#form1").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'http://www.example.com/form.php',
crossDomain: true, //set as a cross domain requests
type: 'post',
data: $("#form1").serialize(),
beforeSend: function (){
// add spinner
$('.spinner').append('<img id="animacija" src="spinnersmall.gif" alt="Loading" />');
},
success: function (data) {
$(".nesa").html(data);
alert("sent " + data);
},
error: function(){
output.text('Message is not sent!');
}
});
});
});
How to to validation? I try to put code in beforeSend but without success.
Or maybe to use submitHandler?
Idea is when user click submit, that validation start, and if fails to tell "insert your email address". Now when i click submit it send data to server. I want that first check input fields.
This form is actual working it sending data to server, but just need to figure out how to do validation. Where to put validation in ajax call?
Thanks
Create a function to validate form which return true/false. Call the function just before the $.ajax. check if return is false then return.. see the example below...
if(!validateForm())
return false;
First, are you actually using an AJAX form?
You explained that you load the form itself via AJAX, but do you send it that way, too? It looks to me that you're trying to send it the HTML way. You can hook into the click event of the send button before you send the form. However, since the button is added to the page at runtime, you need to register the event to document.
$(document).on('click', 'input[type=submit]', function() {
// Validate form
// Add error message on fail, and return
// Else submit form via AJAX
});
In either case, you can use jQuery's blur event as an alternative to validate each field when the user jumps to the next. You could even validate every time the user presses a key with keypress.
I always validate them right before I enter them into an AJAX call. Here is my exampel
$('#form_nieuwsbrief').bind('submit',function(){
var name = $('input[name=naamNieuwsbrief]').val();
var email = $('input[name=emailNieuwsbrief]').val();
var proceed = true;
if (name==""){
$('input[name=naamNieuwsbrief]').css({'border':'2px solid red'});
proceed = false;
}
if (email==""){
$('input[name=emailNieuwsbrief]').css({'border':'2px solid red'});
proceed = false;
}
if(proceed == false){
$("#msg").append("<div class='alert alert-danger' role='alert'>U bent informatie vergeten in te vullen.</div>");
setTimeout(function(){
$('.alert').fadeOut(400, function(){
$(this).remove();
})
;},10000
);
}
if(proceed == true){ // make the ajax call
This is just a quick one for a newsletter that just requests name and email. But the principle is the same. Just before you make an ajax call, create the if else statement with a variable you set if something is false. else you stick it tot he original validation, thus you can proceed.
Please validate the form before sending ajax request. If there is no error then ajax request should be send otherwise return false.
You can do like:
$("#form1").submit(function (e) {
e.preventDefault();
// Get the Login Name value and trim it
var name = $.trim($('#name').val());
// Check if empty of not
if (name === '') {
alert('Text-field is empty.');
return false;
}
});
You can see the demo Here's (http://jsfiddle.net/LHZXw/1/)
You can also make a function onKeyup.
You're already validating via server side correct? Why don't you use that same validation rules to appear like your client side - via Ajax. I have a tutorial on how to do that:
http://michaelsoriano.com/how-to-ajax-validate-forms/
I want to get a text from a div#main, send the text via Ajax jQuery to a php file from where I wil send it via email.
The user can choose the recipient of the from a multiple radio buttons choices on the site.
After I send the data to the PHP file I want to do some styles (e.g. remove a class, etc..).
So far I have this, can you tell me if it is right?
$(document).ready(function(){
$('#submit').click(function(){
$.ajax({
type: 'POST',
url: 'email.php',
email: { recipient: $('input[type=radio]:checked').attr("value")},
data: { content: $('#main').text()},
success: function()
{
$("#email").removeClass("active");
}
});
});
});
PS: I dont have the PHP file yet, I want just to figure out if my Ajax solution above is the right way to do what I've described.
All of the data that you want to send back to the server needs to be in the data property. Also, you probably want to use the val() method rather than accessing the value attribute directly.
data: { content: $('#main').text(), recipient: $('input:radio:checked').val() },
$(document).ready(function(){
$('#submit').click(function(){
$.post("email.php", { recipient: $('input[type=radio]:checked').val(), content: $('#main').text()}, function(){
$("#email").removeClass("active");
});
});
});
using the checkTL() function, i need to send to the server (for example) only the input value into div with class "sideon". So, in the example, i need to get (server side) only the value of inputside0 and inputside3. How is possible this?
cheers
How about using AJAX?
<form method="POST" action="./index.php?general=example3" name="addtl">
...
</form>
and then:
$(function() {
$('form[name=addtl]').submit(function() {
var dataToPost = $(this).find('.sideon :input').serialize();
$.post(this.action, dataToPost, function(result) {
alert('success');
});
return false;
});
});
Of course putting input fields whose values shouldn't be submitted to the server into a form is doubtful. Maybe you should rethink the way you organize the forms.
two ways:
make them into lots of seperate forms.
do return false on the form submit in jquery and use $(".sideon").find('input').val(); to post an ajax query