Reference Controller Action from JavaScript - javascript

I have ASP.NET MVC actions that return JSON data. My client uses jQuery's ajax function to retrieve this data and display it on the screen. I use absolute paths to the controller actions in my JavaScript:
$.ajax({
url: '/Home/Load',
type: 'post',
dataType: 'json'
})
The problem is that in some environments, we'll add an extra virtual directory to the front, so the URL is actually /Path/To/App/Home/Load. I am wondering whether there is a way to write my JavaScript so that it doesn't need updated each time I deploy. I could use relative URLs, like ../Home/Index, but occasionally I move my JavaScript code around. Things get extra tricky when using MVC's bundler, too. It would be nice if the ~ character worked.

Here is how I do:
Add the following lines in your main view (here with the Razor syntax):
<script type="text/javascript">
var appBaseUrl = "#Url.Content("~")";
</script>
Then in Javascript:
$.ajax({
url: appBaseUrl + 'Home/Load',
type: 'post',
dataType: 'json'
})

You could put the URL into an element that is relevant to your ajax request:
<div id="mydiv" data-url="#Url.Action("Load", "Home")">Click me to load ajax request!</div>
Then change your JS code to:
$.ajax({
url: $('mydiv').data('url'), // Could be $(this).data('url') if clicking to load
type: 'post',
dataType: 'json'
})
The advantage of this is that it still uses MVCs routing so any custom routes will still work.

Related

How do I link JSON files within AJAX with Django?

I have a Django app and within it I'm using a template HTML page that utilizes a Javascript library called Cytoscape (allows you to create graphs with nodes and edges).
I have everything set up with regards to templates and static files (the CSS and basic JS functions are working), however the one thing I'm having issues with is the Ajax functions within my main javascript file. These Ajax functions are responsible for displaying the graphs from JSON files (see code below as to how), and they work fine locally without Django. But as soon as I try to incorporate the server-side implementation, the functions can no longer read these files and I don't know how to fix this.
I've attempted to copy over the JSON files into various directories (but I'm still running into a 404 not found error: "Not found filldata/undefined.json", (where filldata is my app) presumably because this URL has not been set up on the server-side.
function onUpload() {
var filename = $('input[type=file]').val().split('\\').pop();
var layoutPadding = 50;
var aniDur = 500;
var easing = 'linear';
var cy;
if (upload_true) {
var graphP = $.ajax({
url: filename,
type: 'GET',
dataType: 'json'
});
var styleP = $.ajax({
url: './style.cycss', // wine-and-cheese-style.cycss
type: 'GET',
dataType: 'text'
});
} else {
var graphP = $.ajax({
url: './undefined.json',
type: 'GET',
dataType: 'json'
});
// also get style via ajax
var styleP = $.ajax({
url: './style.cycss',
type: 'GET',
dataType: 'text'
});
}
The goal here is to be able to upload JSON files on my web page and link the .cycss (css file specific to Cytoscape) within Django to run my page on the server-side. Any help would be appreciated.
Hey Django is a web server. You cannot access files like ./style.cycss etc. You need to set up a static URL, host your files there and use that URL in your code. you can check here about hosting static files. you need to store your JSON in a similar way and use it with a URL.

Post a variable to json format in Ember.js

I apologize if this question seems basic as I am new to both stackoverflow and javascript in general.
My goal here is to store the user's dropdown menu selection as well as some other user inputs into variables, then I want to post the json file that contains the variables into a specific route where my serve-side javascript can read from. I have the variable part and user selection part covered, however, I am having trouble posting the variables to the specified route.
So in my app.js file in my ember framework, I tried the below code to test out if I can post {12345} to address:port/api/iwantmyjsonhere/ but when I run it and go to that specific page (address:port/api/iwantmyjsonhere/), it says cannot GET.
$(document).ready(function() {
$.ajax({ url : "/api/iwantmyjsonhere/",
type: 'POST',
dataType : "json",
data: "12345"
});
});
I understand that this question is lower level, so if you guys are too busy to answer, point me to any resources that might help me would be greatly appreciated too! Thanks in advance!
I guess this is not related to ember anywhere.
You are just using jQuery for ajax call and as per jQuery standards "Data" Object must be Key/Value pairs.
Means you should do something like -
$(document).ready(function() {
$.ajax({ url : "/api/iwantmyjsonhere/",
type: 'POST',
dataType : "json",
data: {id:"12345"}
});
});
You can read more on this one at -
http://api.jquery.com/jquery.ajax/
And if you want to implement it in ember way the you can use something like -
return Ember.$.ajax({
url: '/api',
method: 'POST',
dataType: 'json',
data: {//key value pairs}
}).then(function(result){
//After ajax is successful.
}

jquery ajax - calling my asp.net web api gives a wrong url and a 404 not found message

I'm writing a small ASP.NET MVC site which also includes a WEB API in it that I wrote.
I've configured the project on my local IIS as http://localhost/mysite
On the main page of my site I'm including a js script that I wrote:
<script src="#Url.Content("~/Content/js/home.js")"></script>
on the page ready event of that js I call:
$.ajax({
url: 'api/getdetails',
accepts: 'application/json',
cache: false,
type: 'GET',
success: function (data) {
alert(data);
}
});
when looking with Fidler I see that the page call returns a 404 since it doesn't try to load it to the relative path I'm in (http://localhost/mysite) and it tries to load the root of the server - so the call looks like this http://localhost:80/api/getdetails
when I was writing web forms I used to do ajax calls such as this all the time and it always worked.
what am I missing?
Thanks
What I ended up doing is in my layout html I've added a js var:
var baseUrl = '#Url.Content("~/")';
then on my ajax call I've added that base url:
$.ajax({
url: baseUrl + 'api/getdetails',
accepts: 'application/json',
cache: false,
type: 'GET',
success: function (data) {
alert(data);
}
});
this does the trick no matter how the page looks like. even if I navigate to http://localhost/mysite/home/index
It's probably not the perfect solution, and I definitely think the old webforms way which worked was better - but I guess there are pros and cons to any technology.
Still would be happy to hear if someone has a better solution. for now - this does the trick.
When you navigate to
http://localhost/mysite
The behavior is a little different from
http://localhost/mysite/
Try that to confirm. Without the trailing slash, the "mysite" looks like a document name, not a folder, so relative paths would form from the root of the server.
What you may need to do is pass in the site content URL into your home.js and form absolute paths from it in your code.

Unable to upload file using AJAX

I am trying to upload a file through AJAX. I have searched over a lot but found examples using form submit only, but I can not use form submit. I have tried several examples but nothing reaches my server. When I tried this link, it worked but again it was through a form submission.
Here is the piece of code relevant to the context
JS Code
function _upload(filedata) {
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: 'multipart/form-data',
mimeType: 'multipart/form-data', //Property added in 1.5.1
success: function (data) {
alert(data);
}
});
}
$("#cpc-uploadBtn").click(function (evt) {
var data;
data = new FormData();
data.append('file', $('#cpc-upload')[0].files[0]);
_upload(data);
});
HTML Part
<input id="cpc-upload" name="file" type="file" />
<button id="cpc-uploadBtn" type="button">Upload</button>
Edit
Is there any other way to do this without using form submit and formdata?
Assuming that you are using Safari/FireFox (only those support FormData), you need to modify your $.ajax call:
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
Seeting contentType option to false will force jQuery not to add a Content-Type header for you (otherwise the boundary string will be missing from it). Also the processData flag must be set to false so jQuery will not try to convert your FormData into a string.
Now if you know that your clients are using HTML5 you should try using new JavaScript File API - check following articles:
Working with files in JavaScript, Part 1: The Basics
Working with files in JavaScript, Part 2: FileReader
Working with files in JavaScript, Part 3: Progress events and errors
Working with files in JavaScript, Part 4: Object URLs
Working with files in JavaScript, Part 5: Blobs
In all other cases you are forced to use custom plugins, for example:
Uploadify
jQuery Form Plugin
I suppose currently FormData objects are only supported in Safari/Firefox, it has not been adopted by most of the browsers yet.
I recently struggled a lot finding ajax file uploader for asp.net and I am currently using this one in my project:
https://github.com/valums/file-uploader
there is a small alternative if you want to use
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing soinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
you can find the plugin here

Trying to set variable as part of URL in jquery ajax post

So I am trying to do a post using jQuery.ajax instead of an html form. Here is my code:
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/$org_ID',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Here is my problem:
When this was in an html form, the $org_ID that was part of the URL would actually pull the variable and send it as part of the URL. Now that this is in jquery, its just sending $org_ID as text. How can I get this to figure out what the variable, $org_ID is? I tried declaring it in the javascript but I am brand new to jquery/javascript and don't really know what i'm doing.
Thanks!
Are you rendering this in PHP? In that case you need to do:
url: '/groups/dissolve/<?php print $org_ID; ?>'
Otherwise, you need to do something like
var org_id = 'foo';
// or
var org_id = '<?php print $org_id ?>';
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/'+org_ID,
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Unlike PHP, you can't interpolate variables in javascript, you have to concatenate them with the string.
If you're trying to POST a variable (org_id) then you should put it in data:
data['org_id'] = org_id;
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
While you can concatenate params onto your url to send them in an HTTP request, putting them in a data object not only lets jQuery do more work for you & escape HTML entities etc (and keep your code cleaner), but also allows you to easily debug and play around with ajax() settings.
It's not clear in the question where your data comes from, but you can use something like:
url: '/groups/dissolve/'+orgId,
or:
url: '/groups/dissolve/?orgId='+orgId,
Short answer, concatinate
url: '/groups/dissolve/' + $org_ID

Categories