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.
Related
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.
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 can I add a JSON file in jsfiddle? I have a JSON file but I am not able to attach it in jsfiddle. I can make a JSON object and use it, but is there any way to add an external JSON file to a fiddle?
Myjson.com provides api, which runs in Jsfiddle.net.
Custom my myjson:
// Loading JSON with CROS
var url = 'https://api.myjson.com/bins/3ko1q';
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success');
console.log(data);
},
error: function (e) {
alert('error');
console.log(e);
}
});
Myjson GET Example:
// 1. Create valid uri via POST
// 2. GET using newly created uri
var obj = {
"key": "value",
"key2": "value2"
};
var data = JSON.stringify(obj);
$("#clickMe").click(function () {
$.ajax({
url: "https://api.myjson.com/bins",
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
// load created json
$.get(data.uri, function (data, textStatus, jqXHR) {
var json = JSON.stringify(data);
$("#data").val(json);
});
}
});
});
You can harness the power of Cross-Origin Resource Sharing (CORS) to achieve your task.
Basically how CORS works is that if the Access-Control-Allow-Orign header is set in the HTTP response, then the content loaded by AJAX can be used in our script regardless of the fact it is on the same domain or some other.
Now for your purpose, you can upload your local JSON file to Dropbox's Public folder and get a Public URL, that you can load by a simple AJAX call.
The AJAX call will succeed in this case because Dropbox sets the following value in the response Access-Control-Allow-Orign:* which means any domain can use the loaded content.
Jquery code will be something like this(you can even use pure JavaScript if you prefer ).
var url = 'https://dl.dropboxusercontent.com/u/94145612/example.json';
var myJsonData= {};
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success');
console.log(data);
myJsonData= data;
},
error: function (e) {
alert('error');
console.log(e);
}
});
Example JSFiddle
Based on your comment, you want to use a pure JSON file as an external resource in a jsFiddle. You can't do this, because pure JSON is not JavaScript. Say you try to include http://example.com/foo.json as an external resource, and that file contains the following:
{"foo":"bar"}
This will result in Uncaught SyntaxError: Unexpected token :, because the JSON object is not valid JavaScript by itself.
But if you assign the JSON object to a variable, like so:
var foo = {"foo":"bar"};
then no problem.
Solution: use a modified version of your file to initialize a variable for use in the jsFiddle.
I have a header that I want to share between two sites. They are two separate sites, so I was wondering if its possible to create a javascript, that will pull from site A and display it exactly on site B
basically something like this, but having it display instead of just parsing
function fetchPage(url) {
$.ajax({
type: "GET",
url: url,
error: function(request, status) {
alert('Error fetching ' + url);
},
success: function(data) {
parse(data.responseText);
}
});
You have all the code you need right there. Just replace your "parse" function with a jQuery wrapper and select the section of the page you want. Keep in mind, this will only work if you're using the same stylesheet on both pages. If not, you'll have to pull in a copy of the styles as well.
function fetchPage(url) {
$.ajax({
type: "GET",
url: url,
error: function(request, status) {
alert('Error fetching ' + url);
},
success: function(data) {
$(data.responseText).find('#yourHeader').prependTo(document.body);
}
});
}
I am working on a public api in rails, something very simple.
Currently I have an jsonp callback in my tag class that looks like the following when invoked.
JSON:
{
"tag":
{
"id": 1,
"tag_code": "<script type=\"text\/javascript\">alert(\"hello world\"); <\/script>"
}
}
my goal is to get this code onto a remote page.
I have tried using ajax to do so, However I am to understand that jquery does not allow for external script tags to be loaded onto a page for security purposes.
JQuery on remote page
function fetchTagData(id)
{
$.ajax(
{
url: "http://localhost:3000/tag/" + id + ".js",
dataType: "jsonp",
type: "GET",
processData: false,
contentType: "application/json",
success: function(data)
{
var code = data['tag']['tag_code'];
console.log(code);
$('#test').append(code);
}
});
};
when I view the console i see the js in all of its glory and the alert box appears. When I view source or inspect element the js is not on the page.
Does anyone have an idea of how I can get the js to appear on the page using a similar method or the same?
json like this
{
"tag":
{
"id": 1,
"tag_code": "alert(\"hello world\");"
}
}
run code using eval
function fetchTagData(id)
{
$.ajax(
{
url: "http://localhost:3000/tag/" + id + ".js",
dataType: "jsonp",
type: "GET",
processData: false,
contentType: "application/json",
success: function(data)
{
var code = data['tag']['tag_code'];
console.log(code);
eval(code);
}
});
};