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);
}
});
Related
I tried to call c# function in javascript so i used this: var a = <%=MYC#FUNCTION()%>, but the function in the weird brackets execute even before my page load. like executing the function is the top priority of my code.
i want the function to execute when i am calling it in my javascript code.
Please help me, i need this for my project in school.
i tried to use this but i didnt really understood this ->
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
You are misunderstanding the life cycle of the request/response. In your code, the order of execution will be
Web browser sends a request to your web server.
Web server (C# code) now handles the request and start creating HTML response.
Web server uses your controller/view (MVC) or .aspx/.aspx.cs (web form) to create the response.
Your code "MYC#FUNCTION()" is now executed. Let assume it returns a number 123.
After this, your html response is sent back to web browser.
Web browser receives the response and display to UI. Now, if you inspect HTML you will see "var a = 123;" (123 coming from your "MYC#FUNCTION()")
If you want to execute "MYC#FUNCTION()" after page load. Then you need to look at AJAX.
Inside my controller I have this function for the route /backups
public function index()
{
$backups = \App\Backup::all();
if(request()->ajax()) {
return $backups;
}
return view('backups.index', compact('backups'));
}
My idea was that if I have my javascript ask for the data then return json if not return html.
This works fine, except when pressing the browser back button to go from lets say /backups/1 to /backups it shows the json.
Is there another function I can use that will only respond to ajax calls from my code and not the browsers?
I'd recommend adding an ajax-only query string parameter to the ajax request, e.g. ?ajax=1.
This way, you can 1. utilise the browser cache, and 2. keep the same Laravel route for both request types.
Make sure your AJAX requests use a different URL from the full HTML documents. Chrome (and most probably Firefox) caches the most recent request even if it is just a partial.
Source:
https://code.google.com/p/chromium/issues/detail?id=108425
Or:
Try setting cache to false
$.ajax({
dataType: "json",
url: url,
cache: false,
success: function (data) {...}
});
I'm trying to write a simple 2 way chat but got a problem. I'm sure it's very basic but couldn't figure out since I'm new to this.
Below is my JS code to pass a streamID to AS3:
jQuery.ajax({
url: ajaxurl,
type: 'POST',
data: 'action=sd_chat_code&chat_code='+chat_code,
success: function(data){
object.streamCompanion(data);
},
error: function(data) {
console.log(data);
}
});
and in AS file, I got the streamID passed through as below:
public function streamCompanion(data):void {
var netStreamObj:NetStream = new NetStream(_nc);
netStreamObj.play(data);
_client.attachNetStream(netStreamObj);
}
Here's my code so you can check https://codepen.io/adamboy_1802/pen/MpqyML
The variable data above returns "12345" correctly. I tried to output is via JS and there's nothing wrong:
ExternalInterface.call("function() { console.log("+data+") }")
Any advice would be greatly appreciated.
(Solved)
So after trying to create a text box and output the variable data in Flash instead of alert it out via jQuery, the problem relied in my ajax call, where I use echo json_encode(my_var), simply change it to echo my_var fixed the problem.
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
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.