I'm trying to call a function exposed by WCF service using ajax but the success method is always returning 'undefined' even though the function itself on the WCF side is returning the right answer
I tried debugging and printing everything and the WCF is returning the right answer but when the ajax call enters the success method object it receives is undefined
WCF:
[OperationContract]
[ WebInvoke (
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json
)]
public Result_Login LoginAdmin(string email, string password)
{
System.Diagnostics.Debug.WriteLine("LoginAdmin called");
#region Declaration And Initialization Section.
Result_Login resultLogin = new Result_Login();
#endregion
#region Body Section
try
{
BLC.BLC oBLC_Default = new BLC.BLC();
BLCInitializer oBLCInitializer = new BLCInitializer();
oBLCInitializer.ConnectionString = ConfigurationManager.AppSettings["CONN_STR"];
System.Diagnostics.Debug.WriteLine("Connection string: "+ConfigurationManager.AppSettings["CONN_STR"]);
using(BLC.BLC oBLC = new BLC.BLC(oBLCInitializer))
{
resultLogin.login = oBLC.SignInAdmin(email, password);
}
}
catch(Exception ex)
{
if(ex.GetType().FullName != "BLC.BLCException")
{
resultLogin.ExceptionMsg = string.Format("Get_Persons : {0}", ex.Message);
}
else
{
resultLogin.ExceptionMsg = ex.Message;
}
}
#endregion
#region Return Section
return resultLogin;//giving the right result before ajax return method
#endregion
}
public override string ToString()
{
return base.ToString();
}
// Add more operations here and mark them with [OperationContract]
}
#region Action_Result
public partial class Action_Result
{
#region Properties.
public string ExceptionMsg { get; set; }
#endregion
#region Constructor
public Action_Result()
{
#region Declaration And Initialization Section.
#endregion
#region Body Section.
this.ExceptionMsg = string.Empty;
#endregion
}
#endregion
}
#endregion
#region Result_Login
public partial class Result_Login : Action_Result
{
#region Properties.
public bool login { get; set; }
#endregion
}
Javascript:
function IsAuthenticated_JSON() {
try {
_Params1 = new Object();
_Params1.email = $("#Login1_UserName").val();
_Params1.password = $("#Login1_Password").val();
_Params = JSON.stringify(_Params1);
_Service_Method = "LoginAdmin";
CallService(_Service_Method, IsClientAuthenticated_Completed, Service_Call_InCompleted);
}
catch (e) {
alert("IsAuthenticated_JSON: " + e.Message);
}
}
function IsClientAuthenticated_Completed(i_Input) {
try {
localStorage.setItem("UserInfo", JSON.stringify(i_Input.My_Result));
console.log("unstringify: " + JSON.stringify(i_Input.My_Result));//undefined
if (localStorage.getItem('UserInfo') != null) {
_UserInfo = JSON.parse(localStorage.getItem('UserInfo'));
_Ticket = _UserInfo.Ticket;
alert("done");
}
}
catch (e) {
console.log("error "+e.Message + " " + e.log)
}
}
function CallService(i_Service_Method, i_Success_Method, i_Failure_Method) {
var url = "";
url = js_Prepare_WCF_Url_For_Call();
var request = $.ajax({
type: "POST",
url: url,
data: _Params,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
console.log("data: "+msg.data +"status: "+ msg.status +"message: " + msg.Message);//undefined
i_Success_Method(msg);
},
error: function (msg) {
console.log("fail: " + msg.responseText + msg.statusText)
}
});
}
Web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="FuelAppEntities" connectionString="metadata=res://*/DALC.csdl|res://*/DALC.ssdl|res://*/DALC.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=FuelApp;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="CONN_STR" value="Data Source=.;Database=FuelApp;User ID=sa;Password=sa" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="project.Service1AspNetAjaxBehavior">
<enableWebScript />
</behavior>
<behavior name="My_Behavior">
<webHttp defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="project.WCF.customBinding0">
<binaryMessageEncoding />
<httpTransport />
</binding>
</customBinding>
<webHttpBinding>
<binding maxBufferPoolSize="1048576" maxReceivedMessageSize="1048576" maxBufferSize="1048576" name="jsonpWebHttpBinding" useDefaultWebProxy="false" crossDomainScriptAccessEnabled="false" />
</webHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0"/>
<services>
<service name="project.WCF">
<endpoint address="a" behaviorConfiguration="project.Service1AspNetAjaxBehavior"
binding="webHttpBinding" contract="project.WCF" />
<endpoint address="" binding="webHttpBinding" bindingConfiguration="jsonpWebHttpBinding" contract="project.WCF" behaviorConfiguration="My_Behavior" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Apple" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Android" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.WindowsPhone" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Blackberry" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Windows" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Not sure why you meet this problem , I have copied your code and have a test, but I could get the response.
Below is my code.
[ServiceContract]
public class MyTestRestService
{
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json
)]
public Result_Login LoginAdmin(string email, string password)
{
Result_Login resultLogin = new Result_Login();
resultLogin.ExceptionMsg = "exception";
resultLogin.login = true;
return resultLogin;
}
}
Model
public partial class Action_Result
{
public string ExceptionMsg { get; set; }
public Action_Result()
{
this.ExceptionMsg = string.Empty;
}
}
public partial class Result_Login : Action_Result
{
public bool login { get; set; }
}
Endpoint config.
<service name="Service.Rest.MyTestRestService" >
<endpoint binding="webHttpBinding" contract="Service.Rest.MyTestRestService" behaviorConfiguration="web"></endpoint>
</service>
To enable cross origin request, if your wcf rest server and your client are not at the same origin.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="*"/>
</customHeaders>
</httpProtocol>
protected void Application_EndRequest(object sender, EventArgs e)
{
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.StatusCode = 200;
}
}
The result.
It worked after adding
<webHttp defaultOutgoingResponseFormat="Json" />
to the service behavior in web.config
Related
I have simple login page which uses AJAX POST the page works fine in the browsers. I have created an android studio project with the web view and given the link of the login page, I have also included HTML 5 features for the page, but the login page does not send or receive any data when i run it on the android studio emulator.
The AJAX POST CODE is as follows
var ins = empID + "~" + empPassword;
$.ajax({
type: "POST",
contentType: "application/json",
url: "http://Servername/Service1.svc/json/EmpLogin",
data: '{"EDetailslogin": "' + ins + '"}',
crossDomain: true,
dataType: "json",
processData: false,
success: function(data) {
widow.location.href = "Page2.html";
},
error: function(data) {
alert("User Not Recognized");
}
});
The android manifest code is as follows
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.Myproj.Sample">
<uses-permission android:name="android.permission.INTERNET" />
<application android:allowBackup="true" android:icon="#mipmap/ic_launcher" android:label="#string/app_name" android:roundIcon="#mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
My Main Activity.java file has the following code with the HTML-5 features added to the page.
public class MainActivity extends AppCompatActivity {
private WebView wv1;
public String TAG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv1 = (WebView) findViewById(R.id.webView);
wv1.setWebViewClient(new MyBrowser());
String url = "file:///android_asset/login.html";
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
WebSettings ws = wv1.getSettings();
ws.setJavaScriptEnabled(true);
ws.setAllowFileAccess(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
try {
Log.d(TAG, "Enabling HTML5-Features");
Method m1 = WebSettings.class.getMethod("setDomStorageEnabled", new Class[] {
Boolean.TYPE
});
m1.invoke(ws, Boolean.TRUE);
Method m2 = WebSettings.class.getMethod("setDatabaseEnabled", new Class[] {
Boolean.TYPE
});
m2.invoke(ws, Boolean.TRUE);
Method m3 = WebSettings.class.getMethod("setDatabasePath", new Class[] {
String.class
});
m3.invoke(ws, "/data/data/" + getPackageName() + "/databases/");
Method m4 = WebSettings.class.getMethod("setAppCacheMaxSize", new Class[] {
Long.TYPE
});
m4.invoke(ws, 1024 * 1024 * 8);
Method m5 = WebSettings.class.getMethod("setAppCachePath", new Class[] {
String.class
});
m5.invoke(ws, "/data/data/" + getPackageName() + "/cache/");
Method m6 = WebSettings.class.getMethod("setAppCacheEnabled", new Class[] {
Boolean.TYPE
});
m6.invoke(ws, Boolean.TRUE);
Log.d(TAG, "Enabled HTML5-Features");
} catch (NoSuchMethodException e) {
Log.e(TAG, "Reflection fail", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Reflection fail", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Reflection fail", e);
}
}
wv1.loadUrl(url);
//wv1.loadUrl("file:///android_asset/index.html");
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
I have also Imported all the necessary class files. Still the application does not seem to work. Can anyone please help me with this.
How can I add form fields when I click on link only by using Struts2, jsp without javascript/jquery.
I want when I click on addCompte link in the same page jsp add more fields about compte in addition of client fields already exist.
I want to stay in the same jsp page, when user click on the link more fields about Account display. the Question is when user click on the link which expression should me use in
This my client.jsp code:
<body>
<h1>Show de Clients</h1>
<s:form action="updateClient">
<s:textfield name="nom" label="Nom"/>
<s:textfield name="prenom" label="Prenom"/>
<s:textfield name="age" label="Age"/>
<s:textfield name="codeClient" label="CodeClient"/>
<s:url var="addCompteURL" action="addCompteToClient">
<s:param name="codeClient" value="%{codeClient}"></s:param>
<s:hidden name="moreCompte" value="yes" label="hide"></s:hidden>
</s:url> <s:a href="%{addCompteURL}" onclick="">addCompte</s:a>
<s:if test="%{moreCompte!=null}">
<s:textfield name="numeroCompte" label="NumeroCompte"/>
<s:textfield name="solde" label="Solde"/>
<s:textfield name="dateCreation" label="DateCreation"/>
<s:submit action="addCompteToClient"
value="addCompteToClient" align="center">
</s:submit>
</s:if>
<s:else>
<s:submit action="updateClient" value="update client"
align="center">
</s:submit>
</s:else>
</s:form>
</body>
this my action code ClientAction.java:
public class ClientAction extends ActionSupport{
private int codeClient;
private String nom;
private String prenom;
private int age;
private String adresse;
private String numeroCompte;
private double solde;
private Date dateCreation;
private Client client;
List<Client> clientList;
ServiceMetier serviceMetier= new ServiceMetierImpl();
public int getCodeClient() {
return codeClient;
}
public void setCodeClient(int codeClient) {
this.codeClient = codeClient;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getNumeroCompte() {
return numeroCompte;
}
public void setNumeroCompte(String numeroCompte) {
this.numeroCompte = numeroCompte;
}
public double getSolde() {
return solde;
}
public void setSolde(double solde) {
this.solde = solde;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public List<Client> getClientList() {
System.out.println("methode getClienList");
return clientList;
}
public void setClientList(List<Client> clientList) {
System.out.println("methode setClientList");
this.clientList = clientList;
}
public String init(){
// clientList = serviceMetier.getAllClient();
System.out.println("methode init ");
return SUCCESS;
}
public String afficher(){
clientList=serviceMetier.getAllClient();
// client=serviceMetier.getClient(9);
System.out.println("methode afficher "+clientList);
return SUCCESS;
}
public String ajouter(){
System.out.println("methode afficher "+clientList);
BanqueFactory banque=new BanqueFactory();
Compte compte=banque.buildCompte();
compte.setNumeroCompte(numeroCompte);
compte.setSolde(solde);
compte.setDateCreation(dateCreation);
Client client=banque.buildClient();
client.setCodeClient(codeClient);
client.setNom(nom);
client.setPrenom(prenom);
client.setAge(age);
client.setAdresse(adresse);
client.addCompte(compte);
serviceMetier.createClient(client);
clientList=serviceMetier.getAllClient();
return SUCCESS;
}
public String addCompte(){
System.out.println("methode addCompte");
/*
BanqueFactory banque=new BanqueFactory();
Compte compte=banque.buildCompte();
compte.setNumeroCompte(numeroCompte);
compte.setSolde(solde);
compte.setDateCreation(dateCreation);
Client client=banque.buildClient();
client.setCodeClient(codeClient);
client.setNom(nom);
client.setPrenom(prenom);
client.setAge(age);
client.setAdresse(adresse);
client.addCompte(compte);
serviceMetier.updateClient(client);
// if(codeClient>0){
// serviceMetier.updateClient(codeClient);
// codeClient=0;
// }
*/
client=serviceMetier.getClient(codeClient);
return SUCCESS;
}
public String update(){
client=serviceMetier.getClient(codeClient);
if(nom!=null){
client.setNom(nom);
}
if(prenom!=null){
client.setPrenom(prenom);
}
if(age!=0){
client.setAge(age);
}
if(adresse!=null){
client.setAdresse(adresse);
}
serviceMetier.updateClient(client);
return SUCCESS;
}
public String delete(){
System.out.println("methode delete");
// if(codeClient>0){
serviceMetier.deleteClient(codeClient);
// codeClient=0;
// }
clientList=serviceMetier.getAllClient();
return SUCCESS;
}
}
this my struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="default" extends="struts-default" namespace="/">
<action name= "login" class="org.presentation.action.Account">
<result name="reussite" type="redirectAction">listClient</result>
<result name="echec">logging.jsp</result>
</action>
<action name="clientInit" class="org.presentation.action.ClientAction"
method="init">
<result name="success">index.jsp</result>
</action>
<action name= "addClient" class="org.presentation.action.ClientAction"
method="ajouter">
<result name="success">clientShow.jsp</result>
</action>
<action name="listClient" class="org.presentation.action.ClientAction"
method="afficher">
<result name="success">clientShow.jsp</result>
</action>
<action name="updateClient" class="org.presentation.action.ClientAction"
method="update">
<result name="success">client.jsp</result>
</action>
<action name="addCompteToClient" class="org.presentation.action.ClientAction"
method="addCompte">
<result name="success">client.jsp</result>
</action>
<action name="deleteClient" class="org.presentation.action.ClientAction"
method="delete">
<result name="success">clientShow.jsp</result>
</action>
</package>
</struts>
It's possible by using Struts2, jsp without javascript/jquery? if not how can I add jquery code in Struts2?
Ajax is not sending the data to the specified URL. Here is my controller:
#Controller
public class HomeController {
private List<User> userList = new ArrayList<User>();
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
public String showForm() {
return "AddUsers";
}
#RequestMapping(value = "User.htm", method = RequestMethod.POST)
public #ResponseBody
String addUser(#ModelAttribute(value = "user") User user,
BindingResult result) {
String returnText;
if (!result.hasErrors()) {
userList.add(user);
returnText = "User has been added to the list. Total number of users are"
+ userList.size();
} else {
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value = "ShowUsers.htm")
public String showUsers(ModelMap model) {
model.addAttribute("Users", userList);
return "ShowUsers";
}
}
AddUser.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function AjaxCall() {
alert('ready');
//get the form variables....
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: "AddUsers.htm",
data: " name=" + name + "&education=" + education,
success: function (response) {
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error: function (e) {
alert('ERROR : ' + e);
}
});
}
</script>
<body>
<h1>Welcome to the AddUsers page. </h1>
<table>
<tr><td>Enter your name : </td><td> <input type = "text" id="name"></td></tr>
<tr><td>Educational qualification : </td><td> <input type = "text" id="education"></td></tr>
<tr><td colspan = "2"><input type="button" value="Add Users" onclick="AjaxCall()"></td></tr>
<tr><td colspan = "2"><div id ="info"></div></td></tr>
</table>
Show users
</body>
</html>
I have inserted an alert within the ajax which never comes up. So I believe there is something wrong with the ajax method.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have also created a domain class which would store the student information:
public class User {
private String name = null;
private String education = null;
public void SetName(String name) {
this.name = name;
}
public String GetName() {
return name;
}
public void SetEdu(String education) {
this.education = education;
}
public String GetEdu() {
return education;
}
}
There is also a warning:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with
URI [/sum/] in DispatcherServlet with name 'appServlet'>`
Dispatch servlet:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources
in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-
INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.faisal.sum" />
</beans:beans>
I corrected the upper case problem ($.ajax instead of $.Ajax). Thanks for pointing out.
Now I have a different error:
POST http://localhost:8080/sum/AddUsers.htm 405 (Method Not Allowed)
change url:"AddUsers.htm" to url: "${pageContext. request. contextPath}/AddUsers.htm" and try.
the url you are calling is this
type: "POST",
url: "AddUsers.htm",
Which is POST, the controller method is GET. Hecne the 405 error, method not supported.
You try to send POST request but mapped your method call with GET method
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
try to change RequestMethod.GET to POST
Hi everyone I am trying to calla wcf service from a javascript function for some reason asp.net is not recognizing the namespace and give me an error on runtime, any help will be greatly appreciated following is code:
Default aspx page
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WeatherService.svc"/>
</Services>
</asp:ScriptManager>
Enter a zipcode:
<input id="zipCodeInput" type="text" />
<br/>
<input id="getForecastButton" type="button" value="Get Forecast" onclick="onGetForecast()"/>
<br/>
<div id="resultsDiv">
</div>
</form>
Javasript
<script language="javascript" type="text/javascript">
function onGetForecast() {
var zip = document.getElementById("zipCodeInput").value;
//alert(zip);
UltimateServices.GetForecast(zip, onGetForecastComplete, onGetForecastError, zip);
}
function onGetForecastComplete(result, userData) {
document.getElementById("resultsDiv").innerHTML = "Weather for " + userData + " is going to be " + result;
}
function onGetForecastError(err) {
alert("There was a error " + err.get_message());
}
</script>
WeatherService.cs file(codebehind)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
[ServiceContract(Namespace = "UltimateServices")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WeatherService
{
private static Random _rand = new Random();
[OperationContract]
public string GetForecast(string zipcode)
{
string forecast = "";
switch(_rand.Next(3))
{
case 0:
forecast = "Sunny and Warm";
break;
case 1:
forecast = "Chilly and overcast";
break;
case 2:
forecast = "Hot and humid";
break;
}
return forecast;
}
// Add more operations here and mark them with [OperationContract]
}
web.config file
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WeatherServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WeatherService">
<endpoint address="" behaviorConfiguration="WeatherServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WeatherService" />
</service>
</services>
</system.serviceModel>
here i call simple hello world from WCF using javascript
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;`
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public string helloworld(string name)
{
name = "Hello " + name;
return name;
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="DefaultBehavior">
<endpoint address="" binding="webHttpBinding" contract="IService" name="RunningBarbus.Services.RunningBarbusService" behaviorConfiguration="AjaxBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding crossDomainScriptAccessEnabled="true">
<security mode="None"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<!--<enableWebScript/>-->
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="false" />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true" name="">
</standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="access-control-allow-headers" value="content-type, Accept" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
javascript code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="jsonp.aspx.cs" Inherits="jsonp" %>
<!DOCTYPE html >
<html>
<head runat="server">
<title></title>
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var name="";
var Type;
var Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?name=world";
var Data;
var ContentType;
var DataType;
var ProcessData;
var method;
//Generic function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
// data: name, //Data sent to server
contentType: ContentType, // content type sent to server
//data: '[{"name":"' + name + '"}]',
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function (msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function ServiceFailed(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
function ServiceSucceeded(result) {
debugger;
if (DataType == "jsonp") {
alert(result);
resultObject = result.helloworld;
var string = result.name ;
alert(string);
}
}
function helloworld() {
debugger;
var uesrid = "";
Type = "GET";
// Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?'"+uesrid+'"';
Url = Url;
DataType = "jsonp"; ProcessData = false;
method = "helloworld";
CallService();
}
$(document).ready(
function () {
helloworld();
}
);
enter code here
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
You seem to lack the ScriptService/ScriptMethod attributes on your service/service methods.
I have setup a WCF service that returns json format data with my configuration file setup as follows:
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingJsonP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="webHttpBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="webHttpBehavior" name="Services.Service1">
<endpoint address="mex"
binding="webHttpBinding" bindingConfiguration="webHttpBindingJsonP"
contract="Services.IService1" behaviorConfiguration="webHttpBehavior"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
My service WebInvoke function:
<OperationContract()>
<WebInvoke(Method:="GET", BodyStyle:=WebMessageBodyStyle.WrappedRequest, Responseformat:=WebMessageFormat.Json)>
Function RetrieveData(ByVal screenName As String) As Stream
And Finally my dojo based website's function to call the webservice:
<script type="text/javascript">
dojo.ready(function () {
dojo.io.script.get({ url:
"http://xxx.xxx.x.xxx/Services/Service/Service1.svc/GetData?item=Tweet",
callbackParamName: "callback",
content: { username: "me", password: "you" }
}).then(function (data){
return data.results;
})
});
</script>
The problem is that I cannot get the data to flow through to the dojo application. First I get the error callback undefined. Now I am not sure if I am clear on this callback thing: is it the name of the function in the dojo application as I have above but the function is not named or is it the name of the function the returns the json response in the web service which by the way is installed on a different domain.
this is what I do with .NET:
My service:
[OperationContract]
[WebGet(UriTemplate = "/GetMyStuff", ResponseFormat = WebMessageFormat.Json)]
public String GetMyStuff()
{
var myStuff = getFromService("foo");
return new { label = "name", identifier = "Id", items = myStuff.Select(w => new { Id = w.Id, name = w.Description }) }.ToJSON();
}
I use this ToJSON() helper function declared as this:
public static class LinqUtils
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
}
In web.config:
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="false">
<serviceActivations>
<add relativeAddress="Services/StuffServiceJson.svc" service="MyStuff.MyStuffService" /> <!-- This is an actual URL mapping to your service endpoint -->
</serviceActivations>
</serviceHostingEnvironment>
<!-- other stuff -->
<services>
<service name="MyStuff.MyStuffService">
<endpoint binding="webHttpBinding" contract="MyStuff.MyStuffService" address="" behaviorConfiguration="webHttp"/> <!-- This is a service endpoint to your implementation class mapping -->
</service>
</services>
</system.serviceModel>
In Dojo:
require(["dojo/_base/xhr"], function(xhr) {
xhr.get({
url: "/Services/StuffServiceJson.svc/GetMyStuff",
handleAs: "json",
preventCache: true
}).then(function (data) {
//Do something with DATA
}, function (error) {
//Do something with error OMG
});
});
If you get a problem with the data being returned as string anyway (happens in .NET sometimes) then you're gonna have to take your data and do
require(["dojo/json"], function(json){
json.parse(data)
});
Luck,