Can someone please tell me the code I need, so that this form updates the database without needing a refresh?
#{
Layout = "~/_template1.cshtml";
var db = Database.Open("stayinflorida");
var CurrentUser = WebSecurity.CurrentUserId;
var userdetails = ("SELECT * from UserProfile WHERE UserId='8'");
var quserdetails = db.QuerySingle(userdetails, CurrentUser);
if (IsPost){
var updateuserdetails = "UPDATE UserProfile SET FirstName = #0, LastName = #1 WHERE UserID='8'";
db.Execute(updateuserdetails, Request["FirstName"], Request["LastName"]);
}
}
<h1>My Details</h1>
<hr>
<form method="post" action="~/Account/MyDetails.cshtml">
<fieldset>
<label>First Name</label>
<input class="input-xlarge" type="text" name="FirstName" placeholder=".input-xlarge" value="#quserdetails.FirstName">
<br>
<label>Last Name</label>
<input class="input-xlarge" type="text" name="LastName" placeholder=".input-xlarge" value="#quserdetails.LastName">
<button type="submit" class="btn btn-success">Update</button>
<button type="submit" class="btn btn-success">Cancel</button>
</fieldset>
</form>
What I have written kind of works, but I have to hit F5 for it to update, and it's just not what I want. I want to use jQuery/ajax, but I just don't know the code.
You need some JavaScript if you want to use AJAX. The jQuery library simplifies this. Here's an article I wrote that features AJAX updates using WebMatrix: http://www.mikesdotnetting.com/Article/176/WebMatrix-and-jQuery-Forms-Part-2-Editing-Data
Related
I am building a web application using the ASP.NET Core 3.1 MVC and Razor pages.
I am new to Razor pages.
I created a basic application using above. I created a registeration form having following three fields -
User name
User email address
Verification code
There are two buttons -
Send Code
Register
I am providing a feature in which the user can verify its email address before clicking on the "Register" button.
A verification code will be sent to the user to the email address, when user clicks on the "Send Code" button.
The user should then enter the code in the "Verification code" field and submit the form by clicking on the "Register" button.
Issue
When user clicks on the "Send Code" button, the code is send but the form data gets cleared i.e. "User name" and "User email address" fields values get erased. I used Ajax to call the "Send verification code" function. Following is the code -
Index.cshtml
<form class="form-horizontal" method="post">
<div class="form-row">
<label class="col-sm-2 control-label">Credentials</label>
</div>
<div class="form-group row">
<label asp-for="user.UserName" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input type="text" asp-for="user.UserName" class="form-control" id="UserName"
name="UserName" placeholder="Enter Full Name"
value="">
</div>
</div>
<div class="form-group row">
<label asp-for="user.UserEmailAddress" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input type="text" asp-for="user.UserEmailAddress" class="form-control"
value=""
name="UserEmailAddress" placeholder="Enter Email Address" id="UserEmailAddress">
<div class="form-inline">
<button id="btn1"
class="btn btn-primary mb-sm-1">
#Model.EmailVerifCodeLabel
</button>
<div id="grid" class="col">
<input type="text" asp-for="user.EmailVerifCode"
class="form-control" id="Emailverifcode" placeholder="Enter code">
</button>
</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Register</button>
</div>
</div>
</form>
#section Scripts {
<script type="text/javascript">
$("#btn1").click(function () {
var UserName = $("#UserName").val();
var UserEmailAddress = $("#UserEmailAddress").val();
alert(UserName);
alert(UserEmailAddress);
$.ajax({
url: "#Url.Page("/Register")?handler=SendEmailVerificationCode",
method: "GET",
data: { UserName: UserName, UserEmailAddress: UserEmailAddress }
})
});
</script>
}
Index.cshtml.cs
public JsonResult OnGetSendEmailVerificationCode(string UserName, string UserEmailAddress)
{
Random generator = new Random();
String verifCode = generator.Next(0, 999999).ToString("D6");
_configuration.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;
HttpContext.Session.SetString("verifCode", verifCode);
_myemailSender = new EmailSender();
var emailresult = _myemailSender.SendEmailAsync(UserName, UserEmailAddress, verifCode, _configuration);
return null;
}
Question: What is the reason for the razor pages form data getting erased even after using Ajax call?
When user clicks on the "Send Code" button, the code is send but the form data gets cleared i.e. "User name" and "User email address" fields values get erased.
<button id="btn1" class="btn btn-primary mb-sm-1"> Model.EmailVerifCodeLabel</button>
You do not specify the type attribute for above <button> tag within your <form>, it would work as a submit button, which cause form submit and user inputs cleared.
To fix it, you can try to explicitly specify type="button" for btn1 button.
<button id="btn1" type="button"
class="btn btn-primary mb-sm-1">
#Model.EmailVerifCodeLabel
</button>
Or call preventDefault() method to prevent it from submitting a form.
$("#btn1").click(function (evt) {
evt.preventDefault();
var UserName = $("#UserName").val();
//...
my input for example :
<div class="form-group">
<label for="name">New Name Offers :</label>
<input name="newNameOffers" class="form-control" id="newNameOffers">
</div>
<div class="form-group">
<label for="">From Email :</label>
<input name="fromEmail" placeholder="Email" class="form-control" id="fromEmail">
</div>
How can i put it on text area ....
That my textArea :
<textarea class="form-control" name="HEADER" id="HEADER" rows="11">i need to dispay my values here <textarea>
(i need to put the values not the name of variable)
I have tried to make a simple form for you. You can modify it as you wish. For this, you need to take help of javascript or other similar front end technologies. However, if your requirement is just to take the value to back end then you can get both value $request->newNameOffers and $request->fromEmail then you can concatenate and store in your desired way.
function myFunction() {
var val1 = document.getElementById("newNameOffers").value;
var val2 = document.getElementById("fromEmail").value;
var res = val1 +' '+ val2;
document.getElementById("HEADER").innerHTML = res;
}
<!DOCTYPE html>
<html>
<body>
newNameOffers:<br>
<input name="newNameOffers" onChange="myFunction()" class="form-control" id="newNameOffers">
<br>
fromEmail:<br>
<input name="fromEmail" placeholder="Email" class="form-control" onChange="myFunction()" id="fromEmail">
<p>Click the button to alert the contents of the text area.</p>
<!-- <button type="button" onclick="myFunction()">Try it</button> -->
<br>
<textarea id="HEADER"></textarea>
<script>
</script>
</body>
</html>
Why do you want to put it using Laravel, You can do it in the front-end(JavaScript, JQuery, Vue.js, React) itself.
I am using codeigniter for developing my website.When submitting form Iam variables separated with ? and &. I want variables separated with slashes like below.
Now getting like this
http://example.com/controller/method?id=22&sd=31
I want an url like below
http://example.com/controller/method/22/31
Html Code is given below
<form action="<?php echo base_url();?>controller/method" method="get">
<div class="form-group">
<select id="id" name="id" class="selectcl form-control" data-live-search="true" title="Pick Your place" >
<option value="22" >22</option>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control" name="sd" id="sd" placeholder="Enter details" title="please choose">//getting values here by autocomplete
</div>
<div class="form-group">
<button type="submit" class="btn find" value="submit" ></i>Start </button>
</div>
</form>
Tried URI Routing and below
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
Please help me to find a solution.
change your form method get to post
<form id="form" action="<?php echo base_url('controller/method');?>" method="post">
add following jquery in the page.
$(function(){
$('button[type="submit"]').on('click', function(e){
e.preventDefault();
var id = $.trim($('#id').val());
var sd = $.trim($('#sd').val());
if(id.length > 0 && sd.length > 0){
var url_string = new URL($('#form').attr('action'));
window.location.href = url_string.href.concat(((url_string.href.endsWith('/')) ? '' : '/'),id,'/',encodeURIComponent(sd));
}
});
});
If you want to pass the value through URL, Try the below link:
Send form input value to URL
Ok - someone must have done this before me.
I have a an Ajax form (Ajax form helper) that has a search box and some checkboxes to filter stuff. The search results are rendered beneath by way of a partial view. See below:
Here is the code:
Search.cshtml
#using (Ajax.BeginForm("SearchStuff", "FooController", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnFailure = "searchFailed",
LoadingElementId = "progress",
UpdateTargetId = "search-results",
}))
{
<div>
<div class="search-filter">
<span class="searchFilter">
<input type="checkbox" name="chkAll" checked />
All
<input type="checkbox" name="chkJournal" />
Journal
<input type="checkbox" name="chkBook" />
Book
<input type="checkbox" name="chkBookChapter" />
Book Chapter
<input type="checkbox" name="chkReport" />
Report
<input type="checkbox" name="chkWebsite" />
Website
<input type="checkbox" name="chkPersComm" />
Personal Comm
<input type="checkbox" name="chkConference" />
Conference
<input type="checkbox" name="chkMap" />
Map
<input type="checkbox" name="chkThesis" />
Thesis
</span>
</div>
<div class="searchbox">
<input type="search" name="q" autocomplete="off"/>
<input class="submit-button" type="submit" value="Search" />
</div>
</div>
}
<div id="search-results" class="search-results">
</div>
Problem with Pagination
I have now started to try and get a bit clever and I have included an Ajax Pager to have pagination returned in the first set of search results.
Problem is, I have to retain all values in the ajax search form when the user selects the next page to render, but when I debug back at the SearchStuff method in FooController - it doesn't know anything about the search parameters. Can anyone suggest what I should do to send the search parameters on?
<div class="pager">
#Html.Raw(
Ajax.Pager(new AjaxOptions
{
UpdateTargetId = "search-results",
OnBegin = "beginPaging",
OnSuccess = "successPaging",
OnFailure = "failurePaging"
},
Model.PageSize,
Model.PageNumber,
Model.TotalItemCount,
new { controller = "FooController", action = "SearchStuff"})
)
</div>
Use HttpMethod="Get" in new AjaxOptions. and change your controller with Request[] to get the search parameters.
Refer
Filter is getting lost in WebGrid + Paging + Sorting + Filtering in .NET 4.0
Hi make one html from which submitting without refresh by jquery. Problem is that I am beginner and I dont know how to add validation for html form. I need changes in script so first form will validate by jquery or ajax then it will submit by jquery witout page refresh.. have look in my code. Please provide me working solution in that first form validate by ajax jquery then submit by jquery without refresh.. Thanks in advance
JQUERY:
<script type="text/javascript">
$(document).ready(function(){
$("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var uno = $("#uno").val();
var name = $("#name").val();
var licence = $("#licence").val();
var email = $("#email").val();
var phone = $("#phone").val();
var dataString = 'uno=' + uno + '&name=' + name + '&licence=' + licence + '&email=' + email + '&phone=' + phone;
$.ajax({
type: "POST",
url: "addd.php",
data: dataString,
success: function(){
$('form#form').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
});
</script>
HTML FORM:
<form id="form" method="post" name="form" action="">
<fieldset id="opt">
<legend>Driver Information</legend>
<label for="choice">Name : </label>
<input type="text" id="name" name="name" value=""> <br />
<label for="choice">Licence No : </label>
<input type="text" id="licence" name="licence" value=""> <br />
<label for="choice">Email : </label>
<input type="text" id="email" name="email" value=""> <br />
<label for="choice">Phone : </label>
<input type="text" id="phone" name="phone" value=""> <br />
<input type="hidden" name="uno" id="uno" value="" />
<br />
</fieldset>
<div align="center">
<input id="button2" type="submit" value="Add Driver" />
<input id="button2" type="reset" />
</div>
</form>
I found multiple errors/mistakes on your HTML form too. some of them I want to mention..
for attribute of label have same value of the next input/select id, read:
http://www.w3schools.com/tags/att_label_for.asp
Dont assign name for name and id attribute, it's misleading.( good practice)
Don't write value ="", if you there is no initial value of any input box.
If u want to validate a hidden field then write some value for that on form intialization, otherwise it wud be always empty and your validation never works.
If u want to validate all input field together for emptyness then use :input selector ,read :
http://api.jquery.com/input-selector/
Don't forget to validate email address
If you want to post a form via ajax then there is no need to write method and action attribute in your form
Your reset button shoud have some value, otherwise its takes default value.
A very useful and handy article for newbie for jquery ajax validation
http://jorenrapini.com/blog/css/jquery-validation-contact-form-with-modal-slide-in-transition
OR you can use jquery validator plugin :
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
here is your neat and clean form
<form id="driverForm" name="driverForm">
<fieldset id="opt">
<legend>Driver Information</legend>
<label for="lname">Name : </label>
<input type="text" id="lname" name="lname" > <br />
<label for="licence">Licence No : </label>
<input type="text" id="licence" name="licence" ><br />
<label for="email">Email : </label>
<input type="text" id="email" name="email" ><br />
<label for="phone">Phone : </label>
<input type="text" id="phone" name="phone" > <br />
<input type="hidden" name="uno" id="uno" /><br />
</fieldset>
<div align="center">
<input type="submit" id="submitForm" name="submitForm" value="Add Driver" />
<input type="reset" value="clear" />
</div>
</form>
Hope this will be useful for you.
UPDATE
put it insdie submit() and before ajax like this
$("form").submit(function() {
if($('#lname').val() == '')
return false;
});
$.ajax({
NOTE: dont create dataString Manually there is inbuilt function in jQuery.
serialize
Please note that ,this is not matter that your form is submitting or not. most thing is it a valid form or not.
Happy to help :)