I have a web application that is powered by ASP.NET on the server side and Javascript/jQuery on the client side. I'd like to know if it's possible to make an Ajax call to an ASP.NET WebMethod and have the returned javascript code executed. For example (very simplified example):
My HTML:
<html>
<head>
<title></title>
</head>
<body>
<div id="divMessage"></div>
</body>
</html>
In my C#:
[WebMethod]
public static string GetScriptCode()
{
return "$('#divMessage').html('This is a test');";
}
In my javascript:
$(function() {
var handler = function(msg) {
var myScriptCode = msg.d;
// I'd like $('#divMessage') to contain my message
};
$.ajax({
type: "POST",
url: "Test.aspx/GetScriptCode",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: handler
});
});
I'd like the javascript that is returned from my GetScriptCode() to execute. Any ideas how to do this?
using eval() is one option, but as everyone say eval is evil, don't use it.
I normally do it using a dynamic function like so:
var theCode = "$('#divMessage').html('This is a test');";
var F=new function (theCode);
return(F());
Sort of looks like reinventing the eval, but that's how I do it as of now.
Related
I am using JqueryUI autocomplete widget with asp.net
i create one class file that contain method that will return list of search result.
and on aspx page i called all required jquery file.
on Script part i write below code:
<script type="text/javascript">
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CommonOperation.cs/GetClientName",
data: "{'SearchVal':'" + document.getElementById('<%=txtSearch.ClientID%>').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error......");
}
});
}
});
});
</script>
don't know what problem is their but when i run it always goes in Error part.
You can't put your web method in a class file, as the method itself needs to be web-accessible.
Move it to a standard ASPX page's code-behind, and use the .aspx link instead of .cs.
An alternative would simply be to use an .asmx, and attach your class to that instead. This answer provides some information on that:
You could use something like an asmx (ASP.Net web service) that exposes the webmethods. The file is basically just a markup place holder that points at a class file. Contents are just:
<%# WebService Language="C#" CodeBehind="~/foo/MyClass.cs" Class="MyClass" %>
Then your class has to inherit from System.Web.Services.WebService and you should be good.
If you do an add file from Visual Studio and add a web service file you can get it to create all this for you.
here url should be like this-> url:"CommonOperation.aspx/GetClientName",
Done It
Method will be static and declared as WebMethod and Call it from aspx.cs
I have a function in my login page an it access is protect like other C# function by default.
protected void MyFunction()
{
//do somthing
}
I want to raise it in JavaScript something like this
<script>
$.rise(MyFunction)
</script>
Someone said should use
__doPostBack(control, arg);
Or
<a .... onclick="TriggerPostBack('control', 'arg')" .. />
Or....
but all of this is for an ASP.NET object and if you use ASP.NET object it automatically generate callback and __doPostBack and everything you need.
Unfortunately I dont have an ASP.NET object and I use a simple HTML tag and want to raise a c# function by JavaScript manually.
is it possible? and the access of function what should be? and about the security? is it logical or illogical?
At the end I want to postback happen because I am familiar with jQuery AJAX and in this case I dont need it. I want postback happen.
Change your method to a static webmethod and try an jquery ajax post.
$.ajax({
type: "POST",
url: "YourPage.aspx/MyFunction",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
[WebMethod]
public static void MyFunction()
{
}
I can't achieve this one:
I have a dynamically-generated table in HTML. One of the columns contains just links, it's a column that contains tags. So every link has assigned a function that makes an ajax call and communicates with an aspx:
function cargaDatosModificacion(id) {
var dto = {};
dto.idPromoBanco = id;
var dtoJSON = JSON.stringify(dto);
$.ajax({
async: false,
url: 'PromosBancos.aspx/CargaDatosModificacion',
cache: false,
dataType: 'json',
type: "POST",
data: dtoJSON,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
},
error: errorResponse
});
}
So as you can see, the function receives an ID an calls 'PromosBancos.aspx/CargarDatosModificacion' via ajax.
Well, that aspx contains some ASP controls, like textbox and stuff.
When I try to 'do the stuff' with that controls, I notice that I don't have access to them. So yes, it's the 'static' clause.
Obviously when I get rid of the 'static' keyword, I won't be able to make the ajax call work.
I tried making every control static, didn't work either.
So I'm in the middle of this trouble, and the question is: Is there ANY chance that I can access to the ASP Controls from a static method?
Or: Is there any way to achieve what I'm trying to do? (access ASP controls after clicking on a HTML element).
I am new in the area of jQuery/Ajax and my little test function doesn't work. And my page is also refreshingcan any one help me
<script type="text/javascript" >
$(document).ready(function() {
$("#ser_itm").change(function() {
var id=$(this).val();
var dataString = 'id='+ id;
alert(dataString);
$.ajax({
type: "POST",
url: "bar_pull.php",
data: dataString,
cache: false,
success: function(html) {
$("#tbl").html(html);
}
});
});
});
Pass the function, not the result of the function call:
$('.linkDetails').on('click', getDetailsFromServer);
Apply the same to your AJAX success callback:
success: postToPage
Also, the getDetailsFromServer() function needs to be defined before you bind it to an event. Move the function declaration before your .on('click', ...) call.
So I'm going to try and explain these points more clearly:
You cannot access C:\Users\yah\Desktop\text.txt. This is a server side path, your javascript runs on the client side. So this needs to be a path you can browse to in your browser, something like /pathinURL/text.txt. How you do this is dependant on your hosting technology, etc.
Your call backs are also wrong,
$('.linkDetails').on('click', getDetailsFromServer());
&
success: postToPage()
these will execute the function when they are hit, (well it actually binds the function result) not when the event happens. To make these work you need to remove the braces:
$('.linkDetails').on('click', getDetailsFromServer);
&
success: postToPage
this then hooks up the actual functions as function pointers and thus the actual functions will be fired when you want them to be.
so your final code will look like:
$('.linkDetails').on('click', getDetailsFromServer);
function getDetailsFromServer() {
$.ajax({
type: 'GET',
url: '/someURL/text.txt',
success: postToPage
});
}
function postToPage(data) {
$('.textDetails').text(data);
console.log(data);
}
what Arun P Johny said is right! but your code has another probloem
$('.linkDetails').on('click', getDetailsFromServer);
try above
The same origin policy implemented by browsers prevents local file system urls... if the page and the files are in same folders it might work.
See SOP for file URI for FF
I would like to parse JSON array data with jquery ajax with the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function jsonparser1() {
$.ajax({
type: "GET",
url: "http://10.211.2.219:8080/SampleWebService/sample.do",
dataType: "jsonp",
success: function (xml) {
alert(xml.data[0].city);
result = xml.code;
document.myform.result1.value = result;
},
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the first name" onclick=jsonparser1() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
My JSON data is:
{"Data": [{"Address":"chetpet","FirstName":"arulmani","Id":1,"LastName":"sathish","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"ramaraj","Id":3,"LastName":"rajesh","City":"chennai"},{"Address":"ramapuram","FirstName":"yendran","Id":3,"LastName":"sathi","City":"chennai"}],"Code":true}
But i am not getting any output...anybody please help out...
Concept explained
Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Summary
Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.
If you have reqested with query string
?callback=my_callback_method
then, your server must response data wrapped like this:
my_callback_method({your json serialized data});
You need to use the ajax-cross-origin plugin:
http://www.ajax-cross-origin.com/
Just add the option crossOrigin: true
$.ajax({
crossOrigin: true,
url: url,
success: function(data) {
console.log(data);
}
});
Your JSON-data contains the property Data, but you're accessing data. It's case sensitive
function jsonparser1() {
$.ajax({
type: "GET",
url: "http://10.211.2.219:8080/SampleWebService/sample.do",
dataType: "json",
success: function (xml) {
alert(xml.Data[0].City);
result = xml.Code;
document.myform.result1.value = result;
},
});
}
EDIT Also City and Code is in the wrong case. (Thanks #Christopher Kenney)
EDIT2 It should also be json, and not jsonp (at least in this case)
UPDATE According to your latest comment, you should read this answer: https://stackoverflow.com/a/11736771/325836 by Abdul Munim
Try
alert(xml.Data[0].City)
Case sensitivly!
you need to parse your xml with jquery json parse...i.e
var parsed_json = $.parseJSON(xml);
alert(xml.data[0].city);
use xml.data["Data"][0].city instead
use open public proxy YQL, hosted by Yahoo. Handles XML and HTML
https://gist.github.com/rickdog/d66a03d1e1e5959aa9b68869807791d5