I am using partial views and ajax based functionality to POST to my controller. I want to know how I can leverage the validation functionality I normally get with the MVC Razor forms and using a full page post back with a async based framework.
Pseudo Code
function buttonpress()
{
if(Validate())
.... Call server functionality with AJAX and handle result
else
.... Show standard validation messages as normal. Do not contact server
}
function Validate()
{
... Check the validation like it would with full post back
... Should also limit to a group too
}
I don't want to rewrite the all the free validation I get from the framework if I don't have to.
Related
If I have a form on a page like so - (note the model property):
<form asp-action="ProcessQuote" id="form-calc-total">
<p id="calc-item">#Model.TheCounter.Value</p>
<button id="btn-add">+</button>
<button id="btnContinue" onclick="document.getElementById('form-calc-total').submit();">CONTINUE</button>
</form>
Let's say I have an event listener on the form so when btn-add is clicked, it triggers the following JS function which adds 1 to the counter.
function calculatorClick() {
let cou = document.querySelector('#calc-item');
cou.innerHTML = Number(cnt) + 1;
}
So now when the form submits, it hits the controller and within that I can store the number (#Model.TheCounter.Value) in a session variable if I want:
HttpContext.Session.SetString(SESSION_GUID, model.TheCounter);
That means if I revisit the page I can pull out the session variable and populate that field again.
But that's only stored on form submission - How can I get a session variable to store after each button click so it'd remember the counter without someone having to submit the form first?
I vaguely remember in PHP that there were SESSION variables that could be added to directly on the page with JS (I think) - but how can I do this within an ASP.NET CORE framework / MVC pattern?
Is this something AJAX would be used for?
But that's only stored on form submission - How can I get a session
variable to store after each button click so it'd remember the counter
without someone having to submit the form first?
The session value was stored on the server side, if you want to update and get the session value, you could create an Action method, then use JQuery Ajax to call this method and then update the session and get the latest value.
More detail information about using JQuery Ajax with Asp.net Core, see the following links:
jQuery AJAX and JSON Example in ASP.Net Core MVC
How to use jQuery AJAX method to call an Action method in ASP.NET Core
Besides, on the client side, you could also use web storage API to store the data, check the following tutorials:
Using the Web Storage API
HTML Web Storage API
I am new to Brain Tree. I want to accept payments on my web site using Brain Tree. On client side I use javascript and on the server side C#. I use their drop in form in order to collect card information. All the examples I saw on Brain Tree developer side instructs me to do a form submission in order to receive payment_method_nonce on the server. In my web site I handle interactions through callbacks in order to avoid full page refresh. They let me define a callback method in the setup for receiving payment_method_nonce, but is there a way to initiate call to brain tree server through their client side javascript api in order to request payment_method_nonce by avoiding form postback?
I work as a developer for Braintree. There are global configurations that can be used with the Drop-in integration to do this.
The onPaymentMethodReceived callback halts the form submission after the payment method is tokenized. You can use it to capture the payment method nonce and insert your own code to do what you want in place of the form submission.
Add the callback to your global setup like this:
braintree.setup(clientTokenFromServer, "dropin", {
container: "checkout",
onPaymentMethodReceived: function (obj) {
// Insert your code here to capture and use the payment method nonce
// console.log(obj.nonce);
}
});
See more details about the onPaymentMethodReceived callback and the object it returns here. Hope that helps!
I have a Java application (servlet, written by someone else) that does some processing. I have a PHP application (web site HTML that uses PHP in places) on top that posts data to the Java application:
<form method="post" action="http://site/java" onsubmit="return validate(this)">
I have the JavaScript validating, as well onsubmit.
This works fine, but when I try and validate with PHP (in case JS is disabled), I run into problems.
I'm not sure how to do this. I've tried a few things but none has been really what I want. I want to be able to mimic the JS behavior but with PHP.
It would be cool if I could do something like this:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
//do post to servlet
}
I've tried other things like this:
if (isset($_POST['field'])) {
//validate form with function
}
Part of the problem is that the Java application also does some validation and returns some parameters I can get. I might use something like this to check these:
if ($_GET['error'] == 'invalidEmail') {
$error = 'Please enter a valid email address.';
}
How would I do this? Can I use Location response header or does this not send POST data? If I set action="" and post back to page, I can get the PHP to validate but obviously the whole point is to post to the Java application.
You can use REST to post to your java application from php. More specifically the cURL library.
--edit--
(Trying to rephrase my question to be less confusing..)
My understanding is that you should validate forms both client and server side in case Javascript is not working.
How do advanced developers accomplish this in a seamless interface (if one had to describe in a general manner)?
Currently I have Javascript validating my input fields on the fly with 'onkeyup ()', highlighting invalid fields.
If I run the same validations with PHP after the user submits, then I have to redirect to the form if there were any errors, refreshing the page.
I thought this method was lacking sophistication.
What would be the best method?
Thanks in advance.
--- original question below ---
So I created a form with client side javascript to validate the input as the user types. It highlights the boxes w red borders if the data is invalid (using javascript to alter the css). I would like to re-validate the same data with php server side in case of any problems with javascript client side.
I am trying to figure out what is the proper (or best) way to accomplish this.
Currently the form action is setup to go to "register_post.php" after user hits submit.
--
So do I just validate the form data in PHP in "register_post.php", and redirect back to the form page if something is invalid, or is there a more sophisticated way to do this?
One annoying result of this is the page refreshing when the page is redirected.
Is there a more sophisticated way to do this?
--
Another related question is - should I prep my code for javascript not working at all? ..since currently, I use javascript to highlight the fields if the data is invalid. The user will have no indication of which fields are invalid without js.
please bear with me as I am a beginner.
You are trying to valid the post data with PHP and without refresh the page, I don't know if I get your point right. If you want to valid the data with PHP and without refreshing page, you could use AJAX. You can use javascript to post data to a PHP script and deal PHP return data.
An example of jquery ajax method :
<script>
var validDataArr = ''; //data need to be valided
$.ajax({
type:"post",url:"http://"+top.location.hostname+"/valid.php",
data:validDataArr,
success:function(context){alert(context);}
});
</script>
While submitting the form , call a javascript function to validate the fields and throw an error if it not suits.
you can call a js function as below
input type="submit" name="Submit" id="button2" value="Submit" onClick="javascript:verify()"/>
Try this , this will help you to understand the basic validation
http://jsfiddle.net/NWWL4/15/
I want a login page in which if any user types invalid password or username after clicking submit button, then the user will be displayed an error message on the same page.
What should I have to make this requirement enable? Is this possible with ajax or javascript?
Yes, this is possible with Ajax. It's easiest, frankly, if you use a library like Prototype, jQuery, Closure, etc., because they smooth out browser differences and such for you, and have a lot of built-in functionality.
For example, here's a fairly succinct way you can submit a form and look at the response using Ajax with Prototype:
$('formid').request({
onSuccess: function(response) {
// Request succeeded, check result for whether login was valid
}
});
(That assumes the form has the id "formid".)
Here's a more complete example, which also shows how you hook into the submission process. You might trigger that code by hooking the submit event on the form and sending the Ajax request instead:
$('formid').observe('submit', function(event) {
// Prevent the standard form submission
event.stop();
// Do it via Ajax instead, including an additional flag telling
// the server that this is an Ajax call
this.request({
parameters: {viaAjax: true},
onSuccess: function(response) {
// Request succeeded, check result for whether login was valid
if (response.responseJSON &&
response.responseJSON.loginOkay) {
// Login worked!
}
}
});
});
The above does these things:
Hooks up a Javascript handler for when the user submits the form
Handles that event by cancelling the usual form submission and sending an Ajax call instead
Along with the form data, we also include a viaAjax flag telling the server that we're sending the form via Ajax
The server should expect the form to arrive either with or without the viaAjax flag. If the flag is there, it means the browser supports Javascript and the form was submitted that way, and so it should just return a flag telling us whether the login was okay (in the above I've assumed it will return JSON-formatted data {"loginOkay": true}, which means it should set the content type to application/json). If the flag isn't there, Javascript is disabled on the browser and the server should handle the form submission in the normal way, returning a full HTML page. (This business of handling it regardless of whether Javascript is enabled is called "progressive enhancement" or "graceful degradation".)