Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relatve and Absolute path in JQUERY Ajax

$.ajax(
      {
    type: "GET",                    
    url: 'Home/GetMsg',                 
    success: function (result) {        },
    error: function (req, status, error) {}
     });    

By Default URL taking relative path for Home/GetMsg. I am calling this function from different controller/view which disturb the URL. How can i mention absolute and relative path here. i did tried with URL: 'http://abc.com/Home/Getmsg' but again its not working

like image 848
user1066421 Avatar asked Dec 21 '22 05:12

user1066421


2 Answers

Use a helper:

url: '@Url.Action("GetMsg", "Home")',  

or if this is in a separate javascript file where you cannot use server side helpers, you could use helpers to generate the url on some existing DOM element using HTML5 data-* attributes:

<div id="foo" data-url="@Url.Action("GetMsg", "Home")">Foo</div>

and then in your js:

url: $('#foo').data('url'), 
like image 65
Darin Dimitrov Avatar answered Jan 05 '23 20:01

Darin Dimitrov


Since you are using MVC, you may be looking for Url.Action helper:

@Url.Action("GetMsg","Home")

Also, if you are going to be using paths within Javascript, it may be a good idea to use hidden elements with the path so that you can use the Javascript externally, for example:

@Html.Hidden("GetMsgPath",Url.Action("GetMsg","Home"))

$.ajax({
    type: "GET",                    
    url: $("#GetMsgPath").val(),                 
    success: function (result) {        },
    error: function (req, status, error) {}
}); 
like image 38
Rion Williams Avatar answered Jan 05 '23 22:01

Rion Williams