Retrieve values from getJSON() call in jQuery - ajax

I have an ajax call in my jquery to my MVC controller:
$.getJSON('/mysite/controller/dosomething', { postId: id }, function (data) {
The 'data' that I am returning is in the form of a JsonResult, and consists of a simple custom object with 1 property called 'Message' and another property called 'Count'. Both of these values are assigned and I am returning them as follows (edited for brevity):
[HttpGet]
public JsonResult DoSomething(int postId)
{
var response = new MyAjaxResponseModel {Message = "Hello world!", Count = 66};
return Json(response, JsonRequestBehavior.AllowGet);
}
In my jQuery, I then want to be able to look at both values in the Json response, but I don't know the proper way to get at these values?

data.Message, data.Count in the callback you're passing to $.getJSON()? To inspect the structure of your data object, you can use console.log(data) (also, in that callback)

Related

AspNetBoilerplate Ajax repose error despite 200 response code

Im having some unexpected problems with a ajax call within the aspnetboilerplate system.
I want to return an array to populate a select list,
The ajax call fires correctly and hits the controller. The controller returns the results as a model successfully, except it continually hits an error.
here is my controller action:
public async Task<List<DialectDto>> GetAllDialects(int Id)
{
var language = await _languageAppService.GetLanguage(Id);
return language.Dialects;
}
Here is my ajax call
var languageId = $(this).val();
abp.ui.setBusy('#textContainer');
$.ajax({
url: abp.appPath + 'Language/GetAllDialects?Id=' + languageId,
type: 'POST',
contentType: 'application/json',
success: function (content) {
abp.ui.clearBusy('#textContainer');
},
error: function (e) {
abp.ui.clearBusy('#textContainer');
}
});
Inspecting the return object in javascript clearly shows a 200 result with all the data in the responsetext property.
Other posts suggest that the content type isnt specified correctly and this is likely the a json parse error. Ive tried setting the dataType property to both 'json' and 'text' but still get the same response
I just had the same problem in one project. I'm using AspNet Boilerplate on a web .NET5 project.
Just like in your case I had a call to a controller method in my JavaScript code that returned 200 code, while in JS I had a parse error and then the "success" code was not executed. To solve the problem I changed the return value of my controller method. I used to return an IActionResult value (i.e. the Ok() value for ASP.NET). Then I changed the return value to another object (a DTO in my case) and everything went right afterwards. For reference:
Before (not working):
[HttpPost]
public async Task<IActionResult> Method([FromBody] YourClass input)
{
// method logic
return Ok();
}
After (working):
[HttpPost]
public async Task<DtoClass> Method([FromBody] YourClass input)
{
// method logic
return dtoClass;
}
I also tested that returning a JsonResult class works with the framework just like this (e.g. return new JsonResult(result)).
Hope this helps somebody else in the future :)

What is the best way to put my variable in an Ajax request function

Context: I am working on a Spring WEB MVC app using JSP for the view.
In my JSP page i have an input text field which in fact is a jquery daterange picker:
<input type="text" name="daterange" value="01/01/2017 - 01/31/2017" />
I thought in this ajax function I can retrieve the value of my input daterange and pass it to var daterange? like this:
function filterByDate() {
$.ajax({
url : 'outbatch',
data : ({}),
success : function(data) {
var daterange = document.getElementById("daterange").value();
}
});
}
And this is my Controller (i did not pase everyting it is too long don't look at the return null i just put it for showing) method who will update my batch and get the information from my model:
#RequestMapping(value = "/outbatch", method = RequestMethod.GET)
public String updateEblnotif(Model model) {
String out_path = env.getProperty("notif_out");
List<Doc> doc_list = unmarshal(out_path, "LETTERS");
System.err.println("jbb*********" + doc_list.size());
Set<String> formname_set = new HashSet<>();
`......
return null`}
My question is: Where do I have to pass the variable in my Ajax function call to my Controller? I know that, if I am not mistaken there are several other option parameters that I can pass into an Ajax function like 'data' , 'datafilter' , 'datatype' ? Which is the best way for requesting Dates assuming in my model those are Java Date Objects
Note: I am a very Junior Developer this is my first project. My model uses a DAO with hibernate to map into the database.
Thanks to all of you for your help!
first of all you should get the value of the parameter in client side so to that you simple have to add id attribute to the tag so that your getElementById could be useful, try this :
<input type="text" name="daterange" id="daterange" value="01/01/2017 - 01/31/2017" />
now let's suppose that your function is responsible on retrieving the desired value and send it as parameter to the server side with AJAX, so it's simple :
function filterByDate() {
var daterange = document.getElementById("daterange").value();
$.ajax({
url : 'outbatch',
data : {"daterange":daterange}, //here you send the daterange over an Ajax request and by default it's sended with a GET method
success : function(data) {
alert(data); //here you will see an alert displaying the callback result coming from your spring controller
}
});
}
now we sent the daterange to the controller , so we have to get it back there : to do that you simply can try the following approach :
#RequestMapping(value = "/outbatch", method = RequestMethod.GET)
public #ResponseBody String updateEblnotif(Model model,#RequestParam("daterange") String daterange) {
//so here you're ahving the daterange parameter in controller , if you want to display it in the alert , you can send it in the return like this,
String date = "the daterange is "+daterange
return date;
}
i hope it was clearly for you.

laravel array of strings to route action

A javascript code uses "map" method on array of object to extract just the text value:
var checked_leaves = checked_ids.filter(function(elm) {
if (elm.children.length == 0)
return elm;
}).map(function(elm, index) {
return elm.text.trim();
});
this array of string is sent to a Laravel route using ajax (with Vue http)
this.vm.$http.get(this.el.action + checked_leaves).then((response) => {
console.log(response);
//this.vm.speciesDetails = JSON.parse(response.data);
}, (response) => {
});
Where the this.el.action is api/taxonomytospecies/ and the corresponding Route is:
Route::get('api/taxonomytospecies/{ids}', 'TaxonomyController#getSpeciesFromTaxonomy');
And inside TaxonomyController:
public function getSpeciesFromTaxonomy($ids) {
// Eloquent job to retrieve the data from the DB
}
1) Is there a better way to pass an array of values like the one I get from the javascript code (they are a lot of strings) to a route of a controller?
2) I get an internal 500 error. The error shows that the call is like :
api/taxonomytospecies/name1,name2,name3,name4,name5
But i don't know how to resolve this kind of error
I would suggest you to use post request instead of get as the data is large.
You can send data as an array to the server.
var data = {ids: checked_leaves};
Then send data variable in your post request.
In your controller you can get data as:
public function getSpeciesFromTaxonomy() {
$ids = request()->get('ids') // returns an array.
// Eloquent job to retrieve the data from the DB
}
And your route should be as:
Route::post('api/taxonomytospecies', 'TaxonomyController#getSpeciesFromTaxonomy');
The solution is to set the Route as:
Route::get('api/taxonomytospecies/', 'TaxonomyController#getSpeciesFromTaxonomy');
And the Vue-resource request as:
this.vm.$http.get(this.el.action, {params: { ids: checked_leaves } }).then((response) => {
but i don't understand why.

jQuery DataTables loaded on onclick with ajax data

I have a MVC 5 application utilizing the DataTables jquery library. I've worked with this before, but have always had the table load immediately with the page load. Currently, I want the page to load and allow the user to add text into a search field, call an AJAX function, and then display the returned data.
The error I'm receiving is 'Uncaught TypeError: Cannot read property 'nTable' of null' on page load.
Up to this point I've caught a few errors: Too much data being returned and the wrong order for what's expected back. These are fixed, but I still get the same error.
I know my AJAX method returns data, and I know my click events are firing.
Here's my client side code, with a quick low-down:
I have a public 'sf' variable to house the datatable instance (.DataTable, not .dataTable). Then I setup the table, with no data field. When the user clicks the search button, the ajax method fires, retrieves data (verified with Fiddler), and within the success method calls the function to add those rows to the to the table.
<script>
var sf;
$(document).ready(function () {
SetupSalesForceTable();
});
function SetupSalesForceTable() {
sf = $('#salesForceAccounts').DataTable(
{
"destroy": true
, "processing": true
, "columns": [
{ "data": "Id" },
{ "data": "AccountNumber" },
{ "data": "Name" }
]
});
}
function LoadSalesForceSearchData() {
var search = $("#salesForceSearch").val();
$.ajax(
{
"type": "GET"
, "data": { search: search }
, "url": "#Url.Action(MyMethod, MyController)"
, success: function (data) { AddRecordsToTable(data); }
, error: function () { alert('there was an error! '); }
});
}
function AddRecordsToTable(data) {
sf.rows.add(data).draw();
$("#salesForceAccounts").show();
} </script>
As I said, I've worked with DataTables before, but everything was put into the page load, and it works fine. This time, things are a bit different and I'm not sure what I'm missing. Am I missing any required parts, or have anything incorrectly configured? Thanks for your help!
Arrrrg... From another question here where I asked/learned about data and dataSrc, I realized that my separate ajax call created a wrapper around my data and was one level deeper than I was assigning. Ooops.
Here's what my AJAX controller method does (and no, these are not the real method names I use), and I'm returning just a collection of objects. This works!
[RequireAjax]
[HttpGet]
public ActionResult LoadSalesForceSearchTable(string search)
{
var model = this.MyRepo.MyMethod(search);
var json = this.Json(model, JsonRequestBehavior.AllowGet);
return json;
}
Below does NOT work with how I have my DataTables object setup. Originally, I was doing this which was adding a wrapper to the data, called 'data' that I needed with the way I used my previous datatable. Because my data was one level deeper than I was assigning, I was getting nothing.
[RequireAjax]
[HttpGet]
public ActionResult LoadSalesForceSearchTable(string search)
{
var model = this.MyRepo.MyMethod(search);
var json = this.Json(new { data = model}, JsonRequestBehavior.AllowGet);
return json;
}
Hope this helps you!

Controller action method call have the parameter as NULL while calling javascript in MVC3

I use MVC3.
I have `
function userLocation_change()
{
var text = $("#userLocation").val();
alert(text);
var url = '#Url.Action("GetAllLocations", "Home")';
var data = text;
$.post(url, data, function (result) {
});
}
`
Here is my controller action:
public JsonResult GetAllLocations(string userlocation)
{
///...some code...
return Json(..Something.., JsonRequestBehavior.AllowGet);
}
The problem is whenever the controller function is called "userlocation" parameter does have a NULL value. I want the data value would be passed to the controller action.
Could somebody plz tell me why this happens? Any update would be much appreciated.
Thanks.
You need to pass the parameter to the #Url.Action specifically via this overload method for Url.Action. You can use the RouteValueDictionary inline constructor with to instantiate.
Edit: realize now that you need that link to be populated at run time, but the Url.Action method generates the link at render time. I would suggest adding it to the query string and then reading it from the query string in your controller method. I suspect there is a more elegant way.. but I know this works.
something like: var url = '#Url.Action("GetAllLocations", "Home")?userlocation=' + $("#userLocation").val();
Modify your jQuery post function call as:
$.post(
url,
{ userlocation: text },
function(result){
....
});
This is because, you have to send data to the Controller's action method using JavaScript literal. You can view the full listing of different ways to call Controller's action using JavaScript here: http://www.asp.net/ajaxlibrary/jquery_posting_to.ashx
Your action has a string input parameter named userlocation, hence while sending the data to the action, you should specify this, like done in the code below.
Here I am using data: { userlocation: text},
function userLocation_change()
{
var text = $("#userLocation").val();
var url = '#Url.Action("GetAllLocations", "Home")';
$.ajax({
url: url,
type: 'POST',
data: { userlocation: text},
success: function (result) {
}
});
}
Hopes this solves your null problem.

Resources