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);
}
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'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);
}
});
I am having having problem with sending the an object and two parameter in an ajax call.
My Server side method:
public ActionResult AddUpdate(string model, bool IsEdit, string Type)
{
//Do something
}
Client side ajax call is:
I am fetching all form values provided by user and saving them into "MemberObj" and sending another 2 parameters ie IsEdit and Type. but at server side i am getting only the IsEdit and Type values model parameter is null. The date value in ajax call after stringify is like:
"{"model":{"id":"123","Name":"Jhon Doe","Relation":"Father","Dob":"15-3-2014","Address":"abc":" abc","City":"abc","MobileNumber":"1234567890"},"IsEdit":false,"Type":"FamilyMember"}"
var MemberObj={};
MemberObj.Name="aaa";
var requestJSONData={ "model": MemberObj, "IsEdit": IsEdit, "Type": str[0] }
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: '/Employee/AddUpdate',
data: JSON.stringify(requestJSONData)
success: function (msg) {
//Success
},
error: function (msg) {
}
});
Any help is most appericiate.
Thanks
in one of my projects i used the following line and it works like a charm:
data: "{'sid':'" + sid.toString() + "'}",
try adapting yours to this format, it should work.
I am using render partial concept in MVC. Its not showing the output in div. While debugging everything is OK (Showing Staus 200 OK) but its not going inside success block.Below is my jquery function.
function ShowNavigation() {
var jsonObj = {
'Display': 'Index',
taFormula: $('#taFormula').val()
};
$.ajax(
{
url: "/Home/Index",
type: "POST",
data: jsonObj,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
var message = data.Message;
$("#contentDiv").html(message).val();
}
});
}
My Controller code is:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var val = collection["taFormula"].ToString();
ViewBag.Output = GetValue(val);
return View();
}
Remove the datatype: "json" bit. You're receiving html back from the server, not json data, but because of that setting it's trying to parse it and failing. If you had an error callback function it would go into that.
Also, you don't need the .val() on $("#contentDiv").html(message).val();
Try adding an error handler to the ajax call and see if that gives you any more information:
error: function (xhr, status, error) {
alert(status + " : " + error);
}
Try this for your json object:
data: JSON.stringify(jsonObj),
You might need to include json.js for older browsers.