Currently I'm working on an integration with payment gateway which is using asp.
Below are the sample given.
Post Form Data
// Post Payment Data
<form method="post" name="ePayment" action="https://testing.com/ePayment.asp">
<input type="hidden" name="MerchantCode" value="AAA">
...
<input type="submit" value="Proceed with Payment" name="Submit">
</form>
Get Form Data
// Get Payment Response
<%
MerchantCode = Request.Form("MerchantCode")
...
Status = Request.Form("Status")
%>
IF Status = 1 THEN
Response.Write "Thank you for payment."
ELSE
Response.Write "Payment fail."
I have tried the following but the parameters seems not being posted and redirected.
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("MerchantCode", "AAA")
});
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);
May I know what is the best way to get it work in Blazor?
Thanks
Use this code:
var formContent = new FormUrlEncodedContent(new[]{
new KeyValuePair<string, string>("username", "myusername"),
new KeyValuePair<string, string>("password", "myPa$$word")
});
var response = await http.PostAsync("security/login", formContent);
works correctly!
Related
When I submit my form to my wp-admin/admin-ajax.php I get a 400 error using fetch.
I have tried removing content type.
Hard coding the Fetch URL
using FormData
let formData = new FormData(form);
Using URLSearchParams
using them both
const data = new URLSearchParams(new FormData(form));
I cant get it to work and am out of answers online so thought I'd ask here.
Can you see an error in my code?
<form >
<input type="text" name="fname">
<input type="text" name="email">
<input type="hidden" name="action" value="add_user_details_hook">
<button type="submit">Submit</button>
</form>
<script>
let form = document.forms[0];
const data = new URLSearchParams(new FormData(form));
form.addEventListener('submit', function(e){
e.preventDefault();
fetch('/wp-admin/admin-ajax.php', {
method: 'post',
body: data
})
ADMIN-AJAX.php
function ajax_add_user_details_func(){
var_dump('hey!');
}
add_action('wp_ajax_add_user_details_hook', 'ajax_add_user_details_func');
add_action('wp_ajax_nopriv_add_user_details_hook', 'ajax_add_user_details_func');
Edit I do believe it has something to do with empty FormData as even when I iterate over the object with forloop the fields are empty:
Example:
for (var [key, value] of formData.entries()) {
console.log(key, value);
}
Returns no values
This is the story:
I am making a commenting system, and when a user wants to add a comment they need to put data in a text area. I want to take that value typed by the user and make an #Ajax link which is to send that as a parameter to a controller.
I am using ASP.NET MVC5, and in my View() I have the following:
<textarea class="textArea" rows="3"></textarea>
<br />
#Ajax.ActionLink("Send",
"AddComment",
new { parametar = 0 , Contents = GetText() },
new AjaxOptions
{
UpdateTargetId = "beforeThis",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "GET"
},
new { #class = "postavi btn btn-primary" })
I tried inserting under this the following:
<script type="text/javascript">
function GetText() {
return "hello there!";
}
</script>
I have in error saying that:
the name GetText does not exists in the current Context
(this is in the parameters of the #Ajax.ActionLink)
It seems I cannot integrate javascript (which could fetch me this value and razor code) How do I work this out???
PS> I have searched around for this, and either the answers for much earlier versions of MVC or the answers did not worked when I tried the same.
Make sure that you import this namespace:
using System.Web.Mvc.Ajax
You might add an event handler to the ajax link to update a custom route value.
#Ajax.ActionLink("Click", "Send", new {id = "xxx"}, new AjaxOptions(){}, new { onclick = "addParameter(this)" })
function addParameter(e) {
e.href = e.href.replace("xxx", "HelloWord");
}
What you are doing now is that you want the razor to call your JavaScript code and this is impossible. This is because Views will be rendered to HTML by Razor before they are sent to the client and Razor doesn't know about the JavaScript code, it only knows C#. All JavaScript code runs on the browser.
I suggest you use the POST method to send your comments.
You can use this code to send them:
#using (Ajax.BeginForm("AddComment", new { parametar = 0 }, new AjaxOptions()
{
UpdateTargetId = "beforeThis",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "POST",
Url = Url.Action("AddComment")
}))
{
#Html.TextArea("Contents")
<input type="submit" value="Send" class="postavi btn btn-primary" />
}
I am using a to handle a login. In the case of incorrect credentials, I use Ajax to print an error message on the same web page but in the case of success I would like to forward to another web page. What is happening is that even in the case of success it is printing results on the same page. I know that this has partially to do with the fact that you can't send a redirect to Ajax. However, still a newbie to know how to go about it. Any suggestions?
Here is my gsp section having to do with this form:
<g:formRemote name="subForm" url="[controller:'admin', action:'authenticate']" update = "error_message">
<br><br><label>User Name (email): </label><g:textField name = "username" /><br><br>
<label>Password: </label><g:field name = "password" type = "password" /><br><br><br><br>
<div id = "error_message" style = "text-align: center"> </div>
<div style = "text-align: center">(for TWC employees only)</div>
<g:submitButton id = "submit_button" name="Submit"/>
</g:formRemote>
and here is the controller method 'authenticate':
def authenticate = {
try {
MongoClient mongoClient = new MongoClient("localhost", 27017)
DB db = mongoClient.getDB("admin");
def userName = params.username
def passWord = params.password
boolean auth = db.authenticate(userName, passWord.toCharArray())
if (auth)
redirect (action: loggedin)
else {
render "Login or Password incorrect!"
}
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (MongoException e) {
e.printStackTrace();
}
}
def displayerror = {
render "Login or Password incorrect!"
}
def loggedin = {}
As it is, I can't get the gsp corresponding to the 'loggedin' method to display. Any ideas?
Minor adjustments needed to previous poster's most helpful suggestions. This is the code that will actually solve the issue.
<g:formRemote name="subForm" url="[controller:'admin', action:'authenticate']" onSuccess="doResult(data)">
<br><br><label>User Name (email): </label><g:textField name = "username" /><br><br>
<label>Password: </label><g:field name = "password" type = "password" /><br><br><br><br>
<div id = "error_message" style = "text-align: center"> </div>
<div style = "text-align: center">(for TWC employees only)</div>
<g:submitButton id = "submit_button" name="Submit"/>
</g:formRemote>
javascript below:
function doResult(data) {
if (data.success == true) {
window.location.href = data.url;
} else {
$("#error_message").html(data.message);
}
}
controller code section below
//success case
render(contentType: 'text/json') {
[success: true, url: createLink(controller: 'whateverController', action: 'whateverAction')]
}
}
else {
render(contentType: 'text/json') {
["success": false, "message": 'Login or Password is incorrect.']
}
importing JSON converter in last set of code isn't needed either.
You are correct that you can't send a redirect using ajax. What you can do, however, is send something back in your ajax response that you can read and redirect if needed.
Instead of just updating the div with the response from your ajax call you will need to send back some JSON data and use the onSuccess attribute of the formRemote tag to pass the results to a function which can act accordingly.
I would suggest you start by reading over the documentation for the formRemote tag, then consider something like the following:
<g:formRemote name="subForm" url="[controller:'admin', action:'authenticate']" onSuccess="doResult(e)">
<br><br><label>User Name (email): </label><g:textField name="username" /><br><br>
<label>Password: </label><g:field name="password" type="password" /><br><br><br><br>
<div id="error_message" style="text-align: center"> </div>
<div style="text-align: center">(for TWC employees only)</div>
<g:submitButton id="submit_button" name="Submit"/>
</g:formRemote>
Notice in the above that onSuccess is now set on the formRemote tag and update is removed. The response from the form submission will now be passed to the javascript function doResult.
This is what the function might look like:
<script>
function doResult(response) {
var result = eval('(' + response.responseText + ')');
if (result.success == true) {
window.location.href = result.url;
} else {
$("#error_message").html(result.message);
}
}
</script>
The only thing left is to change how your controller responds to the form submission. First you will need to add the import for import grails.converters.JSON into your controller. Then change the way it responds. It might look like this:
import import grails.converters.JSON
...
// in the case of an error
render [success: false, message: "Login or Password incorrect!"] as JSON
return
...
// in the case of success
render [success: true, url: createLink(controller: 'whateverController', action: 'whateverAction')] as JSON
return
It may seem like a lot to take in all at once, but once you do it a few times it becomes quite simple. One thing that helps a lot is to read the Grails documentation. It's long, but it's very well written and will help a lot.
I don`t speak english well? but i have problem in Django.
I have models:
class Model1(models.Model):
model2 = models.ManyToManyField(Model2)
#...
class Model2(models.Model):
model3 = models.ForeignKey(Model3)
#...
class Model3(models.Model):
custom = models.CharField()
have view
def simple(request, simple_id):
if request.method == 'POST':
if request.is_ajax():
if 'delete' in request.POST:
id3 = request.POST.get('delete', '')
Model1.objects.get(id = simple_id).model2.filter(model3__id = id3).delete()
That is, when submitting a form with name = "delete" Ajax have removed all the objects belonging to Model2 with the same value of the field "model3"
Here's a piece of template:
<form action="" method="post" id="simple">{% csrf_token %}
<input type="submit" name="delete" id="simple_delete" value="">
</form>
the value passed from js:
$('.deletebutton').click(function(){
id = $(this).attr('data-id');
$('#simple_delete').attr('value', id);
$('#simple').ajaxForm();
$('#simple_delete').click();
});
Well, respectively plugin jquery.form.js also connected
The problem is this - if submission without ajax all is normal, it works ... and if with Ajax is an error such as incorrect int value ... How to make it work via Ajax?
try this
$('.deletebutton').click(function(){
id = $(this).attr('data-id');
$.ajax(function(){
type:"POST",
url :"/your_url/",
data:{
'id'=id,
}
}).done(function(result){
alert('your json object result render by view :'+result)
})
i think it work,
and i didnt get wat you are doing in i.e $('#simple_delete').click();
can you please describe about that
in view
obj = Model1.objects.get(id = simple_id)
model2.objects.filter(model3__id = id3).delete()
i just split single line query into two lines and if not working
use .select_related()
I have a form in DoComment.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DT.KazBilet.Objects.PublicationComment>" %>
<div class="wrap">
<h4>Comment</h4>
<%using (Ajax.BeginForm("DoComment", "Publication", new {id = Model.Publication.OID, parentId = Model.OID},new AjaxOptions()))
{%>
<%=Html.TextAreaFor(x=>x.Text) %>
<%-- <textarea style="width: 100%; height: 152px;"></textarea>--%>
<input type="submit" value="Publish" class="btn ok_btn" />
<%}%>
</div>
This is my controller's action:
public JsonResult DoComment(PublicationComment model, int id, int parentId)
{
PublicationRepository.SaveComment(User.Identity.Name,id, parentId, model.Text);
return Json(new {
Message = "You comment on moderation"
});
}
I want that user clicks on Publish button then show popup window where will be written text from Message.
Can you help me(some code)?
Thanks.
You could subscribe to the OnSuccess javascript event in the AJAX options and then show the JSON result you have retrieved the way you like (new window, div, ...):
<% using (Ajax.BeginForm(
"DoComment",
"Publication",
new { id = Model.Publication.OID, parentId = Model.OID },
new AjaxOptions { OnSuccess = "onSuccess" })
) %>
and then you would define the onSuccess javascript function. Depending on whether you use jQuery or MicrosoftAjax the implementation of this function might slightly vary and more specifically the way to retrieve the JSON result.
For example if you are using MicrosoftAjax (obsolete now):
var onSuccess = function(e) {
var json = e.get_response().get_object();
alert(json.Message);
};
and if you are jQuery:
var onSuccess = function(json) {
alert(json.Message);
};