Relative URLs in AJAX requests in MVC application - ajax

I tried to make sense of the results I got (see ajax call below) in relation to this post:
Relative URLs in AJAX requests
The comments annotated with [WORKS and [FAILS] below show various URLs that worked and failed. Since the above post only talked about document based URLs, I tried to make the analogy that a method in a controller corresponds to a document and a controller to folder. However, the results below belie that analogy.
CAS is a MVC application which runs off the root of a website. Subject is a controller. Index, GetSubject and RegisterSubject are methods in the Subject controller.
Not all of these URLs should work. However, I cannot explain why one does another does not.
EDIT: UrlHelpers. I want to understand the rules. What are the rules for resolving a MVC type of url: http://[domain]/[MVC App]/[Controller]/[Method]/ [params] where params is like [p1/p2/ . . ].
I don't see the pattern. As noted below the document url = [http://localhost/cas/Subject/Index] when either method is called.
var ajaxService = (function () {
var ajaxGetJson = function (method, jsonIn, callback, errorCallback, controller) {
var ajaxUrl = getSvcUrl(method, controller);
var docUrl = document.URL; // at his point document url = http://localhost/cas/Subject/Index
//[WORKS] when ajaxUrl = ../GetSubject/359143 where 359143 is the id of Subject in database
// correctly resolves to http://localhost/cas/Subject/GetSubject/359143
//[FAILS] when ajaxUrl = ../RegisterSubject
// resolves to http://localhost/cas/RegisterSubject <-- notice Subject controller is missing.
//[FAILS] when ajaxUrl = /RegisterSubject --> resolves to http://localhost/RegisterSubject
//[WORKS] when ajaxUrl = "RegisterSubject" or "RegisterSubject/
// resovles to http://localhost/cas/Subject/RegisterSubject
//[FAILS] when ajaxURL = "GetSubject"/359143"
// resolves to http://localhost/cas/Subject/Index/GetSubject/359143
if (method === "RegisterSubject") { //workaround for the above failure
ajaxUrl = "http://localhost/cas/Subject/RegisterSubject";
}
$.ajax({
url: ajaxUrl, //getSvcUrl(method, controller),
type: "GET",
data: ko.toJSON(jsonIn),
dataType: "json",
contentType: "application/json",
success: function (json) {
callback(json);
},
error: function(json) {
errorCallback(json);
}});
}
// other AJAX types omitted
return {
ajaxGetJson: ajaxGetJson;
};
}

Related

Ajax call results in 500 {internal server error}

I am trying to send json data through ajax call.
Following is the code I used. I'm using node.js as the backend. a_filters,b_filters,etc. are arrays. I googled the error but couldn't get the code to work.
var filters =
{
"a" : a_filters,
"b" : b_filters,
"c" : c_filters,
"d" : d_filters
};
$.ajax({
url : "query/get-filtered-data",
dataType : 'json',
async: "true",
data:JSON.stringify(filters),
contentType: 'application/json; charset=utf-8',
success : function(data){
},
failure: function(data){
alert('got an error');
}
});
EDIT : This is my server-side code.
var express = require('express');
var router = express.Router();
//the URL below is correct since it redirects from 'query/'
router.get('/get-filtered-data', function (req, res, next) {
console.log(req);
var filters = JSON.parse(req.body);
console.log("foo");
var a_filters = filters["a"];
var b_filters = filters["b"];
var c_filters = filters["c"];
var d_filters = filters["d"];
res.send(query);
});
conosle.log('foo') doesn't print anything.
console.log(req) has req.body empty.
Thanks a lot in advance.
Because you are referencing req.body, you need to use a router method that includes a body - post or put.
You may also need to include type: "POST" in your jQuery Ajax method.
There is a more general semantic question about whether you should use get with a query string to communicate parameters when retrieving data rather than using a request body, but that is an API design question rather than a cause of errors.

Using AJAX with MVC 5 and Umbraco

I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.
FYI, I am using MVC 5 and Umbraco 7.
I currently have the ajax code within the partial view (will want to move this to a js file at some point).
Here is the ajax code:
function GetTime(name) {
var result = "";
$.ajax({
url: '/TimeDifference/GetTimeDifference',
//url: '#Url.Action("GetTimeDifference", "TimeDifference")',
type: 'GET',
//data: JSON.stringify({ location: name }),
data: ({ location: name }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
success: function (msg) {
result = msg;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
return result;
}
Here is the Controller:
public class TimeDifferenceController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetTimeDifference(string location)
{
DateTime utc = DateTime.UtcNow;
string timeZoneName = GetTimeZoneName(location);
TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
TimeSpan utcOffset = gmt.GetUtcOffset(utc);
TimeSpan localOffset = local.GetUtcOffset(utc);
TimeSpan difference = localOffset - utcOffset;
return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);
}
}
The above code gives me a 404 Not Found Error:
Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100
If I use:
url: '#Url.Action("GetTimeDifference", "TimeDifference")'
The #Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.
I have also tried:
#Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url: $("#URLName").val()
Url is still Null.
I have added entries in to the Global.asax.cs for routing i.e.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This doesn't seem to do anything.
I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.
As I am new to this I'm sure it something very simple I am missing.
Many thanks,
HH
Your controller won't be wired automatically, and I don't think the global.asax.cs file will work either. You can either register a custom route for your controller in an Umbraco Startup Handler: https://our.umbraco.org/documentation/reference/routing/custom-routes or you can create your controller as an Umbraco WebApi Controller, which is designed for stuff like this: https://our.umbraco.org/documentation/Reference/Routing/WebApi/.
Umbraco WebAPI controllers get wired in automatically and will return either JSON or XML automatically depending on what the calling client asks for.

How to use Angular service in place of Ajax url property

Here is code:
loader:function(param,success,error){
$.ajax({
//url: 'http://localhost/mvcController?assetid=1&dataformat=attribute',
url: assetsMVCService.execute("mvcController", { assetId: 1, dataFormat: 'attribute' }),
dataType: 'text',
type: 'post',
success: function (data) {
alert('ok');
},
error: function () {
error.apply(this, arguments);
}
});
assetsMVCService is my wrapper for Angular service. Unfortunately, a product that I am implementing forces me to use AJAX call to get data. Normally, I would use services to get data and then scope for data binding. Is it possible to use a service assigned to the url property in the code above? Interesting enough, I am hitting server with the code above. But something gets wrong on the server.
Thanks
Yes. You could do something like this:
app.service('MVC', function($http) {
var root = 'http://localhost/mvcController';
var queryParams = '?assetid=1&dataformat=attribute';
this.get = function(num) {
return $http.get(root + '/' + num + queryParams);
};
// or if you want to pass the query params in
this.execute = function(assetId, dataFormat) {
return $http.get(root + '?assetId=' + assetId + '&dataFormat=' + dataFormat;
};
// other routes
});
Note that $http can and should be used instead of $.ajax when you're using Angular. It does pretty much the same thing as $.ajax, except it plays nice with Angular.

Ajax post request from Backbone to Laravel

I'm trying to send a Backbone collection to Laravel with an Ajax Request.
I don't need to save it or update the database I just need to process the data with the Omnypay php Api. Unfortunately the Laravel Controller variable $input=Input::all() contain an empty string.
var url = 'index.php/pay';
var items = this.collection.toJSON;
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: items,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
This is the Laravel Route:
Route::post('pay','PaypalController#doPay');
And finally the Laravel Controller:
class PaypalController extends BaseController {
public function doPay() {
$input=Input::all();
}
}
Your route doesn't match, it's
Route::post('pay','PaypalController#doPay');
So the url should be
var url = 'pay';
instead of
var url = 'index.php/pay';
BTW, not sure if anything else (backnone) is wrong.
Update : toJSON is a method, so it should be (you missed ())
var items = this.collection.toJSON();
The hack solution I found to transfer a backbone collection to Laravel was to convert the collection to JSON and then wrapping it in a plain object, suitable for the jQuery Ajax POST. Here is the Code:
var url = 'index.php/pay';
var items = this.collection.toJSON();
var plainObject= {'obj': items};
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: plainObject,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
Now the $input variable of my "doPay" controller function contain an array of Backbone models.

dojo pass URL parameter into AJAX

I want to take URL parameter and pass to ajax function,
var queryParams = dojo.queryToObject(window.location.search.slice(1));
var data = dojo.toJson(queryParams, true);
console.log(data);
getCategory( data );
...
function getCategory(input){
dojo.xhrGet( {
// The following URL must match that used to test the server.
url: "http://js.localhost/dojo-release-1.5.0-src/json3.php",
handleAs: "json",
content: input,
on my URL parametetr, I pass in
?return_type=category&category_desc=Business2
when I view on firebug, the ajax request become ....
t?0=%7B&1=%0A&2=%09&3......
but data debug is correct, any idea what's wrong?
{ "return_type": "category",
"category_desc": "Business2" }
just found out that it doesn't need dojo.toJson
var queryParams = dojo.queryToObject(window.location.search.slice(1));
getCategory( queryParams );

Resources