ASP.NET MVC 5 Ajax controller call not working after publish - javascript

I have been working on an ASP.NET MVC 5 web application which includes a view that contains a Raphael javascript image that is using AJAX calls to controller method to get some data on the initial render. When I render the page locally on my own machine, everything executes as expected and the page loads fine. However, when I 'Publish' the application to a test server, the AJAX call hits the 'Error' function every time I try to load the page.
After some research I was able to resolve some of the javascript errors by adding this tag to the layout page:
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
However, it still does not work any time I try to use Ajax to make a call to a controller method. When I take a look at the issue with firebug i see the error that is being thrown is "Boostrap requires JQuery". I have searched the error and have ensured that the script tags are in the correct order- JQuery is being called before Boostrap:
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/boostrap.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/raphael.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/update.js")"></script>
I have also checked the permissions on the files and they both have the same, correct privs which has left me stuck. These controller calls work exactly as expected when I run the application locally on my machine, but error once I have published the application to a server.
I am not sure what else could be causing this issue. Any and all advice would be greatly appreciated!!!
Below is one of the JQuery call to the controller method:
function GetESN(area, ID) {
$.ajax({
url: "/Home/GetESN",
type: 'POST',
async: false,
dataType: 'json',
cache: false,
data: { area: area, ID: ID },
success: function (data) {
esn = data
},
error: function () {
alert('error occurred');
}
});
}
Please let me know if there any more information that is required.
UPDATE
The issue actually fell in the way the site was named- it needed to be formatted as "http://projectname.com/location". I ended up having to split the pathname to account for the "/location" bit and built the URL right at the beginning of the script. Probably not an ideal situation but it works well for my situation.

It is possible that your
"url: "/Home/GetESN",
is an incorrect url when on the web server than on your local.
Try adding
<script>
rootUrl = '#Url.Content("~")'
</script>
to _Layout.cshtml
Then update your js file so you use the rootUrl
function GetESN(area, ID) {
$.ajax({
url: rootUrl + "Home/GetESN", // or url: rootUrl + "/Home/GetESN"
type: 'POST',
async: false,
dataType: 'json',
cache: false,
data: { area: area, ID: ID },
success: function (data) {
esn = data
},
error: function () {
alert('error occurred');
}
});

There are 2 ways where you can achieve this.
Option 1
change the url as follows in your ajax call,
url: #Url.Action("GetESN", "Home")
Option 2
This is the best option if you want to avoid razor tag helpers.
Right click on the project and select "Properties".
In the properties, select the link called "Web".
In the "Web" link find "Project Url" field.
In the "Project Url", set a name to the project as following example.
Example:- http://localhost:1851/TestApp/
Once setting a project name, select "Create Virtual Directory".
In your ajax call, set the url as follows.
Example:- url: "TestApp/Home/GetESN"
Finally make sure to publish the project as the same name. Example:- TestApp

Related

Call C# server side from Javascript with parameter passing

I know this question has been asked before but nothing so far has helped me reach a final solution.
I have an ASP web page that has numerous buttons that perform different functions. I also have a dropdown box that contains a list of objects. When I select an item from the dropdown, the button functionality remains the same in each button, however I would like a function called on the server in my C# code that receives a couple of key variables that I can then pass to an API. If only one parameter can be passed, I could pass it as a JSON string, so this is not a restriction any possible solutions should be concerned with.
What I am having trouble with is determining the best way to do this. I have read some possibilities in things like using AJAX calls, an OnCommand attribute inside the asp button, WebMethods and a few other more obscure possibilities. I would like to avoid the hidden field approach as it does seem pretty hacky. That being said, I am open to changing my thoughts if people really do think it is the best way.
The relevant parts of my code are as follows:
Javascript code
function testAJAX()
{
//The console.log was called successfully, however the ProcessData function was never hit correctly
/*console.log("hello");
PageMethods.ProcessData("Hello", successAjax, failAjax);*/
$.ajax({
type: "POST",
url: "UserManagement.aspx/ProcessData",
data: '{data:"Hello"}', // passing the parameter
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "text",
success: function(retValue) {
// Do something with the return value from.Net method
alert(retValue);
}
});
}
function successAjax(response) {
alert(response.get_message());
}
function failAjax(response) {
alert(response.get_message());
}
C# code (debugging was attempted on data += " from the server";)
[WebMethod(EnableSession = true)]
public static string ProcessData(string data)
{
data += " from the server";
return data;
}
Calling the Javascript code
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server" />
<button onclick="testAJAX()">Test AJAX</button>
</form>
For the life of me, I simply can not get ANY Ajax or Web Method calls hitting my breakpoint in the server side code. I have tried:
Copying the AJAX from the top answer in this and changing the variables so that it points to my function (url: "UserManagement.aspx/ProcessData",)
Moving my script tag to be inside the body tag
Adding a ScriptManager to my form
Made sure I was not using a Master page as apparently that changes things
Using PageMethods.ProcessData(). This seems to be the closest, as it actually did hit the success function, but didn't seem to hit my ProcessData function...
I'm really at a loss as to why it is not debugging on the server, if anyone has any suggestions, that would be fantastic. I'm assuming I am missing something small, but it certainly seems to be enough to halt progress. Once I can debug, I should be good to go. Thank you all in advance.
you are not passing your data correctly
// data:"{data:Hello}", its not correct
remove and do that like this
data: { data: Hello },
and you can pass Hello variable like this
var Hello = "test";
$.ajax({
type: "POST",
url: 'UserManagement.aspx/ProcessData',
data: { data: Hello },
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});

How to refresh PHP file with AJAX

Okay, so I searched the web as much as I could and I couldn't find the solution on my problem. I also typed the question and searched for an answer as I saw similar questions to mine. Didn't help. I tried numerous solutions.
Well I have an index page that loads includes/data.php which loads the data from database and echo the .js format that is then loaded by function and display data on the page, so I have at the end of my index.php something like this:
<script type="text/javascript" src="includes/data.php"></script>
On the same index page I have a form that inserts data to database. If you refresh the page I will see refreshed includes/data.php along with new data I just inputted.
I am trying to implement AJAX so that when I click on the button I insert the data to database (already achieved this) and to refresh content of includes/data.php and index.php so it shows data right away without refreshing the index.php. This is my AJAX code:
$('#addtocal').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
// This is the part where I am stuck.
},
error : function(){
$(".error").fadeIn(2000);
$(".error").fadeOut(2000);
}
});
return false;
});
Just to mention that #calendar is where main jquery function is loading the html content based on the info from /includes/data.php. Thank you in advance for any help you can provide and let me know if you need any other information from me in order to better assist me.
P.S. I saw many suggested using .load() to load content from includes/data.php but that is not working in my case as the content from includes/data.php needs to serve other jquery function that creates html on the fly and and place it in #calendar
I got it to work. What I did I inser aditional $.ajax inside the $.ajax and on completion and I called again again the jquery that uses /includes/data.php
so the code would be something like this:
$('#addtocal').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
$.ajax({
url: "../includes/data.php",
dataType: "script",
cache: true
}).done(function() {
// Here I called other jquery function that uses ../includes/data.php
});
},
error : function(){
$(".error").fadeIn(2000);
$(".error").fadeOut(2000);
}
});
return false;
});
Thanks for your help anyway #Half Crazed gave me a clue so I get the $.getScript function and saw the way to call .js again so I tried and it worked.

How to create an ajax request within google scripts with '$' variable error?

I'd like to use the ajax() method to perform an AJAX Request. I've tried to create the below functions within scripts.google.com, but I get the following error:
function AjaxCall() {
var arr = { City: 'Moscow', Age: 25 };
$.ajax({
url: 'https://worker-aws-us-east-1.iron.io/2/projects/',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});
}
Error:
ReferenceError: "$" is not defined. (line 5, file "Code")
Is there a way to get around this issue?
It appears that jquery isn't sourced in your HTML. Keep in mind that jquery is a client side, javascript library -- so the browser needs to load the jquery javascript file. In other words, a valid reference needs to be in the HTML that is returned to the client browser.
Your comment indicated that you tried:
<script src="code.jquery.com/jquery-2.1.1.min.js"></script>
Try updating that to:
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
If you don't include the "http://" (or "https://" or "//") in the front of the URL, the browser thinks it's a relative path and will try to load that from the current directory (and that probably isn't what you were trying to do). So, if the page that you were viewing was
http://www.examplesite.com/example.html
Then, the script tag you showed in your comment would try to load jquery from
http://www.examplesite.com/code.jquery.com/jquery-2.1.1.min.js
This is likely returning a 404 error -- check your javascript console to see if it's receiving an error when trying to load the jquery script.
Also, in most cases, it's recommended that you put the script tag at the bottom (right before the closing body tag). This keeps the page rendering from being blocked as the browser download the js file. This is not likely causing the problems you were originally seeing -- just thought I'd mention it since your comment potentially indicated that you were loading it right before the ajax call.

jquery ajax - calling my asp.net web api gives a wrong url and a 404 not found message

I'm writing a small ASP.NET MVC site which also includes a WEB API in it that I wrote.
I've configured the project on my local IIS as http://localhost/mysite
On the main page of my site I'm including a js script that I wrote:
<script src="#Url.Content("~/Content/js/home.js")"></script>
on the page ready event of that js I call:
$.ajax({
url: 'api/getdetails',
accepts: 'application/json',
cache: false,
type: 'GET',
success: function (data) {
alert(data);
}
});
when looking with Fidler I see that the page call returns a 404 since it doesn't try to load it to the relative path I'm in (http://localhost/mysite) and it tries to load the root of the server - so the call looks like this http://localhost:80/api/getdetails
when I was writing web forms I used to do ajax calls such as this all the time and it always worked.
what am I missing?
Thanks
What I ended up doing is in my layout html I've added a js var:
var baseUrl = '#Url.Content("~/")';
then on my ajax call I've added that base url:
$.ajax({
url: baseUrl + 'api/getdetails',
accepts: 'application/json',
cache: false,
type: 'GET',
success: function (data) {
alert(data);
}
});
this does the trick no matter how the page looks like. even if I navigate to http://localhost/mysite/home/index
It's probably not the perfect solution, and I definitely think the old webforms way which worked was better - but I guess there are pros and cons to any technology.
Still would be happy to hear if someone has a better solution. for now - this does the trick.
When you navigate to
http://localhost/mysite
The behavior is a little different from
http://localhost/mysite/
Try that to confirm. Without the trailing slash, the "mysite" looks like a document name, not a folder, so relative paths would form from the root of the server.
What you may need to do is pass in the site content URL into your home.js and form absolute paths from it in your code.

How to get content type of a given url inside Javascript?

I want to know the content type of a given url input by the user inside my Javascript code. Actually, I have a drop-down list (html,csv,xls etc.) and I want to make it so when the user inputs an url, I want to detect the type of the content of the url and based on this type I want to set the value of my drop-down list (html,csv,xls etc.). I know, I can get the content type using Ruby like this :
require 'open-uri'
str = open('http://example.com')
str.content_type #=> "text/html"
or, also, I could use curl to get the content and then parse it to know the content type. But, I need to do this inside my Javascript code because of my need explained above. Any thought ?
EDIT_1 :
I tried this code in my javascript :
$("#wiki_form_url").change(function(){
$.ajax({
type: "GET",
url: "content.rb",
data: {
// input_url: $("#wiki_form_url").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert('Success !!!');
}).fail(function () {
alert("failed AJAX call");
});
});
I have a ruby script content.rb inside which I do :
require 'open-uri'
str = open('http://www.ofdp.org/benchmark_indices/25')
str.content_type
But, it does not seem to work. I am getting Ajax failure. May be it's because of url path of the script content.rb ? How should I specify a script path here ? (Relative or absolute)
The same origin policy prevents you from using client side JavaScript to directly discover information about arbitrary URIs (URIs you control are a different story).
You'll need to get that information with another technology, such as your server side Ruby.
You could do this by simply submitting a form to the server and returning a new webpage to the browser.
If you don't want to leave the page, then you can pass the data using Ajax. There are no shortage of Ajax tutorials out there, here is a good one from MDN.
Here's an example of an AJAX call:
$(document).ready(function () {
$("#button_check").on("click", function () {
$.ajax({
type: "GET",
url: "Your URL",
data: {
input_url: $("#textbox_id").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
});
Where your HTML is something like:
<input type="text" id="textbox_id" />
<input type="button" id="button_check" value="Submit" />
And your Ruby code would be something like:
require 'open-uri'
class TestController < ApplicationController
def index
req = open(params[:input_url])
render :text => req.content_type
end
end
I have never used RoR before, so I have no idea if this is right or works in the slightest. But it's what I could quickly conjure up when scrambling through several tutorials. It's simply the concept you seem to be looking for. You'll need to figure out how to map a URL to this method, and then update the AJAX option url to use that.
So in the Javascript code - in the done method, that means the whole AJAX request was successful and the data variable should contain the result from the Ruby code req.content_type.
Atlast I could figure out the whole thing with the great help of #Ian. Here is my completed code : In javascript file :
$("#wiki_form_url").change(function () {
$.ajax({
type: "GET",
url: "/wiki_forms/content",
data: {
input_url: $("#wiki_form_url").val()
},
dataType: "text"
}).done(function (data) {
// `data` contains the content-type
alert('Success');
console.log(data);
// alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
Inside my wiki_forms controller I created a new method named content :
def content
req = open(params[:input_url])
render :text => req.content_type
end
Then added a new route in routes.rb file :
get "/wiki_forms/content" => 'wiki_forms#content'
and used /wiki_forms/content as the ajax request url. And, everything is working nicely now.

Categories