AJAX Success Function on Server - javascript

This works on my dev machine, but not on a production server. I am trying to update some divs with ajax, but they are not updated, though other parts work fine. I am using IIS 6 on the server.
When I debug this code on the server side with firebug, it does not hit any breakpoints I add to the success function.
Script:
function updateServiceInfo(nodeId) {
var id = { id: nodeId };
$.ajax({
url: '/ServiceInfo/ServiceInfoPartial',
type: 'GET',
data: id,
dataType: 'html',
success: function (data) {
$('#serviceInfoContent').html(data);
},
error: function (request, error) {
}
});
}
Controller:
public class ServiceInfoController : Controller
{
public ActionResult ServiceInfo()
{
return PartialView("ServiceInfo");
}
public ActionResult ServiceInfoPartial(string id)
{
return PartialView("ServiceInfoPartial");
}
}
Views:
serviceinfopartial
#model string
<p>
Немає опису</p>
serviceinfo
<div id="serviceInfo">
<div id="ContainerPanel" class="ContainerPanel">
<div id="serviceInfoHeader" class="collapsePanelHeader">
<div id="dvHeaderText" class="HeaderContent">
Опис сервісу</div>
<div id="dvArrow" class="ArrowClose">
</div>
</div>
<div id="serviceInfoContent" class="serviceInfoContent">
</div>
</div>
</div>
The response that is returned in the console is
GET http://localhost/Managers/GetManagers?nodeId=563344 404 Not Found 42ms

Ahhhhhhhhhhhhhh, another hardcoded url:
url: '/ServiceInfo/ServiceInfoPartial',
Never hardcode urls like this in an ASP.NET MVC application.
Always use url helpers to generate them:
url: '#Url.Action("ServiceInfoPartial", "ServiceInfo")',
or if this is in a separate javascript file where you cannot use url helpers simply use HTML5 data-* attributes on some DOM element:
<div id="serviceInfo" data-url="#Url.Action("ServiceInfoPartial", "ServiceInfo")">
...
</div>
and then in your javascript simply:
url: $('#serviceInfo').data('url'),
The reason your code doesn't work when you host it in IIS is because in IIS you are probably hosting your application in a virtual directory so the correct url is no longer /ServiceInfo/ServiceInfoPartial but is /YourAppName/ServiceInfo/ServiceInfoPartial. That's the reason why you should never hardcode any url and use helpers to generate them => it's because helpers handle this cases. Another benefit of using helpers is that if you later decide to change the layout of your routes in Global.asax you won't need to modify all your javascript files, etc... Your url managment is centralized in a single location.

This worked for me, but only tested in Chrome 53:
Create some global scope variables in your .cshtml file, just be mindful of scope issues and give your variables unique names.
<script>
globalUrl = '#Url.Action("ServiceInfoPartial", "ServiceInfo")';
</script>
Then reference your js file...
<script type="text/javascript" src="yourJsFile.js"></script>
Inside your yourJsFile.js:
url: globalUrl,

Related

External script not working (ASP.NET MVC) [duplicate]

I have a div element in my index.cshtml with id #myresults and i am trying to load data through jquery.load method by calling a mvc controller method. But i am not able to get the right syntax.
I am passing a custom object as a parameter as well.
var mycustomObject = {
obj1:value1,
obj2:value2,
..
}
The following does not work...(an i have tried other combinations as well..i get server not found error)
$("#myresults").load ('#Url.Action("MyActionMethod","Home")',mycustomObject);
while the following works
$("#myresults").load('/Home/MyActionMethod', mycustomObject);
While the last statement works, it works only on localhost.
Whats the right syntax to use for jquery load with Url.Action ?
#Url.Action() will always generate the correct url, so if your getting a 404, it means this code is in an external script file. Razor code is not executed in external scripts so your url would literally be the text "#Url.Action("MyActionMethod","Home")".
Options to solve this include
moving the code into the view or its layout
declaring a global variable in the view - var url =
'#Url.Action("MyActionMethod","Home")'; an in the external file use
$("#myresults").load(url, mycustomObject);
assign the url to an element as a data-* attribute, for example
<button type="button" id="loadSomething" data-url="#Url.Action("MyActionMethod","Home")">...</button>,and in
the external file
$('#loadSomething').click(function() {
var url = $(this).data('url');
$("#myresults").load(url, mycustomObject);
});
Define the div element as:
<div id="myresults" onload="loadMyData();"></div>
And make the ajax call in your method:
<script type="text/javascript">
function loadMyData() {
$.ajax({
cache: false,
url: '#Html.Raw(Url.Action(MyActionMethod","Home"))',
data: { obj1:value1, obj2:value2 },
dataType: "json",
type: 'post',
success: function (result) {
if (result.success) {
$('#myresults').html(result.data);
}
else {
alert("Failed to load data!");
}
}
});
}
</script>

How to use value from Jquery to Html helper razor

in JavaScript
<script>
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '#Url.Action("****", "****")',true);
xmlHttpRequest.onloadend = function() {
#{
var res = (UserResponseMvc) TempData["UserResponse"];
}
#Html.ShowAlert(res?.Message)
}
xmlHttpRequest.send();
</script>
in Controller
public ActionResult Upload() {
//code
TempData["UserResponse"] = new UserResponseMvc
{
Success = true,
Message = "Upload Success"
};
return View();
}
In this piece, the code does not know the res variable.
How can I use the res variable here?
I write in Asp.net Mvc code.
Pls help me.
You can like this:
View
<input type="button" value="ClickToSend" onclick="sendToAction()" />
<script>
function sendToAction() {
var res = ["Upload1", "Upload2", "Upload3"]; // Sample
jQuery.ajax({
type: "POST",
url: "#Url.Action("Upload")", // Upload is your action in controller
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(res),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
Action
[HttpPost]
public ActionResult Upload(List<String> res)
{
return View();
}
I think that can not happen
ShowAlert if only the function displays the message, then it should be a function of javascript.
You can't. and the reason is that they do not "live" in the same time.
The Razor variables are "Server side variables" and they don't exist
anymore after the page was sent to the "Client side".
When the server get a request for a view, it creates the view with
only HTML, CSS and Javascript code. No C# code is left, it's all get
"translated" to the client side languages.
The Javascript code DO exist when the view is still on the server, but
it's meaningless and will be executed by the browser only (Client side
again).
This is why you can use Razor variables to change the HTML and
Javascript but not vice versa. Try to look at your page source code
(CTRL+U in most browsers), there will be no sign of C# code there.
In short:
The server get a request.
The server creates "takes" the view, compute and translate all the C# code that was embedded in the view, to CSS,Javascript, and HTML.
The server returns the client side version of the view to the browser as a response to the request.
the browser renders the page and executes all the Javascripts
Refer to How to pass a value to razor variable from javascript variable?
In your case, I have a some documents for you refer.
jQuery Ajax File Upload
File upload using MVC 4 with Ajax

Jquery Autocomplete with ASP.NET Issue

I am using JqueryUI autocomplete widget with asp.net
i create one class file that contain method that will return list of search result.
and on aspx page i called all required jquery file.
on Script part i write below code:
<script type="text/javascript">
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CommonOperation.cs/GetClientName",
data: "{'SearchVal':'" + document.getElementById('<%=txtSearch.ClientID%>').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error......");
}
});
}
});
});
</script>
don't know what problem is their but when i run it always goes in Error part.
You can't put your web method in a class file, as the method itself needs to be web-accessible.
Move it to a standard ASPX page's code-behind, and use the .aspx link instead of .cs.
An alternative would simply be to use an .asmx, and attach your class to that instead. This answer provides some information on that:
You could use something like an asmx (ASP.Net web service) that exposes the webmethods. The file is basically just a markup place holder that points at a class file. Contents are just:
<%# WebService Language="C#" CodeBehind="~/foo/MyClass.cs" Class="MyClass" %>
Then your class has to inherit from System.Web.Services.WebService and you should be good.
If you do an add file from Visual Studio and add a web service file you can get it to create all this for you.
here url should be like this-> url:"CommonOperation.aspx/GetClientName",
Done It
Method will be static and declared as WebMethod and Call it from aspx.cs

Ajax request on html link click in NodeJS

I'm using nodejs to develop a website that extract data from an API using ajax requests. I use templates, .hbs files (index.hbs, area.hbs etc.). My problem is that I want to make a navbar (with text links), but since I use templates its not that easy. I need to use ajax. I have made ​​all the necessary routes, but I need help with the ajax request on the links. I have searched the internet for an answer, and tried a lot of different solutions, but nothing seems to solve my problem.
My navbar code:
<div id="navbar">
<ul>
<li>Companies</li>
<li>Area</li>
</ul>
</div>
Server.js route code:
app.get('/area', routes.goToArea);
Routes.js code:
goToArea: function (req, res) {
res.render('area');
}
I think something along those lines could work:
var url = "/area";
function area() {
$.ajax({
url: url,
type: 'GET',
Any help would be greatly appreciated!
This is how you bind click event and make an ajax request
$(document).ready(function () {
$('.navbar a').click(function () {
$.ajax({
'type': 'get',
'url': '/area',
'success': function (data) {
// use the data
}
})
})
})
Conceptionally spoken I would create partial layouts (or sections of html) which renders inside the global layout. This "Partial" should represend an Area.
I would also have a variable in the html (id or data-attribute) which represents the Area Identifier.
then your could request something like
http://myserver.com/area/tab1 or
http://myserver.com/?area=tab1
(depending how you want to structure your code / routing.
Then you whould request that partial via ajax and "Success" you would insert it into the Dom.
The docs here explain how to assemble the ajax call:
http://api.jquery.com/jQuery.ajax/
Here is a good read which might also help:
Express.js hbs module - register partials from .hbs file

How to get Asp.Net MVC 3 current project name?

I have an Asp.net MVC 3 project with name of "abc". It shows http://localhost:23543/abc/.... when debugging run in VS. The url will be http://hostname/webAppName/abc/... after publish the project in a virtual folder under the default web site of IIS 7.
However, there is some jQuery ajax call, using '/scripts/...', in a separated external js file. The absolute path of '/scripts/' will become ...wwwroot/abc/scripts/... instead of ...wwwroot/webAppName/abc/scripts/.... I am creating a js function for wrapping the ajax url links.
var fullPath = '#HttpContext.Current.Request.Url.Scheme://#HttpContext.Current.Request.Url.Authority';
function GetPath(projectName, url) {
return fullPath + projectName + url;
}
In js file: ... url: GetPath('/scripts/...')....
How to get the project name? Or is there a better solution?
Use the below code to create the mvc request url
var siteRoot = '#Url.Content("~/")';
function GetPath(url) {
return siteRoot + url;
}
In your markup, you can use a site-relative URL that will be translated to the correct form at runtime:
<script type="text/javascript" src="#Url.Content("~/Scripts/myscript.js")"></script>
Usually in script what I tend to do is AJAXify existing anchor links or forms which already have the proper url as they were generated using HTML helpers.
So for example with a form (generated using Html.BeginForm helper):
$('#myform').submit(function() {
$.ajax(}
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
}
});
return false;
});
or with an anchor (generated using Html.ActionLink helper):
$('#mylink').click(function() {
$.ajax(}
url: this.href,
type: 'POST',
success: function(result) {
}
});
return false;
});
Of course there might be some cases where you need an url other than a link or a form. What I tend to do in those cases is to use HTML5 data-* attributes on some DOM element. For example:
<div id="foo" data-url="#Url.Action("SomeAction", "SomeController")">foo bar</div>
and when I needed this url I would simply:
var url = $('#foo').data('url');
See how we don't need any GetPath function. All the urls are already part of our DOM and in the separate javascript file we simply use them.

Categories

Resources