I am making a email contact form with a ajax post on a umbraco site, I am halway thru it and was just testing the ajax part and I get a "Web Service method name is not valid" error when it runs.
I have a booking.cs in app_code, then booking.asmx in a webservice folder,
[WebService(Namespace = "http://localhost/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Booking : System.Web.Services.WebService
{
public string Email { get; set; }
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string SaveIt(string Email)
{
try
{
return "success";
}
catch (Exception er)
{
return "error";
}
}
}
javascript:
$("#email_popup_submit").click(function (e) {
$.ajax({
url: '/webservice/Booking.asmx/SaveIt',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'Email': 'testemail' },
beforeSend: function () {
},
success: function (data) {
//console.log(data.d);
if (data.d == "success") {
e.preventDefault();
// console.log('SUCCESS!');
} else {
}
},
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
}
});
})
Uncomment following line from your service code to be enabled to call from javascript/ajax
[System.Web.Script.Services.ScriptService]
you could try to change data parameter to this:
data: '{ "Email":"testemail"}'
Related
I can't access webmethod within javascript. It gives the error in the title. Why might it be caused?
Js :
function funcGoster() {
$.ajax({
type: "POST",
url: "/WebService1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// document.getElementById('text').innerHTML =
},
error: function (e) {
alert("başarısız" + e);
}
});
}
</script>
WebMethod :
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public static string HelloWorld()
{
return "Hello World";
}
}
Ok, what you have looks quite good, but note in the web service page, you have to un-comment the one line.
so, you should have this:
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
Ok, now our code and markup:
<asp:Button ID="Button1" runat="server" Text="Button" Width="153px"
OnClientClick="ajtest();return false;"/>
<br />
</div>
<script>
function ajtest() {
$.ajax({
type: "POST",
url: "/WebService1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(' back from ajax message = ' + msg.d)
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage)
}
});
}
</script>
So, we also assume you have jQuery setup for this page? You need that.
You can call the web method without jQuery.
So, pure JavaScript, you could use this:
// Web method call without jQuery
function ajtest2() {
// ajax call without jquery
var xhr = new XMLHttpRequest()
xhr.open('POST', '/WebService1.asmx/HelloWorld')
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send('{}');
xhr.onload = function () {
if (xhr.status === 200) {
var userInfo = JSON.parse(xhr.responseText)
alert(' back form ajaxes message = ' + userInfo.d)
}
}
}
I am developing a code to check whether a data already exist on the server or not. If there is a conflict, then the program must return status code 409. I can get the data returned by the webmethod via ajax.success. However, I cannot get the data via ajax.statusCode. It always returns error:
TypeError: data is undefined
I have tried this but I got an error
Non-invocable member "Content" cannot be used like a method
How do I get my object via ajax.statusCode?
C#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Case CreateNewCase(int id)
{
try
{
Case caseResponse = new Case();
//some process about checking if the ID exists and loading other data
if(idCount > 0)
{
HttpContext.Current.Response.StatusCode = 409;
return caseResponse;
}
else
{
HttpContext.Current.Response.StatusCode = 200;
return caseResponse;
}
}
catch (Exception ex)
{
HttpContext.Current.Response.StatusCode = 500;
return null;
}
}
JS:
function newCase() {
$.ajax({
url: 'Default.aspx/CreateNewCase',
data: JSON.stringify(
{id: ID }
),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
statusCode: {
409: function (data, response) {
//how do I get the "data" from WebMethod here?
loadCase(ID, data);
//TypeError: data is undefined
}
},
success: function (data, status) {
loadCase(ID, data);
},
error: function (data) {
}
});
}
You can do like this. Use Web API instead of Web method and return HttpResponseMessage instead of case
public HttpResponseMessage CreateNewCase(int id)
{
try
{
Case caseResponse = new Case();
//some process about checking if the ID exists and loading other data
if(idCount > 0)
{
return Request.CreateResponse( HttpStatusCode.Conflict, caseResponse );
}
else
{
return Request.CreateResponse( HttpStatusCode.OK, caseResponse );
}
}
catch (Exception ex)
{
return Request.CreateResponse( HttpStatusCode.InternalServerError, null);
}
}
If you want to use the web method approach then change the ajax and try to parse the error in errro function as given below
function newCase() {
$.ajax({
url: 'Default.aspx/CreateNewCase',
data: JSON.stringify(
{id: ID }
),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data, status) {
loadCase(ID, data);
},
error: function (jqXHR, textStatus, thrownError) {
if(jqXHR.status =="409" ){
var data= jqXHR.responseJSON;
loadCase(ID, data);
}
else
{
console.log(textStatus);
}
}
});
}
I am having a drop down with "Create New" option. If User clicks "Create New" option then Popup window will display with Save button. In that Popup window, User will enter data and after User will save this data on server. To achieve this what approach I should follow. Any Help Please..??
use for example from javascript:
$(function () {
$("#btnSave").click(function () {
var person = { Name: 'MrX', Age: 25 };
$.ajax({
type: "POST",
url: "/AddUser",
data: car,
datatype: "html",
success: function (data) {
/*
done
*/
}
});
});
});
and then into your controller:
[HttpPost]
public JsonResult AddUser(string data)
{
/* deserilize and insert */
or if you are using web forms you need to decorate your method like:
[WebMethod]
public static void AddUser(string data)
{
/* deserialize, add */
Note: out there are so many options you can do this. it depends in what conditions you are or what you like
JavaScript function to call C# Web Method from Ajax.
<script>
function savefile()
{
var person = 'test',
returnEmail = 'test#test.com';
var dataValue = { "name": person, "returnAddress": returnEmail };
var url = "WebForm1.aspx/OnSubmit";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(dataValue),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
if (msg.d != null) {
alert("We returned: " + msg.d);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
}
});
};
</script>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="savefile()" />
Web Method to receive Ajax Request and Process it.
using System.Web.Services;
[WebMethod]
public static string OnSubmit(string name, string returnAddress)
{
return "it worked";
//Code for writing your data to text file.
}
I am now trying to build a dnn module using ajax calls. But there is a jquery error stating
SyntaxError: Unexpected token <
I have tried to work around with ajax "url: " and tried to create a new ascx at the root folder but still showing error 404.
My ajax call is as below
$.ajax({
url: "NewsManagement.ascx/Add",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
beforeSend: function () {
},
cache: false,
data: {
title : $('#txt_Title').val(),
news_content : $('#txt_Content').val(),
image : $('#file_Image').val(),
chapter_id : $('#sel_Chapter').val(),
is_draft : $('#chk_Draft').val(),
posted_date : $('#dp_PostDate').val(),
created_by : "",
lastupdate_by : ""
},
success: function (data) {
console.log(data);
if (data == "success") {
console.log(data);
}
else {
initMdlError("SERVER : " + data);
}
},
error: function (data, textStatus, error) {
// ERROR IS BEING CALLED FROM HERE
console.log("JQUERY JAVASCRIPT : " + error);
initMdlError(error);
},
complete: function () {
console.log('complete');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is there any way to solve the issues?
The problem you're running into is that DNN isn't handling the requested URL properly that you are calling. If you want to call a service URL in DNN you're going to want to setup routes to handle the calls.
namespace Christoc.Com.Modules.SlidePresentation.services
{
public class SlidePresentationRouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapRoute("SlidePresentation", "{controller}.ashx/{action}",
new[] {"Christoc.Com.Modules.SlidePresentation.services"});
}
}
}
In the Controller you can define the methods available
[DnnAuthorize(AllowAnonymous = true)]
public ActionResult ListOfSlides()
{
try
{
var slides = Slide.GetSlides(ActiveModule.TabID, ActiveModule.ModuleID);
return Json(slides, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
DnnLog.Error(exc);
return Json(null, JsonRequestBehavior.AllowGet);
}
}
https://slidepresentation.codeplex.com/SourceControl/latest#DesktopModules/SlidePresentation/services/SlidePresentationController.cs
sample Javascript
//get slides on initialization
this.init = function(element) {
//var data = {}; //removed because we don't need this
//data.moduleId = moduleId; //removed because we don't need this when calling setModuleHeaders
//data.tabId = tabId; //removed because we don't need this
//serviceFramework.getAntiForgeryProperty(); //removed because we don't need this
$.ajax({
type: "POST",
cache: false,
url: baseServicePath + 'ListOfSlides',
//data: data,
//dataType:"json",
beforeSend: serviceFramework.setModuleHeaders
}).done(function(data) {
viewModel.slides = ko.utils.arrayMap(data, function(s) {
return new slide(s);
});
ko.applyBindings(viewModel);
$(element).jmpress();
}).fail(function () {
Console.Log('Sorry failed to load Slides');
});
};
Here's an example module that does this
https://slidepresentation.codeplex.com/
And a user group video I did years ago on this module.
https://www.youtube.com/watch?v=hBqn5TsLUxA
I am trying to make an ajax call (using IE 10) to a page that returns json (not jsonp) but I keep getting a "401 - Unauthorized: Access is denied due to invalid credentials." The site is setup in IIS to use "Windows Authentication", however, if I change the site to enable Anonymous Authentication the call works. Below is the code I am using to make the call. What am I missing with my call or what do I need to change on my webserver? The Windows Authentication is currently set up to use NTLM authentication on the Windows Auth.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="scripts/jquery-2.0.3.min.js"></script>
<script src="scripts/base64.js"></script>
<script type="text/javascript">
function QueryMyData() {
var postUrl = 'http://mydevpage/storage.ashx';
var data = 'AssetNumber=102405';
$.support.cors = true;
$.ajax({
type: "POST",
url: postUrl,
data: data,
dataType: 'json',
crossDomain: true,
cache: false,
username: "mydomain.net\\myuser",
password: "password",
beforeSend: function (xhr) {
xhr.withCredentials = true;
},
success: function (result) {
if (result) {
if (result.error)
alert(result.error);
else
alert(result.id);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Unknow Error:' + thrownError + ajaxOptions + xhr.status + " " + xhr.statusText);
}
});
}
QueryMyData();
</script>
</head>
<body>
</body>
</html>
I found a solution to my problem. While I was not ever able to get the ajax request to work with security hitting a page on another domain, I did find a way to accomplish this. I ended up creating a ProxyHandler.ashx page and setting the permission on the request using the WebClient.
html page
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
function QueryMyData() {
var postUrl = './ProxyHandler.ashx?http://mydevpage/storage.ashx';
var data = 'AssetNumber=102405';
$.support.cors = true;
$.ajax({
type: "POST",
url: postUrl,
data: data,
dataType: 'json',
cache: false,
success: function (result) {
if (result) {
if (result.error)
alert(result.error);
else
alert(result.id);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Unknow Error:' + thrownError + ajaxOptions + xhr.status + " " + xhr.statusText);
}
});
}
QueryMyData();
</script>
</head>
<body>
</body>
</html>
Here is the proxy page (ProxyHandler.ashx)
public class ProxyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string username = "svcMyServiceAccount";
string password = "password";
try
{
string uri = context.Request.RawUrl.Substring(context.Request.RawUrl.IndexOf("?") + 1);
if (uri.StartsWith("ping"))
{
context.Response.Write("<html><body>Hello ProxyHandler</body></html>");
return;
}
context.Response.ContentType = "text/plain";
byte[] bytes = new byte[context.Request.InputStream.Length];
context.Request.InputStream.Read(bytes, 0, (int)context.Request.InputStream.Length);
var data = System.Text.Encoding.UTF8.GetString(bytes);
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
//this is the magic of getting auth passed. See post http://stackoverflow.com/questions/1680718/domain-credentials-for-a-webclient-class-dont-work
wc.Credentials = CreateCredientialCached(uri, username, password, "mydomain");
var response = wc.UploadString(new Uri(uri, UriKind.Absolute), "POST", data);
context.Response.Write(response); //already in the JSON Reponse class format
}
}
catch (Exception e)
{
context.Response.Write(GetJSON(string.Empty, e));
}
}
private CredentialCache CreateCredientialCached(string uri, string userName, string userPassword, string domain)
{
CredentialCache cc = new CredentialCache();
cc.Add(new Uri(uri), "NTLM", new NetworkCredential(userName, userPassword, domain));
return cc;
}
private string GetJSON(string id, Exception error)
{
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new Response() { id = id, error = error != null ? error.ToString() : string.Empty });
return json;
}
// Necessary for IHttpHandler implementation
public bool IsReusable
{
get { return false; }
}
private class Response
{
public string id { get; set; }
public string error { get; set; }
};
}