Retrieving Json Object from action method in ASP.NET - javascript

I have searched and seen many solutions but yet I still am not getting any progress. I get no errors within the console and get nothing in return from the ajax request.
Here is action method code:
[HttpGet]
public ActionResult GetEmployees()
{
AWEmployeeModel aw = new AWEmployeeModel();
aw.ID = 0;
aw.Name = "Selena";
aw.Position = "Cashier";
aw.Department = "Finance";
return Json(aw,JsonRequestBehavior.AllowGet);
}
And here is my ajax call within my controller:
EmpApp.controller("AWEmpControl", function ($scope) {
loadEmployees();
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.employees = response["Name"];
}
});
}
});
I do also have the ng directives on the desired page:
<div class="container" ng-app="AWEmpApp" ng-controller="AWEmpControl">
{{employees}}
</div>
I tested to see if the scripts work fine by assigning $scope.employees = "Hello..."; and no problems, so I know it has nothing to do with script loading.... What could be the issue? I've made sure to describe the request as GET and to return a JSON object. Am I missing something?
Thanks in advance.
EDIT
I checked the firefox console and got back Parsing Error: No XML found at location.......
Which I found odd since the server returns a JSON object, so I replaced the ajax method with the following:
function loadEmployees() {
$http.get('/AWEmployee/Index/GetEmployees')
.then(function(response) {
$scope.employees =response;
});
};
Now response is html data of the page that called it (Index), instead of the JSON object ! I assume something is happening in between the communication as suggested in this post.

As you use JQuery to fetch data from server instead of $http service and moreover success function is executed asynchronous, AngularJS will not reflect any changes that was happened, to force it, just wrap assigning into $apply:
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.$apply(function(){
$scope.employees = response["Name"];
});
}
});
}

Found out the issue, it's a simple mistake on my part. I was calling http://localhost:53729/AWEmployees/Index/GetEmployees which was the wrong thing to do. I took out the Index page, so now the url looks like http://localhost:53729/AWEmployees/GetEmployees and it worked perfectly!

Related

Return view after using ajax call

I am doing a search for a date in the database using ajax to call the function. The problem is that it gives me a 404 result when it should be showing it and the ajax enters in error mode.
controller code that works
[HttpPost]
public ActionResult SearchDate(DateTime date)
{
code...
return View(employees);
}
ajax code
function SearchByDate()
{
var x = document.getElementById("DateInputField");
if (x.value != "")
{
$.ajax({
url: '/Employees/SearchDate',
type: 'GET',
data: { "date": x.value },
error: function (data) {
alert('Error!');
},
succes: function (data)
{
alert('Succes!');
}
});
}
else
{
alert('Date not selected!')
}
}
I ran the program with breakpoints and it exits with the right result but it is showing none and in the developer console i get ERROR 404!Not found! and also the ajax returns alert error.Please help! Ty
Update after some issues where fixed i get this error:
The view 'SearchDate' or its master was not found or no view engine supports the searched locations!
There are multiple errors:
[HttpPost] at backend and you are sending a GET request.
404 means file is not found, so your path might be not correct.
succes callback should be success.
contentType is not set instead you can look into traditional:true,.
Use Query string in place of send data from data parameter.
changed type: 'GET',datatype: "html", then created a partial view rendered it inside and changed the function in controller to HTTPGET and returned partial view as result!

Cannot retrieve JSON data from Last.FM's API

I am working on a school project and have run into trouble. Namely, I am building a simple AngularJS app which shows some kind of a radio chart based on Last.FM's data.
However, when trying to access the API, I never get a response.
This is the code that I use for accessing:
APIservice.getChartTracks = function () {
return $http({
method: 'JSONP',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json'
});
}
Afterwards, when I do something like this:
APIservice.getChartTracks().success(function (response) {
$scope.tracks = response.tracks.track;
});
the success() method never gets called. If I were to change the url to this one (found it on some online tutorial), I get a response and everything.
How should I go about accessing Last.FM's API?
Thanks in advance.
With $http, the method to use is GET, not JSONP. Write:
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json'
});
Or use the shortcut:
return $http.get('http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json');

Jquery ajax success, not working no return data

I really need your help.
I got this problem in my jQuery, i try to make a ajax call to a Javascript there keep an array inside in this file.
test-ajax.js
var data = ["kategori", "Alarm"];
return data;
But it come not with an array or anything not a single error.
Here is the ajax call.
$(document).ready(function() {
$(".tip").mouseover( function() {
$.ajax({
url: "http://localhost:8080/kraftvaerk/falck/FalckAlarmWeb/FalckAlarmWeb.Website/js/test-ajax.js",
dataType: "javascript",
succes: function(resultat) {
console.log("here");
$(".tip").append("<span>Katagori: " + resultat[0] + " <br /> Beskrivelse: "+ resultat[1] +"</span>");
}
});
});
});
In Html i got a table inside that table is there an a tag with class tip.
When the user mouse over that tag it should make the ajax call.
WARNING.
I use jQuery 1.2.2 the customer site i canĀ“t upgrade it
Json is not ALLOW on thit project.
You don't need to define and return a variable in your test-ajax.js file. You can simply define it as follows:
["kategori", "Alarm"]
Also, you had an extra bracket on the end that was invalid syntax.
The method you are using is more similar to jsonp. jsonp works by including a script tag on your page that points to a js script that executes a function containing the data.
For example, your test-ajax.js would be:
testajax(["kategori", "Alarm"]);
and to request it, simply do this:
window.testajax = function(data) {
console.log(data[0],data[1]);
};
$.getScript("test-ajax.js");
There you go. you just performed your first JSONP request, and it didn't involve any "json".
i try to do the same like you but from $.ajax it is not returning the result but if you use the below example then you will get the result but your file should like this :
JScript1.js ["kategori", "Alarm"]
JScript1.json ["kategori", "Alarm"]
1. $.getJSON("JScript1.js", function (data) {
console.log(data);
});
2. $.getJSON("JScript1.json", function (data) {
console.log(data);
});
result:
Array[2]
0: "kategori"
1: "Alarm"
length: 2

JQuery Ajax POST throwing an empty error without making the request

I have a function that makes an Ajax request for any anchor. The request method can be GET or POST. In this case, I want to make a POST without using a form but the Ajax request throws an error before even sending the request. The error has the value "error" and all error/failure description variables are "".
function loadPage(url,elem_id,method,data) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: data,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
When the function is called the params are these (copied from the js console):
data: "partial=yes"
elem_id: "page"
method: "post"
url: "/projects/2/follow"
As asked, here is the code that calls the loadPage function.
$("body").on("click","a.ajax",function(event) {
var _elem = getDataElem($(this));
var _method = getRequestMethod($(this));
var _partial = getRequestPartial($(this));
handlers.do_request(event,$(this).attr("href"),_elem, _method, _partial);
});
var handlers = (function() {
var obj = {};
obj.do_request = function(event,url,elem_id,method,data) {
event.preventDefault();
loadPage(url,elem_id,method,data);
history.pushState({selector:elem_id,method:method,data:data},null,url);
};
}());
After the failure of the Ajax request, the request is made by default and it responds sucesss. In all I have read, this seems to be a valid way to make a POST request (that doesn't need a form).
Am I doing something wrong in the function? Why is the error information empty?
Thanks
EDIT:
I have been thinking, for a POST from a "form" that function works, when the variable "data" is made with the serialize function (e.g. "var data = $(this).serialize();"). Could it be that the format of the "data" when I make a POST without a "form" is wrong in someway? Maybe the JQuery Ajax function doesn't accept a simple string like "partial=yes" as data when a POST is made. Any thoughts on this?
I just experienced this problem and after an hour or two, thought to try setting cache to false. That fixed it for me.
$.ajax({
url: url,
cache: false,
type: method
});
Unfortunately, when I removed cache again, my request was working as if it had never had a problem. It seems as if setting cache:false made something 'click'.
Oh well.
Just a guess, but in the docs the type parameter is in all caps, i.e. 'POST' and not 'post'.
Try:
function loadPage(url,elem_id,method,dat) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: dat,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
I'm wondering if you are running into a problem using a variable named after a keyword. If this doesn't work, try calling loadPage with no arguments and hard coding all of your ajax parameters, just to see if that works.
Could not solve the problem, neither could find the reason why it was happening. Although, I found a way around, by using a hidden empty form instead of an anchor with the method 'POST'. For a form, the function worked nicely.
Thanks for the answers

ASP.NET MVC - Render PartialView with AJAX?

Earlier today I posted another post where #Darin Dimitrov helped me great, however once again I'm stucked...
My javascript calls the AddWebsite ActionResult which does it job as it should, however the error function in the $.ajax() is always firing since
return PartialView(ListPartialView, MapUserToViewModel);
isn't valid JSON.
I've come across examples where people use something like
RenderPartialViewToString(partialview, model);
and throws it into a JSON object... but it's just too "hackish" if you ask me.. isn't there an easier way to accomplish this?
... And the code:
// DashboardController.cs
[HttpPost]
public ActionResult AddWebsite(CreateWebsiteViewModel website)
{
if (!ModelState.IsValid)
{
throw new HttpException(400, "Client-side validation failed.");
}
if (string.IsNullOrWhiteSpace(website.URL))
{
throw new ArgumentNullException("URL", "The URL cannot be empty nor contain only whitespaces.");
}
using (_session.BeginTransaction())
{
_session.Query(new AddWebsite(_contextProvider.GetUserSession.UserId, website.URL));
_session.Transaction.Commit();
}
return PartialView(ListPartialView, MapUserToViewModel);
}
// MyJs.js
$("#testform").live('submit', function () {
var test = { URL: $("#URL").val() };
$.ajax({
url: "/Dashboard/AddWebsite",
type: "POST",
data: JSON.stringify(test),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("TRIG");
$("#content").html(data);
},
error: function () {
alert("Error");
}
});
return false;
});
Thanks in advance!
In your particular instance I think the problem is with your javascript code. You are specifying the dataType (which is what the function expects to parse in the response) as json. Based on the Action you posted you should have html as the dataType and it should solve your problem. There's nothing wrong with doing that (you don't have to use JSON for everything).
Simple data
Why are you setting dataType and contentType in the first place? Since your object test is very simple you can just provide it as is and it will be consumed by Asp.net MVC without any problems and you will return your partial view.
Complex data
If your object would be more complex then you could use a different jQuery plugin that will make it possible to send complex JSON objects without strigification.

Categories