Post Asp.net Form Using AJAX - asp.net

I am a little new to JQuery. let's suppose that we have this jquery function :
var f = $("#myForm");
var url = f.attr("action");
var formData = f.serialize();
$.post(url, formData, function(data) {
$("#postResult").html(data);
});
and this form :
<form id="myForm" action="/Monitor/Test/FormPost" method="post">
<div>First Name: <input name="FirstName" type="text" value="Bob" /></div>
<div>Last Name: <input name="LastName" type="text" value="Cravens" /></div>
<div>Age: <input name="Age" type="text" value="43" /></div>
<input type="submit" value="Save Contact" />
<div id="postResult">?</div>
</form>
How can I bind the save button with the jquery function ? Thank you

One simple way would be to bind to the click event of the button. Something like this:
$('#myForm input[type="submit"]').click(function () {
var f = $("#myForm");
var url = f.attr("action");
var formData = f.serialize();
$.post(url, formData, function(data) {
$("#postResult").html(data);
});
});
This specifically looks for the submit input that's a child of the form of id "myForm" (in case there are other buttons, etc.) and responds to its click event with the function in question.
Just to be safe, since you're essentially short-circuiting the form and posting via AJAX, you should also probably change the submit to a normal button:
<input type="button" value="Save Contact" />
Or perhaps:
<button value="Save Contact" />
Which would change your jQuery selector to:
$('#myForm input[type="button"]')
Or:
$('#myForm button')

$(document).on("click","input[type=submit]",function(e)
{
e.preventDefault();
var form = $(this).closest("form");
$.post(form.attr("action",form.serialize(),function(d){
//result
});
});
more general way.

//this handler can work on any form that need to post all values
$("form input[type='submit']", f).click(function(e){
e.preventDefault();
var $this = $(this);
var f = $this.parents('form');
var url = f.attr("action");
var formData = f.serialize();
$.post(url, formData, function(data) {
$("#postResult").html(data);
});
return false;
})
In this code you are subscribing click event.
[e.preventDefault();][1] will stop your form from premature submittion and you can do the work you want.

Related

Close modal with search results when clicking outside?

I'm trying to close a modal div with AJAX search results, but nothing works.
I have tested several solutions on SO but nothing works?!
This is the code I have right now:
<form action="/search" method="get">
<input type="hidden" name="qt" value="main">
<div class="searchBox" id="search">
<input type="text" name="q" id="find" placeholder="Search here..." class="mainSearchField" />
<div class="searchBoxResults" id="search_items"></div>
</div>
</form>
<script>
$(document).ready(function() {
$( "#find" ).keyup(function(){
fetch();
});
});
function fetch() {
var val = document.getElementById("find").value;
$.ajax({
type: 'post',
url: '/include/functions/searchFetch.php',
data: {
q:val
},
success: function (response){
document.getElementById("search_items").innerHTML = response;
}
});
}
</script>
UPDATE
This is what I have tried to add, to the above:
window.onclick = function(event) {
if (event.target.id != "search_items") {
$("search_items").hide();
}
}

How do I call my own API from a View? ASP.NET MVC

I have an API that I've created for user registration / authentication, and similar operations. Example post method:
[AllowAnonymous]
[HttpPost("authenticate")]
public IActionResult Authenticate([FromBody]AuthenticateModel model)
{
var user = _userService.Authenticate(model.Username, model.Password);
if (user == null)
return BadRequest(new { message = "Username or password is incorrect" });
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.Role)
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
// return basic user info and authentication token
return Ok(new
{
user.Id,
user.Username,
Token = tokenString,
});
I now need my front-end to implement my API. So I'd like to call this API from a View. For example, say I want to create a simple login page:
<div class="row">
<div class="col-md-12">
<form method="post" action="">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" />
<span asp-validation-for="Username" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
How would I now call the authenticate post method for this login form? As I have a controller which is the API controller, and I have a controller which is the action controller, for the users.
File structure if needed:
File structure
Calling your own web action can be done in mainly two ways:
Native HTML form submission.
AJAX
Native submit reloads your entire page. And address will be changed to the URL or your web action. Typically used as a search function, like:
<form asp-controller="Search" asp-action="Blogs" method="get">
<input type="text" name="question" />
<input type="submit" />
</form>
When the user submit the form with clicking the submit button, the browser will be redirect to /search/blogs?question=textHeInput.
To prevent page refreshing, you can submit a request with pure JavaScript. Which called AJAX.
https://en.wikipedia.org/wiki/Ajax_(programming)
For example:
// Require jQuery:
$.post('/authenticate', { "yourPropertyName" : "yourPropertyValue" }, function(response) {
// Do something after the request. Access response like this:
alert(response.Username);
});
And server responded username will shown.
You can use ASP.NET MVC Core Tag Helpers:
<form asp-controller="MyControllerName" asp-action="Authenticate" method="post">
<!-- Input and Submit elements -->
</form>
Since you're using JwtBearer with WebAPI's, an assumption is that you're probably going to call your authentication method using Ajax. Unfortunately you did not provide your class declaration showing your route convention for your ApiClass but normally it goes as "api/[Controller]"... If this is the case, you can do the following:
$("submitButton").click(
function authenticateUser()
{
$.post(
'/api/[COntrollerName]/authentication', // URL
$('#form").serialize(), // this is your form data as an object
function(payload) //Response
{
// do something with payload here
}
});
}
);
<button type="submit" class="btn btn-primary" id="submitButton">Login</button>
You might want to set your <button type="button"> so that the form doesn't submit. Attach a click event to that function, so that it processes the api call.

How to get the right submit from a form in a list of forms in meteor?

I have a list of forms in a page of my meteor app, the list is generated dynamically and all the forms have the same class.
So i made the event submit on the events area of my template, but when i submit the form, only the first form works, if i submit the second form for example, meteor event understand that the event came from the first, and i don'k know how to pass the form id to meteor events, so i can't get the data from the right form. Someone can help me?
This is my event:
'submit .form-equation': function (e, t) {
e.preventDefault();
var name = t.find('#name').value,
equation = t.find('#equation').value,
order = Number(t.find('#order').value),
isChart = t.find('#isChart').checked;
var equationData = {
name: name,
equation: equation,
order: order,
isChart: isChart
};
var station = Stations.findOne(Session.get('stationNewID'));
var sensorId = t.find('#sensorId').value;
Meteor.call('insertEquation', station, sensorId, equationData, function (error, result) {
if (error)
console.log(error);
});
}
I think there is something else wrong with your application. The behavior you described (having multiple forms of the same class with different IDs) works correctly on a clean example.
Check out the demo I made that demonstrates this: http://meteorpad.com/pad/8CPL2xvS7taeL6jZS/MultipleFormSubmitExample
Basically, the forms look like this:
<template name="example">
<form id="1" class="yolo">
<input type="submit" value="Submit">
</form>
<form id="2" class="yolo">
<input type="submit" value="Submit">
</form>
<form id="3" class="yolo">
<input type="submit" value="Submit">
</form>
</template>
And there is only one event listener:
Template.leaderboard.events({
'submit .yolo': function (e, t) {
e.preventDefault();
alert($(e.target).attr('id'));
}
});

Refresh GridView to an other WebForm

I have a Gridview on "Webform1.aspx" ,i want when i click the refresh button on "webform2.aspx","webform1.aspx" refresh or better way "webform1.aspx" gridview just refresh.
Provided that from webform1 opened the webform2, try:
webform2.aspx From here you can refresh the webform1.asp or you can call a function.
<script>
function refresh_webform1(){
window.opener.location.reload();
}
function CallFunctionFrom_webform1(){
//example function display_ct();
window.opener.display_ct();
}
</script>
<input type="button" onclick="refresh_webform1()" value="Refresh webform 1">
<input type="button" onclick="CallFunctionFrom_webform1()" value="Call Function From Webform1">
webform1.aspx
<script>
function openWebform2(){
window.open("webform2.aspx","windowName", "width=200,height=200,scrollbars=no");
//or
//window.open("webform2.aspx","_blank" );
}
//example function display_ct();
function display_ct() {
var x = new Date();
document.getElementById('ct').innerHTML = x;
}
</script>
<span id='ct' ></span>
<input type="button" onclick="openWebform2()" value="Open WebForm 2">

pass values from view to controller

in my html5 page there is a search textbox with a haperlink. when i click on hyperlink value does not goes to controller. i can not use form because on this page i am already using a form.
<input type="text" name="searchval"/>
Go!
and in controller
function user()
dim val as string = Request("searchval")
but searchval always return nothing even i put some text in textbox. Please help
Hyperlinks do not submit forms. You need a form tag and a submit button.
<form action="/users" method="POST">
<input type="text" name="searchval"/>
<input type="submit" value="Go!" />
</form>
You also need to make sure your VB.NET method is routed to appropriately by the form action and is actually a controller action:
Function User() As ActionResult
when you click on hyperlink call ajax function.
function Searchfunction() {
var searchValue = $("#searchval").val();
$.ajax({
url: '#Url.Action("Action", "Controller")',
data: { "searchval": searchValue },
success: function (result) {
$('#dvSearch').html(result);
}
});
}

Resources