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>
Related
I'm currently working on a website which should heavily rely on ajax. But I'm facing a problem which I cannot find a solution to online.
I'll now shamelessly post my (stripped) function to completely fetch a page.
function loadTemplate(name, replaceWholePage = true){
$.when( $.ajax({ url: "./templates/{0}/{0}.html".format(name), error: function() { console.error( "Could not load HTML file of template '{0}'!".format(name)); }}),
$.ajax({ url: "./templates/{0}/{0}.css".format(name), error: function() { console.error("Could not load CSS file of template '{0}'!".format(name)); }}),
$.ajax({ url: "./templates/{0}/{0}.js".format(name), error: function() { console.error("Could not load JS file of template '{0}'!".format(name)); }}) )
.then(function(html, css, js) {
var _css = "\n<style>\n" + css[0] + "\n</style>";
var _js = "\n<script>\n" + js[0] + "\n</script>";
if(replaceWholePage) {
$("#content").empty();
}
$("#content").append(html[0]);
$("#content").append(_css);
//$("#content").append(_js);
});
}
You see the line where it appends the js file is commented. But somehow the site still gets the js. When I comment that line out, my js code isn't actually twice in the document, but still gets called twice.
As Varinder stated, jQuery automatically recognised the fetched file as javascript and executed it. Setting the dataType to "text" in the call fixed it!
Thanks
I was trying to make an ajax call and show an html part inside a div class. For that i used the following way.
$.ajax({
type: "get",
url: "{{url('searchByCheckbox')}}",
dataType: 'html',
success: function(html)
{
$(".infinite-scroll").html(html)
}
});
But the problem is there is a script inside that html part which i wanted to load when i make first ajax call it's not loaded but for the second one it's loaded the script.
suppose the html response like this :
<script>
alert()
</script>
// html
How do i make it work?
I put the script above the html page which i'm getting as response.
(those who are marking the Question as duplicate should read at least what i want and what they wanted )
Im sure that the error is happening because of the script, because you are closing the </script> tag inside the html.
The best solution is to return the data from your ajax call as a json
To do that you should:
1- add a dataType to your ajax parameter as the below:
$.ajax({
type: "get",
dataType: "json",
2- In the php file handling the ajax call, you must resurn the values as a json as below:
Assume that currently you are doing the following:
echo $html
You should change it to match the below:
$retArr = array(
"html" => $html, //Your html code without the javascript function
"jsFunc" => $jsFunc //Your java script function parameters
) ;
echo json_encode($retArr) ;
And then your ajax success must be as the below:
success: function(data)
{ //You can access all the object parametes by calling the object name `data` followed by a dot `.` and then by the parameter key
data.jsFunc // Your javascript function params
$(".infinite-scroll").html(data.html) ;
}
I've loaded jquery but as far as I can tell my script is not running, I don't believe its an issue with my ajax request, but rather with my loading of jquery?
I'm not getting any relevant error messages and console.log is not running.
<script src = "jquery.js">
$(document).ready(function(){
console.log('why wont my script run?')
$.ajax({
type: 'GET',
url: 'https://blockchain.info/ticker',
datatype: 'json',
success: function(data) {
window.alert('success',data)
},
error: function(error) {
window.alert('error')
}
});
});
You don't use the src attribute plus a script together within a <script> tag. It's one or the other.
If you use the src attribute then it needs to reference the .js file or the CDN.
The reason your variable isn't changing is because you need to make an AJAX call to your exchange rate API. You will then need to extract that value from the HTTP response and then update your DOM.
Okay here's my problem.
I have an html page that has a javascript variable initialized in it.
<html>
<script>
MyVaribale = "Random Data";
</script>
<!-- Then I include an external js file to handle the processes in this html file -->
<script type="text/javascript" language="javascript" src="/scripts/some_random_script.js"></script>
</html>
Now, inside that script. I used the MyVaribalevarible in one of the ajax request there, like this :
$(document).ready(function() {
$.ajax(
url : '/some/random/url',
data : { MyVariable : MyVaribale }
etc ...
);
});
So, on page load, that ajax code is executed immediately.
In the url specified above, i checked for the existence of MyVaribale, then flag an error that it is a required value if it doesn't exist.
Backend code like this (in Perl):
my $MyVariable = trim_param('MyVariable'); # trim_param() is a function that gets the passed data from ajax.
if ( $MyVariable ) { # Test if it exists
# Display something
}
else {
# Flag an error, which is my problem
}
Now I am sure that in the html page, that variable is always populated (yes 100% sure). But I always get flag errors that that value doesn't exist in my backend code (url above).
So question,
Does ajax have some issue with document.ready, maybe it executes before the variable has finished assigning a value? Any idea why this happens? Because sometimes my ajax request is successful, sometimes it's not
Thanks
The syntax of your ajax call is not correct. Have a look here and then try this code (note the addition of {, } and ,):
MyVaribale = "Random Data";
$(document).ready(function() {
$.ajax({
url: '/some/random/url',
data : { myVariable : MyVaribale }
});
});
Did not you try out some complete ajax calls? Like this.Sometimes no need to use JSON.stringify for MyVariable.
$.ajax({
url: "/some/random/url",
type: 'POST',
dataType: 'json',
data: JSON.stringify(MyVaribale),
contentType: 'application/json',
mimeType: 'application/json'
}).done(function(data) {
}).fail(function(error) {
}).always(function(){
});
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.