Calling Controller Function in Ajax - javascript

I want to call this yellow colored Controller function with ajax (Image of my project).
and this is my JavaScript function in View:
function notificationDivPressed(element,x,user,numberOfUsers) {
jQuery(document).ready(function ($) {
$.ajax({
url: 'MvcApplication3/Controllers/NotificationController/ChangeReadStatus',
type: "POST",
cache: false,
data: { arg: x },
success: function (data) {
}
}
});
});
}
when I write url like that (url: 'MvcApplication3/Controllers/NotificationController/ChangeReadStatus') it doesn't work. What should I change to get a desired result?

As you saw your URL is wrong (because you're just using a mix of project paths and class name instead of proper URL that MVC framework will rewrite and route to right methods).
Change it with:
url: '#Url.Action("ChangeReadStatus", "Notification")'

Change to
url: '/Notification/ChangeReadStatus'

Related

Calling Action with ajax doesnt show page

I want to call a controller method with an Ajax call. If this is called, another view should be returned.
When I debug the code, I also reach my controller method. However, the new view is not displayed.
What am I doing wrong?
Controller:
public ActionResult RequestDetails(string requestId, string requestState)
{
// ToDo handle parameter
return View();
}
JS:
ShowDetails = function (e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$.ajax({
type: 'GET',
data: {
'requestId': dataItem.RequestId,
'requestState': dataItem.RequestState
},
url: "/Controller/RequestDetails",
contentType: 'application/json; charset=utf-8'
});
}
What I am doing wrong?
best regards
It wouldn't show unless you direct it about what to do with the result that is returned from the ajax call.
You would need to create a container html element on the main View which is currently being displayed on the page firstly:
<div id="RequestDetailsContainer">
</div>
and then in the success callback you will need to put the html returned by controller action to be displayed in that div :
$.ajax({
type: 'GET',
data: {
'requestId': dataItem.RequestId,
'requestState': dataItem.RequestState
},
url: "/Controller/RequestDetails",
contentType: 'application/json; charset=utf-8',
success: function(response) { // note this function
$("#RequestDetailsContainer").html(response);
}
});
A side note about the url property that, you should be using Url.Action for generating the urls instead of using string literals like:
url: "#Url.Action("RequestDetails","Controller")"
Hope it helps.

Calling controller function from JS file

Im using Yii framework, i want to call controller function from JS file,
My ajax code in JS file:
$.ajax({
type: "POST",
url: "operator/checkDisabledDates",
data: {
id: 1
},
success: function(data) {
alert('success');
},
error: function(data) {
alert("Fail");
}
});
where checkDisabledDates is my controller method name, and operator is my controller name.
i got wrong formation of url something like,
www.example.com/operator/agent/id/4/operator/checkDisabledDates
my ajax url just appends at last position of existing url,
i tried different combinations like,
url: "/operator/checkDisabledDates"
url: "../operator/checkDisabledDates"
url: "../checkDisabledDates"
nothing worked,
but when i use in below syntax it worked,
url: "../../checkDisabledDates"
Is there anyway to do this without hardcoding dots(.) like this???
I would suggest not using a relative path to call your controller.
Try using your domain as context
var domainName = 'yourSite.com'
url: domainName+"operator/checkDisabledDates"
I'm using in my project and it's working for me, please try this -
Define a Global Variable in JS file eg. -
var url_path = document.location.origin+document.location.pathname;
so now you can use like this
url: url_path+'?r=operator/checkDisabledDates'
or
url: url_path+'operator/checkDisabledDates'
Use this:
data = {};
data.r = 'operator/checkDisabledDates';
data.id = 1;
$.ajax({
type: "POST",
url: "index.php",
data: data,
success: function(data) {
alert('success');
},
error: function(data) {
alert("Fail");
}
});
Always works for me.

When sending jQuery post to MVC controller getting 404 error

I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int

How to get a URL from a jQuery Ajax

I have this function, and every time I call it, I need the imagesUploadScript variable to be updated with a new URL. I've implemented in the server side a JSON response with the desired URL for each request, but I'm not able to get that JSON value with jQuery.
$(function () {
$('.editor').editorInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: /* The url*/
}
});
});
I have tried this, but doesn't seem to work :S
$.getJSON("/admin/upload_url",function(result){
return JSON.stringify(result)
})
EDIT
I have restructured my code, this way my function accepts a callbacks as #Mohamad suggested and thanks to this question:
function getURL(callback) {
var url;
$.ajax({
type: "GET",
async: false,
url: "/admin/upload_url",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
url = data['url'];
callback(url);
} //success
});
}
But I'm not able to return the url for imagesUploadScript but yes this way
getURL(function(url){
console.log(url);
});
I'm confused, how should I declare this function inside the other one so imagesUploadScript get's a new URL every time is called ?
Thanks in advance for any help ! :D

MVC 4 Ajax Requests - referencing a javascript file

Im making some ajax calls to return some partial views which are working fine when the scripts are written in the view.
Script code is
<script type="text/javascript">
$.ajax({
url: "#(Url.Action("ProjectPartial", "Project"))",
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html',
data: {
documentType: $('#DocumentType').val(),
sectionName: $('#SectionName').val()
}
})
.success(function (result) {
// Display the section contents.
$('#Projects').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
</script>
What i want to do is to store these in a javascript file called renderpartial.js so that i can add ajax calls to to one file and not write them into every view.
Does anyone know if this is possible?
Ive tried putting
<script src="~/Scripts/RenderPartial.js"></script>
at the top of my page but all i get is the error function.
As long as you use inline razor syntax like #(Url.Action( you can't move it to js file
You can do it in either specifying url like
url: '/Project/ProjectPartial',
or in View.cshtml
<script type="text/javascript">
var projectUrl="#(Url.Action("ProjectPartial", "Project"))"
</script>
in RenderParial.js
url: projectUrl,
There are two ways to do it:
By using AJAX.BeginForm. Using this, helps you not to write
your javascript/jquery ajax calls but it is useful when you are
doing something with only one form. When your form renders it then
creates javascript for you which makes your view very clean.
I normally use a html5's data- attribute to read such kind of data
that is easily available from the view in my js files. Because there
are many cases where you want something to read from server in your
view and you also want that data to be accessed in your javascript
code, mainly in another view. Use razor syntac to put data in
data- attributes like this:
//I assume you write this attribute in any control like this
data-url="#(Url.Action("ProjectPartial", "Project")"
//or if you want to write it in any html helper control as html attribute like this
new { data_url="#(Url.Action("ProjectPartial", "Project")"}
Now in your external js file you can read the url while making an ajax call. You can write as many data attributes as per your needs and make your of razor syntax to give you your data eg: type-post/get, contenttype,etc. and use like this:
$.ajax({
url: $('anyinput').attr('data-url');,
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html',
data: {
documentType: $('#DocumentType').val(),
sectionName: $('#SectionName').val()
}
})
.success(function (result) {
// Display the section contents.
$('#Projects').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
How about move the following to the js file.
function getPartial(UrlToGet) {
$.ajax({
url: UrlToGet,
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html',
data: {
documentType: $('#DocumentType').val(),
sectionName: $('#SectionName').val()
}
})
.success(function (result) {
// Display the section contents.
$('#Projects').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
}
And in your view:
<script type="text/javascript">
$(function () {
getPartial('#(Url.Action("ProjectPartial", "Project"))');
});
</script>
A pattern I have used on recent projects to avoid polluting the global namespace is to encapuslate the function and configuration variables into an object-
var projectHelpers {
config: {
projectUrl: null
},
init: function() {
//Do any page setup here...
},
getPartial: function() {
if (projectHelpers.config.projectUrl) {
$.ajax({
url: projectHelpers.config.projectUrl,
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html',
data: {
documentType: $('#DocumentType').val(),
sectionName: $('#SectionName').val()
},
error: function (xhr, status) {
alert(xhr.responseText); //Consider if console.log is more appropriate here
},
success: function (result) {
$('#Projects').html(result); // Display the section contents.
}});
} else {
console.log("Missing project URL);
}
}
};
And then in the page-
projectHelpers.config.projectUrl = "#(Url.Action("ProjectPartial", "Project"))";
projectHelpers.init();
This helps encapsulate your code and is particularly useful when working with lots of external libraries to avoid variable collisions, as well as avoiding coding errors where you re-use a variable name and overwrite values.
See What does it mean global namespace would be polluted? and Using Objects to Organize Your Code.

Categories

Resources