Dears,
I do read a barcode and save the user in the database by posting back once I read the code, while in the OnPostAsync I validate on the user and I want to show a popup window if the user renewal date is expired? so how can I do this?
You can use ajax to call OnPostAsync and then show a popup in ajax success.Here is a demo:
cshtml(you can put the data you want to pass into data of ajax):
#Html.AntiForgeryToken()
<button onclick="postdata()">submit</button>
#section Scripts
{
<script>
function postdata() {
$.ajax({
type: "POST",
url: '',
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: { id: 1 }
}).done(function (result) {
if (result.message != "") {
alert("message:"+result.message);
}
});
}
</script>
}
cshtml.cs:
public async Task<IActionResult> OnPostAsync(int id)
{
//you can check if the user renewal date is expired here
if (id==1)
{
return new JsonResult(new{ message = "user renewal date is expired" });
}
else {
return new JsonResult(new { message = "" });
}
}
result:
Related
I am trying to follow the guide here ( https://stripe.com/docs/stripe-js/elements/payment-request-button ) to setup Apple Pay for the web and Stripe. The initial steps such as verification of domain and all the pre-setup is done but I am having an issue following the steps for the payment.
The Apple Pay Button is showing up in my Safari browser. When the button is clicked, I fire an event called Paymentmethode() i am facing this error while checking live.Either you do not have a card saved to your Wallet or the current domain (pwafe.devco.pk) is not registered for Apple Pay. Visit https://dashboard.stripe.com/account/apple_pay to register this domain.
main.js:25. and button is hide I get lost after step 3 and not sure what to do. I am posting to my backend and on the backend, creating a payment intent and returning the client_secret
paymentMethod() {
// STEP 1 FROM GUIDE
var stripe = Stripe("pk_test_YxSI6F4QeV0XCofSgabilbTu00ChOmJWJ0", {
apiVersion: "2020-08-27",
stripeAccount: "CONNECTED_STRIPE_ACCOUNT_ID",
});
// STEP 2 FROM GUIDE
var paymentRequest = stripe.paymentRequest({
country: "US",
currency: "usd",
total: {
label: "Demo total",
amount: 1099,
},
requestPayerName: true,
requestPayerEmail: true,
});
// STEP 3 FROM GUIDE
var elements = stripe.elements();
var prButton = elements.create("paymentRequestButton", {
paymentRequest: paymentRequest,
});
// console.log("before api call", paymentRequest);
paymentRequest.canMakePayment().then(function (result) {
// console.log("after api called" + result);
if (result) {
prButton.mount("#payment-request-button");
} else {
//prButton.mount('#payment-request-button');
document.getElementById("payment-request-button").style.display =
"none";
}
});
// STEP 4 FROM GUIDE -- THIS RETURNS A CLIENT SECRET
let clientSecret;
axios
.post("https://pwa.devco.pk/api/Create_PaymentIntent", {})
.then((resp) => {
// Assign this previously defined variable
clientSecret = resp.client_secret;
});
paymentRequest.on("paymentmethod", function (ev) {
// Confirm the PaymentIntent without handling potential next actions (yet).
stripe
.confirmCardPayment(
clientSecret,
{
payment_method: ev.paymentMethod.id,
},
{
handleActions: false,
}
)
.then(function (confirmResult) {
if (confirmResult.error) {
// Report to the browser that the payment failed, prompting it to
// re-show the payment interface, or show an error message and close
// the payment interface.
ev.complete("fail");
} else {
// Report to the browser that the confirmation was successful, prompting
// it to close the browser payment method collection interface.
ev.complete("success");
// Check if the PaymentIntent requires any actions and if so let Stripe.js
// handle the flow. If using an API version older than "2019-02-11" instead
// instead check for: `paymentIntent.status === "requires_source_action"`.
if (confirmResult.paymentIntent.status === "requires_action") {
// Let Stripe.js handle the rest of the payment flow.
stripe.confirmCardPayment(clientSecret).then(function (result) {
if (result.error) {
let data = {
msg: "An error occurred. Please try again.",
};
this.handleShowFlashMsg(data);
// The payment failed -- ask your customer for a new payment method.
} else {
this.handleShowOrderConfirmModal();
// The payment has succeeded.
}
});
} else {
// The payment has succeeded.
}
}
});
});
var paymentRequest = stripe.paymentRequest({
country: "US",
currency: "usd",
total: {
label: "Demo total",
amount: 1099,
},
requestShipping: true,
// `shippingOptions` is optional at this point:
shippingOptions: [
// The first shipping option in this list appears as the default
// option in the browser payment interface.
{
id: "free-shipping",
label: "Free shipping",
detail: "Arrives in 5 to 7 days",
amount: 0,
},
],
});
paymentRequest.on("shippingaddresschange", function (ev) {
if (ev.shippingAddress.country !== "US") {
ev.updateWith({
status: "invalid_shipping_address",
});
} else {
// Perform server-side request to fetch shipping options
fetch("/calculateShipping", {
data: JSON.stringify({
shippingAddress: ev.shippingAddress,
}),
})
.then(function (response) {
return response.json();
})
.then(function (result) {
ev.updateWith({
status: "success",
shippingOptions: result.supportedShippingOptions,
});
});
}
});
var stripe = Stripe("pk_test_YxSI6F4QeV0XCofSgabilbTu00ChOmJWJ0", {
apiVersion: "2020-08-27",
stripeAccount: "CONNECTED_STRIPE_ACCOUNT_ID",
});
},
You should verify domain registration and add card into wallet.tha
hi I'm trying to send a string from controller to ajax in ajax call response. but my ajax doesn't get the string in response , and i see the raw content in browser.Actually ,this is a simple example of my main project.
I'm using ASP.NET Core for server side programming.
here's my codes:
server side :
public IActionResult addlink(string link)
{
return Redirect("/home/showlink?key=" + link);
}
public IActionResult showlink(string key)
{
return Content("this is content from 2nd controller");
}
client side :
<form>
<input type="text" id="mainlink"/>
<button id="btn">submit</button>
</form>
<script>
$("#btn").click(function () {
$.ajax({
type: "POST",
url: "/home/addlink",
data: {
"link": $("#mainlink").val()
},
success: function (response) {
alert(response);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
}
)
})
</script>
what i see in browser :
in main project i want to send a text from controller to ajax call succes ,just this, please help me :)
Try to return Ok ActionResult:
public IActionResult addlink(string link)
{
return Ok("/home/showlink?key=" + link);
}
If you add ajax to the submit button in the form, you should prevent the default behavior of form submission.
<script>
$("#btn").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/home/addlink",
data: {
"link": $("#mainlink").val()
},
success: function (response) {
alert(response);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
}
)
})
</script>
I am receiving a CORS error from my browser while trying to implement a simple login authentication (email/password) with firebase.
I checked the security rules and it is set to
{
"rules": {
".read": true,
".write": true
}
}
Here's a summary of my code from the example.
<script src="https://cdn.firebase.com/js/client/1.0.15/firebase.js"></script>
<script type='text/javascript' src='https://cdn.firebase.com/js/simple-login/1.5.0/firebase-simple-login.js'> </script>
var myRootRef = new Firebase('https://vivid-fire-myserver.firebaseio.com/');
var authClient = new FirebaseSimpleLogin(myRootRef, function(error, user) {
if (error) {
alert(error);
return;
}
if (user) {
alert('user already logged in');
} else {
alert('user logged out');
}
});
$("#registerButton").on("click", function() {
var email = $("#email").val();
var password = $("#password").val();
authClient.createUser(email, password, function(error, user) {
if (!error) {
alert('registered successfully');
} else {
alert(error);
}
});
});
It appears that the problem is a result of submitting my form, which causes the page to reload. As confirmed with Rob, "the reload is taking place before the HTTP OPTIONS request to the server checking the CORS configuration is able to complete.
A work around is to prevent the form from reloading upon submission. I did this by returning false in my html form and my jquery scripts.
<form class="m-t" role="form" onSubmit="return goLogin()">
..........
function goLogin() {
$("#loginButton").click(function() {
......
)};
return false;
}
I use jquery ajax to call (get) an action which renders a partialview for creating(inputting) a new product. The content of this partialview is inserted into a vid tag in a full page which has a base _layout. The ajax code below:
$("#Create").on('click', function (e) {
//debugger;
e.preventDefault();
$.ajax({
type: "GET",
data: { returnUrl: String(window.location) }, <-- passing in the Url
url: "/CreateGroup/CreateGroup",
dataType: 'html',
success: function (data) {
$("#group-list").html(data);
},
});
})
.....
<div id="group-list">
#Html.Partial("PagedGroupList")
</div>
The action:
// GET: /Create/
[Authorize]
public PartialViewResult CreateGroup(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
CreateGroupModel cgm = new CreateGroupModel();
cgm.ReturnUrl = returnUrl;
cgm.group = new Static_Group();
return PartialView("CreateGroup", cgm);
}
Now if I login first before clicking CREATE button, eveerything is fine as expected. The problem is when CREATE button is clicked without login first. Due to [Authorize], the login page will come first and after login, it is expected to redirect back to my CREATE partialview inside the full page together. The problem is that the login page redirects back to a NAKED create partialview without any of its parent view's elements. If the CREATE page is NOT a partialview, login page redirects back to the full page perfectly.
I use MVC4 defafult login. I tried to make the login page into a ajax form submit and use OnSuccess to call document.location in both the login page and the create partialview, but I found it is an issue of returnUrl of the partialview. I also tried Request.UrlReferrer.AbsoluteUri, but it gives the same URL which is "/CreateGroup/CreateGroup?returnUrl=http%3A%2F%2Fwww.dev.com%3A22531%2F" or in full: http://www.dev.com:22531/CreateGroup/CreateGroup?returnUrl=http://www.dev.com:22531/. If you put the Url into a browser, it also displays the pure partialview.
I believe I must have missed something obvious coz this should be a common scenario but I could not find any threads from googling. Is there a URL which displays a partialview inside its parent view together? if not, then possible to redirect back to a previous view from a partialview?
Looks there is no URL for a partialview with its host page. The solution I can think of at the moment is get login redirect to the host page and pass in the partialview name in Model or viewbag or session temp to render the whole page again with the right partialview in it.
Here is how I work around this issue. Don't feel very comfortable with it. If anyone has a better solution, please help.
I added two string vars in LoginModel:
public string RetUrl { get; set; }
public string UrlReferrer { get; set; }
In get Login action:
public PartialViewResult Login(string returnUrl)
{
ViewBag.ReturnUrl = Request.UrlReferrer.AbsolutePath;
LoginModel lgm = new LoginModel();
lgm.UrlReferrer = Request.UrlReferrer.AbsoluteUri;
lgm.RetUrl = returnUrl;
return PartialView(lgm);
}
In post Login action:
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
model.IsLoggedIn = true;
if (string.IsNullOrEmpty(model.RetUrl))
{
model.RetUrl = Url.Action("Index", "Home");
}
}
else
{
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
return PartialView("Login", model);
}
in Login.cshtml: put two hidden fields to retain Model preset value:
#Html.HiddenFor(m => m.RetUrl)
#Html.HiddenFor(m => m.UrlReferrer)
In ajax OnSuccess event handler, append a CallPartial querystring in the end of returnUrl and redirect to this returnUrl:
<script type="text/javascript">
function logInComplete() {
//debugger;
if ('#Model.IsLoggedIn' == 'True' && '#Model.UrlReferrer' != '') {
//debugger;
var returnUrl = '#Model.UrlReferrer';
if ('#Model.RetUrl' != '#Model.UrlReferrer') {
if (returnUrl.indexOf('?') == -1) {
returnUrl = returnUrl + "?CallPartial=True";
}
else {
returnUrl = returnUrl + "&CallPartial=True";
}
}
document.location = returnUrl;
}
}
Now back to the CREATE partialview host page:
$('.ifCallPartial').each(function () {
//debugger;
if ('#Request["CallPartial"]' == "True") {
$(document).ready(function () {
CallCreate();
});
}
});
function CallCreate() {
//debugger;
//e.preventDefault();
var returl = String(window.location);
var n = returl.indexOf("?CallPartial");
if (n >= 1) {
returl = returl.substring(0, n);
}
else {
n = returl.indexOf("CallPartial");
if (n >= 1) {
returl = returl.substring(0, n);
}
}
$.ajax({
type: "GET",
data: { returnUrl: returl },
url: "/CreateGroup/CreateGroup",
dataType: 'html',
success: function (data) {
$("#group-list").html(data);
},
error: function (xhr, status, error) {
alert(error);
}
});
}
I'm using the Javascript SDK to allow the user to login to facebook, retrieve their friends profile pictures, and then finally post a message on the logged in users wall. Problem is I keep getting an error, "Error while loading page from Pencils of Promise," when the user has to authorize the application.
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: '154058871279888', status: true, cookie: true,
xfbml: true});
console.log(FB.getLoginStatus());
$('div.voice-btn:eq(0)').click(function() {
FB.login(function(response) {
if(response.session) {
FB.api('/me', function(data) {
console.log(data);
});
donateVoiceSlider();
}
});
});
$('#voice-step-2-btn').click(function() {
var body = 'Test Facebook post';
FB.api('/me/feed', 'post', { body: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});
});
// Donate Voice Content Slider
function donateVoiceSlider() {
var $ul = $('#donatevoice');
var cur_left = parseInt($ul.css('left'));
var li_width = 980;
$ul.animate( {'left': cur_left-li_width+'px'} );
}
</script>
Please help!
My friend who had created the application did NOT set the site URL. After doing that, everything ran smoothly.