I'm trying to implement reCAPTCHA in my MVC site, but it doesn't Validate unless I submit it from a form, like this:
#using(Html.BeginForm("VerifyCaptcha", "Signup") )
{
#ReCaptcha.GetHtml(theme: "clean", publicKey: "6LcnfAITAAAAAAY--6GMhuWeemHF-rwdiYdWvO-9");
<input type="submit" id="btnVerify" value="Verify" />
}
[HttpPost]
public ActionResult Index(PolicyModel model)
{
var result = ReCaptcha.Validate(privateKey: "THE_KEY");
return View();
}
I don't want to use form submission because I don't want to return a new view. All my data is being pushed around with ajax in json form. What I'd like to do is:
$.ajax({
url: 'verifyCaptcha',
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
type: "POST",
async: false,
success: function (response) {
alert(response);
},
error: function(response) {
alert('There was a problem verifying your captcha. Please try again.');
}
});
return valid;
[HttpPost]
public ActionResult VerifyCaptcha()
{
var result = ReCaptcha.Validate(privateKey: "THE_KEY");
return Json(result);
}
The ajax call gets to the controller, but the Validation method completes immediately, almost as if it doesn't even get to making the request. I'm not sure why the validation always fails if the captcha isn't in a form - is it perhaps losing information like it's public key or something? Is there a workaround to this?
Edit: Added the ajax controller action method without model.
Just use serializeArray() or serialize() and change your ajax request to
$.ajax({
url: 'verifyCaptcha',
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
type: "POST",
async: false,
data: $('form').serializeArray(), // $('form').serialize(),
success: function (response) {
alert(response);
}
});
You haven't added the data part in your request. That seems to be the problem
You need to set the Ajax Request with all parameters for a form request. For example the content-type as application/x-www-form-urlencoded.
Look at this: application/x-www-form-urlencoded or multipart/form-data?
UPDATE:
...and yes ...you must do a POST request, and not a GET.
UPDATE:
$.ajax({
url: 'verifyCaptcha',
contentType: "application/x-www-form-urlencoded",
type: "POST",
success: function (response) {
alert(response);
},
error: function(response) {
alert('ERROR', response);
}
});
Related
I'm using web-forms to collect data from a form and then send the data to the code-behind to send to an API. Using a button I'm calling a JavaScript method which collates the data and then sends to my aspx.cs file to send to the API. The Html code for the button is
<button class="search btn" ID="btnSearch" onclick="searchApi(); return false;"><i class="fas fa-search"></i>Search</button>
This runs the searchAPI() function which works and creates a concatenated string called SearchData. The Javascript code looks like this
var searchString = JsonData;
var trimsearchString = searchString.replace(/,/g, '');
$.ajax({
type: "POST",
url: 'Default.aspx/GetApi',
data: searchString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (errordata) {
console.log(errordata);
alert(errordata);
}
});
The method GetAPI in my Default.aspx.cs file is never called. The method code is
[System.Web.Services.WebMethod]
public static void GetApi(string searchData)
{...
The success: function (data) returns success but the code behind method is never called, can someone please tell me what I am missing.
fix the ajax data, it seems that method with this parameter can' t be found
$.ajax({
type: "POST",
url: 'Default.aspx/GetApi',
data: { searchData: trimsearchString},
//or if it is still problem, you can even try
data: JSON.stringify( { searchData: trimsearchString}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (errordata) {
console.log(errordata);
alert(errordata);
}
});
and your webmethod should return something
[WebMethod]
public static string GetApi(string searchData)
{
return searchData
}
I'm building a program that searches documents in ASP.NET Core. I'm passing the search data from a text box to the controller through an Ajax request but the controller isn't receiving the string.
I've tried changing how the ajaxData field is defined, adding quotations around 'search' and even turning the whole thing into a string but I can't get it to pass to the controller.
This is the code for the request:
ajaxData = {search: $("#textSearchBox").val()}
console.log(ajaxData);
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: ajaxData,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
And this is the top of the Controller's GetDocuments function:
[Route("GetDocuments")]
public async Task<IActionResult> GetDocuments(string search)
{
No error messages anywhere. The Console shows an Object that contains 'search: "Test"' but when I hit the breakpoint in GetDocuments 'search' is null.
I think is more elegant way to use GET in this case then you should change your code to
var ajaxData = $("#textSearchBox").val();
url: "#Url.Action("GetDocuments", "DocumentSearchApi")"?search=ajaxData
and remove data: ajaxData
Because you want to get something from the search. Using the post is when you want to modify the data from API
you need use JSON.stringify() when sending data to a web server, the data has to be a string not a object
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: JSON.stringify(ajaxData),
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
I am trying to build an ASP.NET MVC web service in which I am trying to make a POST call in javascript using jQuery ajax as below.
$.ajax({
url: "/bug/CreateBug",
type: "POST",
data: rowData,
contentType: "application/json",
datatype: "json", //return type
success: function (data) {
console.log(data);
},
error: function (xhr) {
alert('error');
}
});
I keep getting the error TypeError: e is undefined. I tried adding a log statement just before this ajax call and things are working fine. Not sure what am I missing out on. My rowData looks something like below.
{
"Date": "2016-12-31",
"Id": "1234-csj4-sadf-random",
"Scenario": "abc",
"IsFixed": "No"
}
My C# code in the controller looks something like this
[HttpPost]
public JsonResult CreateBug(string jsonRequest)
{
var bugId = GetBugId(jsonRequest);
return this.Json(bugId, JsonRequestBehavior.AllowGet);
}
I tried to test the above POST call using Postman and I got jsonRequest as null. Could someone pls help me out here on how can I get the POST request to work?
Thanks in advance!
try it hope it works
$.ajax({
url: "/bug/CreateBug",
type: "POST",
data: JSON.stringify(rowdata),
contentType: "application/json",
datatype: "json", //return type
success: function (data) {
console.log(data);
},
error: function (xhr) {
alert('error');
}
});
------ on controller
do something like this or the best approach is to create model with all these property and MVC will bind it for you.
[HttpPost]
public JsonResult CreateBug(string Id, string Date, string IsFixed , string Scenario)
{
var bugId = GetBugId(jsonRequest);
return this.Json(bugId, JsonRequestBehavior.AllowGet);
}
I have tried to use AJAX call in an MVC5 project as many similar examples on the web, but every time there is an error i.e. antiforgerytoken, 500, etc. I am looking at a proper AJAX call method with Controller Action method that has all the necessary properties and sending model data from View to Controller Action. Here are the methods I used:
View:
#using (Html.BeginForm("Insert", "Account", FormMethod.Post, new { id = "frmRegister" }))
{
#Html.AntiForgeryToken()
//code omitted for brevity
}
<script>
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
$('form').submit(function (event) {
event.preventDefault();
//var formdata = JSON.stringify(#Model); //NOT WORKING???
var formdata = new FormData($('#frmRegister').get(0));
//var token = $('[name=__RequestVerificationToken]').val(); //I also tried to use this instead of "AddAntiForgeryToken" method but I encounter another error
$.ajax({
type: "POST",
url: "/Account/Insert",
data: AddAntiForgeryToken({ model: formdata }),
//data: { data: formdata, __RequestVerificationToken: token },
//contentType: "application/json",
processData: false,
contentType: false,
datatype: "json",
success: function (data) {
$('#result').html(data);
}
});
});
</script>
Controller: Code cannot hit to this Action method due to antiforgerytoken or similar problem.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult Insert(RegisterViewModel model)
{
try
{
//...
//code omitted for brevity
}
}
I just need a proper AJAX and Action methods that can be used for CRUD operations in MVC5. Any help would be appreciated.
UPDATE: Here is some points about which I need to be clarified:
1) We did not use "__RequestVerificationToken" and I am not sure if we send it to the Controller properly (it seems to be as cookie in the Request Headers of Firebug, but I am not sure if it is OK or not). Any idea?
2) Should I use var formdata = new FormData($('#frmRegister').get(0)); when I upload files?
3) Why do I have to avoid using processData and contentType in this scenario?
4) Is the Controller method and error part of the AJAX method are OK? Or is there any missing or extra part there?
If the model in your view is RegisterViewModel and you have generated the form controls correctly using the strongly typed HtmlHelper methods, then using either new FormData($('#frmRegister').get(0)) or $('#frmRegister').serialize() will correctly send the values of all form controls within the <form> tags, including the token, and it is not necessary to add the token again.
If your form does not include a file input, then the code should be
$('form').submit(function (event) {
event.preventDefault();
var formData = $('#frmRegister').serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")', // do not hard code your url's
data: formData,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
or more simply
$.post('#Url.Action("Insert", "Account")', $('#frmRegister').serialize(), function(data) {
$('#result').html(data);
});
If you are uploading files, then you need you need to use FormData and the code needs to be (refer also this answer and
$('form').submit(function (event) {
event.preventDefault();
var formData = new FormData($('#frmRegister').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")',
data: formData,
processData: false,
contentType: false,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
Note that you must set both processData and contentType to false when using jQuery with FormData.
If you getting a 500(Internal Server Error), it almost always means that your controller method is throwing an exception. In your case, I suspect this is because your method is returning a partial view (as suggested by the $('#result').html(data); line of code in you success callback) but you have specified that the return type should be json (your use of the datatype: "json", option). Note that it is not necessary to specify the dataType option (the .ajax() method will work it out if its not specified)
If that is not the cause of the 500(Internal Server Error), then you need to debug your code to determine what is causing the expection. You can use your browser developer tools to assist that process. Open the Network tab, run the function, (the name of the function will be highlighted), click on it, and then inspect the Response. It will include the details of the expection that was thrown.
contentType should be application/x-www-form-urlencoded
Try this code
<script>
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "/Account/Insert",
data: $(this).serialize(),
contentType:"application/x-www-form-urlencoded",
success: function (data) {
$('#result').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
</script>
I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});