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
}
});
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 trying to make a GET call in jQuery passing a parameter here is what I'm doing
function getChirurghi() {
var id = "1";
$.ajax({
type: "GET",
url: "/api/ControllerName/GetDataHere",
contentType: "application/json; charset=utf-8",
data: id,
dataType: "json",
success: function (data) {
console.log(data);
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
}
});
}
On server side the controller is called but the data I'm getting is always null...
[HttpGet]
public IEnumerable<TypeOfObject> GetDataHere([FromBody]string id)
{}
Any idea how's that happening?
You need to give the value a key so that the ModelBinder can recognise and work with it:
data: { id: id },
You also need to remove the [FromBody] attribute in the action signature, as GET data is sent in the URL (either as part of the querystring, or in a routing structure).
Lastly, the options object of $.ajax() has no failure property so that can be removed as it's redundant.
I upvoted #RoryMcrossan, but there is another solution.
you could just add it to the end of the url.
function getChirurghi() {
var id = "1";
$.ajax({
type: "GET",
url: "/api/ControllerName/GetDataHere/" + id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
}
});
I want to pass a lot of parameters from my ajax function to my controller. Initially, I thought I would just do this using a query string but that wasn't giving me the result I wanted, although it worked it was creating an unattractive URL the more data I added.
I thought the better approach would be to take all this data I need to pass, store it as an object and pass that payload into the controller from an ajax function.
The ajax function is triggered from the .event() attribute of the KendoGrid.
Kendo Grid
#(Html.Kendo().Grid<MyProject.Models.Car>()
.Name("requirement-grid")
.Columns(columns =>
{
columns.Bound(c => c.Name);
columns.Command(command => command
.Custom("Test").Click("payload"));
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetCars", "cars"))))
As you can see from the above code, there is a custom command that I've used which triggers a function when you click on it. The function is payload and the code is as follows:
payload
function payload(e) {
e.preventDefault();
//Get row data
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Create Object
var obj = {
Name: dataItem.Name,
BHP: dataItem.BHP,
YearOfBuild: dataItem.YearOfBuild
}
//Post via Ajax
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: JSON.stringify({
array: obj
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("Success");
},
error: function (ob, errStr) {
console.log(ob.responseText);
}
});
}
I access the data of the row that was clicked on and pass it down via the events parameter, from there I create an object and add the data to it. I then create an ajax call and try to pass it to the controllers.
The controller expects the parameter, the code is as follows but shortened for brevity.
Controller
public ActionResult Create(object[] obj)
{
return View(obj);
}
If I use "POST" in my ajax function I get an error regarding a anti-forgery token which is missing. If I use "GET" the obj parameter is always null.
The required anti-forgery cookie "__RequestVerificationToken" is not present.
Is there a better way to be doing this or is my approach incorrect?
So this should be a relatively simple change to your code. I am assuming you have an anti-forgery token loaded onto the page and the action you are posting to is protected by this. You have two solutions here:
1) Remove the requirement for the token if it isn't needed from the action in your controller
2) Provide the token as part of the data package you are sending back to the server by changing your code from
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: JSON.stringify({
array: obj
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("Success");
},
error: function (ob, errStr) {
console.log(ob.responseText);
}
});
to:
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: {
array: JSON.stringify(obj),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
},
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log("Success");
},
error: function(ob, errStr) {
console.log(ob.responseText);
}
});
Notice I have just added a reference to the anti-forgery token as part of the data package for you and this should be read by the controller and allow the command to complete successfully for you if you have the token on the page. if not then just add the #Html.AntiForgeryToken() to the view and you should be fine.
In this SO post I learned how to get a return value from an AJAX call:
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
This function calls its web service wich does return true. The problem is that inside the following callUpdateGrid, the logging shows that that web service method is not getting called from the $.ajax call:
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
Anyone know what is wrong?
It is always a good idea to include an error handler function as one of the options passed to $.ajax. For example, add this code after your success functions:
,
error: function(jqXHR, textStatus, errThrown) {
console.log("AJAX call failed");
console.log(errThrown);
}
That will log at least a bit of information if the $.ajax call doesn't succeed.
EDIT
According to your comment, this logs
SyntaxError: Invalid character
And in fact, I now see that you are giving a plain JavaScript object as the data option passed to $.ajax, but indicating that it is a JSON object in the dataType field. You need to actually convert the input object into JSON yourself, like so:
data: JSON.stringify(input),
dataType: 'json',
Alternatively, you could simply format input as a JSON object in first place, like so:
var input = { "requestGUID": "<%=guid %>" };
The quotes around the field name requestGUID are sufficient, in this case, to give you a JSON object.
Here is my script:
$.ajax({
type: "Get",
url: "Sample.js",
datatype: 'json',
data: JSON.stringify({ key:key }),
success: function (data) {
var sample = data.name;
$("#html").html(sample);
},
error: function () {
alert("Error");
}
});
This is my Sample.js file:
{ "name": "user" }
When I run this code I get a blank screen. This is my script using getJSON():
$.getJSON("Sample.js", function (data) {
var sample = data.name;
$("#html").html(sample);
})
This produces "user" perfectly. What is the problem with $.ajax code?
In the getJSON version your don't send any data. Could this be the reason why that works? To me it looks like this could be sth. on the server side that delivers an empty JSON object when you pass the key parameter.
As the jQuery documentation states:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Try modifying the dataType param.
change your datatype to dataType. Its case sensitive. Refer http://api.jquery.com/jQuery.getJSON/
Remove JSON.Stringify and change Get to GET
$.ajax(
{ type: "GET",
url: "Sample.js",
dataType: "json",
data: {key:key },
success: function (data)
{ var sample = data.name; $("#html").html(sample); },
error: function () { alert("Error"); }}
);