i'm tried to implement ajax using jQuery.Its my first time to use ajax.so in a button click i need to display the current datetime. For this, i write the below code
//==============aspx page===============
<script type="text/javascript">
$(document).ready(function (){
var Button1 = $("#Button1");
var Label1 = $("#Label1");
Button1.click(function (){
$.ajax({
type: "POST",
url: "/myownajax14/WebService/WebService1.asmx/GetDateTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#Label1").text(msg.d);
//alert('hi');
},
error:alert('error');
});
});
});
//================asmx.cs page===========
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetDateTime()
{
return DateTime.Now.ToString();
}
}
My problem is,it doesn't give the answer..and it doesn't show any error.Have any mistake in this code?Please help me..
I too had a similar problem it's simple try this:
You need to specify type="button" attribute.
contentType: "application/json;" means that the client need the server to response a json type data.But the server response a string type one instead.
In the "success" block,the "msg" must be like '2010-10-10',so error happens in msg.d.
try the following for a string type data,or response a json type data in the server code such as {"y":2010,"m":10,"d":10}.
contentType: "application/text; charset=utf-8",
success: function (date) {
$("#Label1").text(date);
}
Have you tried accessing the ASMX directly using a browser? This way, you can easily see what kind of response your ASMX is producing...
Related
I am a newbie at javascript and jquery and I would like some help if possible. I searched and tried to make it work, but I think I am missing something simple.
I have the following method in my cs file (CeduleGlobale.aspx.cs)
[WebMethod]
public static void SetSession(string data)
{
HttpContext.Current.Session["salesorderno"] = data;
}
I also have a some javascript in my ascx file
<script type="text/javascript">
function SetSession() {
var request;
var values = 'fred';
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
request.done(function () {
alert("Finally it worked!");
});
request.fail(function () {
alert("Sadly it didn't worked!");
});
}
</script>
The function in the script is called by
<dx:ASPxCheckBox ID="cbxHold" runat="server" AutoPostBack="true" Text="OnHold" ClientSideEvents-CheckedChanged="SetSession">
</dx:ASPxCheckBox>
And the result i keep getting is "Sadly, it didn't work!".
I know the problem is not with anything relative to the path of the url, because it worked when i passed NULL as data and had the method with no parameters.
The parameters and data is what i tripping me I believe.
You should pass serialized JSON into the method:
var values = JSON.stringify({data:'fred'});
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
You are specifying that you are sending JSON, but you don't serialize the value to JSON, so try changing the request to this:
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: JSON.stringify({data: values}), // 'stringify' the values to JSON
contentType: "application/json; charset=utf-8",
dataType: "json"
});
'fred' is not json nor object
use object notation :
{"myattr":"fred"} //you can also do {myattr:"fred"}
and then use JSON.stringify which transform it into STRING representation of json object.
The data sent through post should be sent in a {key:value} format
values={name:'fred'}
The data should be passed into [key:value] pair.
I am using asp.net datepicker. Then executing a static event when a user clicks on a date through jquery like such:
<script>
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
$("#<%= lblDate.ClientID %>").text("Are available on " + $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val());
$.ajax({
type: "POST",
url: "Schedule.aspx/DisplayAvail",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Do something interesting here.
}
});
}
});
});
</script>
Code behind:
[WebMethod]
public static void DisplayAvail()
{
//Grab data from db to check avail from this date
}
Which works fine. But, from this static method there is no way to access page level objects. How can I send data from this method to the page?
Have a look here. You can get this via NuGet
http://james.newtonking.com/projects/json-net.aspx
Once you have the NewtonSoft Json dll added as a reference to your project which contains the webmethod, you can use JSONConvert to serialize your available dates and send it client side.
public IEnumerable<string> AvailableData {get; set;}
[WebMethod]
public static void DisplayAvail()
{
this.AvailableData = GetRequiredData();
this.AvailableData = JSONConvert.SerializeObject(this.AvailableData);
}
And on the client side, you can do:
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
$("#<%= lblDate.ClientID %>").text("Are available on " + $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val());
$.ajax({
type: "POST",
url: "Schedule.aspx/DisplayAvail",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var arr = <%= this.AvailableData %>;
$.each(arr, function(index, value) {
// Do something with the data
});
});
}
});
}
});
});
I decided the best rout to go is to use JQuery load() function to load an external page into the current page as such:
...Jquery
$("#GetData").load("getData.aspx?GetDate=012420012");
...html
<div id="GetData">
...
</div>
Thanks for all your feedback, but I think that this is the best way to go. Cheers! :)
You could try using PageMethods():
This is a simple tutorial Simple PageMethods example.
And also you need to do this:
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true" />
;)
I have the follow line in my Javascript code
credenciadausuario = '<%= getCredenciada() %>';
In my code-behind I have this method
public string getCredenciada()
{
Utilidade.QuebraToken tk = new Utilidade.QuebraToken();
string credenciada = tk.CarregaToken(1, Request.Cookies["token"].Value);
return credenciada;
}
but when I put the debugger in my javascript code, the credenciadausuario variable, receives the string "<%= getCredenciada() %>" and not the return of my method. How can I call my method that are in my code-behind via javascript or jquery ?
It seems all you want to do in your code is get the value of a cookie. Why not do that in JavaScript on the client?
IF possible make use of ajax and do call the method, that will do you task.
check this post : http://pranayamr.blogspot.com/2012/01/calling-server-side-function-from.html
Cs File (codebehind)
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
Javascript
function IsExists(pagePath, dataString)
{
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
},
success:
function(result) {
alert( result.d);
}
}
});}
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'ab" }";
IsExists(pagePath, dataString);
This article from Encosia is excellent. It shows how to call a method in your code behind using jQuery ajax.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
In your code behind you have to give the method the [WebMethod] attribute:
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
To call that method using jQuery you would use the following:
$.ajax({
type: "POST",
url: "PageName.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Well, to actually CALL your code-behind methods from Javascript, you would have to use ajax. JQuery has a nice $.ajax wrapper for that.
But I think you just want to include some value into the js code once, while it's being generated and sent to the browser. In that case, you need to use a file type which ASP.NET recognizes as a dynamic file.
The easiest would be to put JS code (in a <script> tag) into .ascx files. Then <%= getCredenciada() %> will be executed and will return an actual string which will be rendered into javascript code.
Then, of course, you should include such a control to the page as a regular ASP.NET control.
And I am not saying this is the best way to achieve what you want. Sometimes it's just the fastest.
I am trying to create a webservice that takes data, posts it to a database, and returns the result. I know how to write all the C# code that does that, but it is the communication that I am having problems with. At the moment, I am just trying to invoke the service and get back "Hello World" (I start with something simple since I have no idea what I'm doing)...
My Jquery:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PersonService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg) {
alert("Success");
$("#log").html(msg);
alert(msg);
}
});
My Webservice:
public class PersonService : System.Web.Services.WebService
{
~
[WebMethod(CacheDuration = CacheHelloWorldTime,
Description="As simple as it gets - the ubiquitous Hello World.")]
public string HelloWorld()
{
return "Hello World";
}
~
}
After using chrome to Inspect the Element, and selecting the Network tab, finding my webservice, it shows me that the result was:
<?xml version="1.0" encoding="utf-8"?>
<string>Hello World</string>
So, it seems that the service executed successfully, but the success function does not fire, and there are no errors in the console. What is going on? Also, why is the result in XML?
Do I need to use Web Services, or could I just post the variables via AJAX to an ASPX page that would process it the same way it would a form submission?
Using jQuery to Consume ASP.NET JSON Web Services ยป Encosia
$(document).ready(function() {
$.ajax({
type: "POST",
url: "RSSReader.asmx/GetRSSReader",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Hide the fake progress indicator graphic.
$('#RSSContent').removeClass('loading');
// Insert the returned HTML into the <div>.
$('#RSSContent').html(msg.d);
}
});
});
Also, you're missing [ScriptMethod] on your web service method and [ScriptService] on your service class.
[WebService]
[ScriptService]
public class PersonService : WebService
{
[ScriptMethod]
[WebMethod(CacheDuration = CacheHelloWorldTime,
Description="As simple as it gets - the ubiquitous Hello World.")]
public string HelloWorld()
{
return "Hello World";
}
}
I am trying to call an ASMX method from jQuery without success. Following is my code, and I don't understand what I am missing.
File Something.js,
function setQuestion() {
$.ajax({
type: "POST",
data: "{}",
dataType: "json",
url: "http: //localhost/BoATransformation/Survey.asmx/GetSurvey",
contentType: "application/json; charset=utf-8",
success: onSuccess
});
}
function onSuccess(msg) {
$("#questionCxt").append(msg);
}
File SomethingElse.cs,
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Survey : System.Web.Services.WebService {
public Survey () {
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetSurvey() {
return "Question: Who is Snoopy?";
}
}
One thing that stands out is you have UseHttpGet=true but in your jQuery code you are using POST.
Also here is a test page I created calling an ASMX page.
[WebMethod]
public Catalog[] GetCatalog()
{
Catalog[] catalog = new Catalog[1];
Catalog cat = new Catalog();
cat.Author = "Jim";
cat.BookName ="His Book";
catalog.SetValue(cat, 0);
return catalog;
}
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "default.asmx/GetCatalog",
cache: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: handleHtml,
error: ajaxFailed
});
});
function handleHtml(data, status) {
for (var count in data.d) {
alert(data.d[count].Author);
alert(data.d[count].BookName);
}
}
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' +
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
</script>
You have to make sure you specify Json as the response format if that is what you want and get rid of UseHttpGet due to security features:
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string GetSurvey() {
return "Question: Who is Snoopy?";
}
I came across this question and had the same issue. I solved it by adding:
[WebInvoke(Method="POST",ResponseFormat=WebMessageFormat.Json)]
Below your web method attribute, if you'd like to use POST. ie:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Survey : System.Web.Services.WebService {
public Survey () {
}
[WebMethod]
[WebInvoke(Method="POST",ResponseFormat=WebMessageFormat.Json)]
[ScriptMethod(UseHttpGet = true)]
public string GetSurvey() {
return "Question: Who is Snoopy?";
}
}
Here is an example of a jQuery call to a page method on an aspx, but it would be similar to an asmx page.
$.ajax(
{
type: "POST",
url: "NDQA.aspx/ValidateRoleName",
data: '{"roleName":"' + $('[id$=RoleNameTextBox]').val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: ValidateSuccess,
error: ValidateError
});
I would also suggest removing UseHttpGet as Jim Scott suggested.
You can add the following to your options and check the objXMLHttpRequest to see a more detailed error response.
error: function(objXMLHttpRequest, textStatus, errorThrown) {
debugger;
}
You have to make sure you specify Json as the response format if that is what you want and get rid of UseHttpGet due to security features:
If you read that article then you would see that it is safe to use UseHttpGet as ASP.NET has features to block the cross site scripting attack vector.
There are plenty of valid reasons to use GET.
He can remove the data parameter and change POST to GET to make the call work. Assuming you want a JSON response it would be required to add ResponseFormat=ResponseFormat.Json as well.
The following Steps solved my problem, hope it helps some one,
To allow this Web Service to be called from script, using ASP.NET AJAX, include the following line above your asmx service class for example
[System.Web.Script.Services.ScriptService]
public class GetData : System.Web.Services.WebService
{
Add protocols under system.web in web.config, please click on the link if you are not able to view configuration
https://pastebin.com/CbhjsXZj
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
If you try chrome browser, try internet explorer it worked for me and also it is about chrome browser you must add extension to works in chrome but i dont know the name of extension