|
HI,
I'm trying to get a WCF service to a JSON for Jquery Ajax, but the method is not even to be initiated now returns the error Bad Request.
Below is the Java Script code calling the service, Service Interface, Class of Service, the service Web.config, Global.asax service.
Detail if I access the GetData method for $.getJSON works, but at $.Ajax not.
Already with the AddStudant method does not work somehow.
Could anyone help telling me what's wrong?
JavaScript
$("#bt").click(function () {
var url = "http://localhost:8318/Service1.svc/AddStudant";
var data = { "ID": 1, "Name": "Ericsson Alves" };
var jdata = {};
jdata.student = data;
callAjax(url, 'json', 'POST',
function (result) {
alert(result);
},
JSON.stringify(jdata)
);
});
function callAjax(ajaxUrl, ajaxDataType, ajaxType, funcSucess, dataValues) {
$.ajax({
url: ajaxUrl,
dataType: ajaxDataType,
type: ajaxType,
data: dataValues,
processdata: true,
contentType: "application/json;charset-uf8"
})
.done(function (data) {
funcSucess(data);
})
.always(function (data) {
}).fail(function (xhr, status, errorThrown) {
alert(xhr.responseText);
});
}
Interface
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
Student GetData(int id);
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
Student AddStudant(Student student);
}
[DataContract]
public class Student
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
}
Service Class
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
[WebInvoke(Method = "GET",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
public Student GetData(int id)
{
return new Student() { ID = id, Name ="Ericsson Alves" };
}
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
public Student AddStudant(Student student)
{
return new Student() { ID = student.ID , Name ="Ericsson Alves" };
}
}
Web.config Service
="1.0"
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebHttpBdg" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="BehaviorDefault">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AJAXWCFServiceAspNetAjaxBehavior">
<webHttp defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="TestWCFJsonAjax.Service.Service1" behaviorConfiguration="BehaviorDefault">
<endpoint address="" binding="webHttpBinding" bindingConfiguration="WebHttpBdg"
behaviorConfiguration="AJAXWCFServiceAspNetAjaxBehavior"
name="Service1" contract="TestWCFJsonAjax.Service.IService1" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" crossDomainScriptAccessEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Global.asax Service
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(Service1)));
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
}
Ericsson Alves
|
|
|
|
|
Hi,
How to load depends upon country datetime format?
how to load datetime format depends upon the country ?
example 1:
when i am select India ,it will display in textbox : 06/Feb/2014
india dd-MM-yyyy
example 2:
when i am select USA ,it will display in textbox : Feb/06/2014
USA mm/dd/yyyy
<html>
<head><title> date time</title> </head>
<script type ="text/javascript" src="jquery.js"></script>
<script type ="text/javascript" src="jquery.jdpicker.js"></script>
<body>
<link rel="stylesheet" href="jdpicker.css" type="text/css" media="screen" />
<div><div class="jdpicker_w"><input id="test1" type="text" name="test"></input>
</body>
<script>
$('#test1').jdPicker({
date_format:"dd MM YYYY",
});
$(document).ready(function(){
$('#your_input').jdPicker();
});
$(document).ready(function(){
$('#your_input').jdPicker({
start_of_week:2,
show_week:1
});
});
Thanks,
Karthikeyan,Bangalore
|
|
|
|
|
in the old days we used to call this 'locale' based programming - I believe the correct term these days is 'culture' - I'd do a search on 'javascript culture datetime' or terms like that, and see what it came back with - Im guesing javascript is locale/culture sensitive, you just need the correct library(ies)
'g'
|
|
|
|
|
Try the Globalize[^] library.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I have a code of piece ie:
m_sHTML = ""
m_sHTML = m_sHTML & "var x = (screen.availWidth - 12 - 375) / 2;"
m_sHTML = m_sHTML & "var y = (screen.availHeight - 48 - 200) / 2;"
m_sHTML = m_sHTML & "showModalDialog('xmHarmony.asp?WCI=changePassword','_blank',"
m_sHTML = m_sHTML & "'resizable ;status ;scrollbars=0;help ;unadorned:1;dialogWidth:375px;"
m_sHTML = m_sHTML & "dialogHeight:200px;dialogLeft=' + x + 'px;dialogTop=' + y + 'px;');"
m_sHTML = m_sHTML & ""
Response.Write (m_sHTML)
and output on ie10:
<html><head><script language='javascript'>var x = (screen.availWidth - 12 - 375) / 2;var y = (screen.availHeight - 48 - 200) / 2;showModalDialog('xmHarmony.asp?WCI=changePassword','_blank','resizable ;status ;scrollbars=0;help ;unadorned:1;dialogWidth:375px;dialogHeight:200px;dialogLeft=' + x + 'px;dialogTop=' + y + 'px;');<
this is popup syntax error due not closing properly but in main code closed properly .Please suggest..
|
|
|
|
|
Given the file extension, I'm guessing this is "classic" ASP? (Which was replaced 12 years ago, and really shouldn't still be being used.)
I seem to recall ASP having problems with <script> tags in strings. Try breaking the strings up:
m_sHTML = "<html><head><scr" & "ipt language=""javascript"">"
...
m_sHTML = m_sHTML & "</scr" & "ipt></head></html>"
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi all, I have a web app that has a display box and button UIs for typing numbers (0 through 9) into the display box. There is one button that when clicked generates multiple input fields.
My problem is that I can enter numbers into the first input field by clicking the numbered buttons and by typing numbers using the keyboard. Numbers can only be entered into other input fields using the keyboard. Any attempt to use the numbered buttons to enter numbers into other input fields will cause the focus to return back to the first input field.
Below are my markups and jquery
<body>
<div id="page">
<div id="myOutputs">
</div>
<script type="text/javascript">
$(document).ready(function () {
if ($('#box1').click())
{
$(".BTN").click(function () {
if ($.isNumeric($(this).html())){
$("#box1").val($("#box1").val() + $(this).html());
}});
}
else
if ($('#box2').click())
{
$(".BTN").click(function () {
if ($.isNumeric($(this).html())) {
$("#box2").val($("#box2").val() + $(this).html());
}
});
}
else
if ($('#box3').click())
{
$(".BTN").click(function () {
if ($.isNumeric($(this).html())) {
$("#box3").val($("#box3").val() + $(this).html());
}});
}
$("#functs").click(function () {
document.getElementById("myOutputs").innerHTML =
"<table id='data-table'>"
+ "<tr>"
+ "<td><input type='text' id='box1'/><td></tr>"
+ "<tr>"
+ "<td><input type='text' id='box2'/><td></tr>"
+ "<tr>"
+ "<td ><input type='text' id='box3'/><td></tr>"
+ "</table>";
document.getElementById('box1').tabIndex = "1";
document.getElementById('box2').tabIndex = "2";
document.getElementById('box3').tabIndex = "3";
});
}
Please explain why the code above is giving me the problems I've stated, thanks in advance.
modified 4-Feb-14 8:09am.
|
|
|
|
|
jQuery's .click method[^] has two forms; one to attach a handler to the click event of the matched elements, and one to trigger the click event. Your code is calling the second version.
Since the method returns the original jQuery wrapper object, which in Javascript terms is not "false-y", the code within the first if block executes.
Try something like this instead:
$(function() {
var currentBox = null;
$(document).on("focus", "#box1, #box2, #box3", function(){ currentBox = $(this); });
$(document).on("click", ".btn", function() {
if (currentBox) {
var value = $(this).html();
if ($.isNumeric(value)) {
currentBox.val(currentBox.val() + value);
}
}
});
});
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi, thanks for replying. Your code works like a charm.
|
|
|
|
|
Hello friends ,
i want to do a project java script . In which i want to compare algebraic expressions,
as if i give someone a question:
"A bike rental company charges initial deposit 100rs and 50 Rs/day . ravi paid 500 rs. then write an equation for to find no. of days x."
ANSWER will be 50x+100 = 500.
but answer can be written in may ways.
like :
100 + 50x = 500
500 -100 = 50x
there may be equations in two or more variables and polynomial of two or more degrees.
please help me to get source code if available,, or guide me in how to achieve that , what the things are needed.
|
|
|
|
|
|
Good Evening all
i am trying to post data coming from a form to the server and return a string , when i test this service works nicely. Its a Rest web api. now iam consuming it in Javascript Ajax like this
<script type="text/javascript">
function ProcessRegistration() {
jQuery.support.cors = true;
$.getJSON("http://www.mydomain.mymaindomain.com/api/Registration/Create", function (data) {
alert(data);
});
} </script>
When i run this and i get an Error
Failed to load resource: the server responded with a status of 405 (Method Not Allowed) http://www.mydomain.mymaindomain.com/api/Registration/Create
i have added the headers in IIS
"Access-Control-Allow-Origin" "*"
in my web config of the service i have added
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<...........
i have done all suggested by my research but i still get that error, try to restart the server but still the same.
Vuyiswa Maseko,
Spoted in Daniweb-- Sorry to rant. I hate websites. They are just wierd. They don't behave like normal code.
C#/VB.NET/ASP.NET/SQL7/2000/2005/2008
http://www.vuyiswamaseko.com
vuyiswa[at]dotnetfunda.com
http://www.Dotnetfunda.com
|
|
|
|
|
How did you declared Create method on the server?
I'm not questioning your powers of observation; I'm merely remarking upon the paradox of asking a masked man who he is. (V)
|
|
|
|
|
Did you get any response? I am in the same boat, it returns to the same error. Please help
|
|
|
|
|
|
Good Day
i have a web api that i want to call on the client side and return its contents, so it s a post and i return some string. Now i have a form that will have the data to be posted as depicted below
<form name="registrationForm" method="post">
and there are other controls within the form and i have a button that triggers the post as depicted below
< <input title="Register" onclick="ProcessRegistration();" style="width: 100px; height: 100px; align-self: center" type="submit" name="submit_fourth" id="submit1" value="register" />
onCick i call a function from the client side, the definition of the function is
function ProcessRegistration()
{
$.getJSON("http://www.mydomain.maindomain.com/api/Registration/Create", function (data) {
alert(data);
});
}
now when i click the button to fire the service i get the following error in the console
XMLHttpRequest cannot load http:
Does anyone know how to solve this ?
Thanks
Vuyiswa Maseko,
Spoted in Daniweb-- Sorry to rant. I hate websites. They are just wierd. They don't behave like normal code.
C#/VB.NET/ASP.NET/SQL7/2000/2005/2008
http://www.vuyiswamaseko.com
vuyiswa[at]dotnetfunda.com
http://www.Dotnetfunda.com
|
|
|
|
|
The problem is that the client and the server are on different domains (mydomain.maindomain and localhost). XHR will deny such call except you put an 'Access-Control-Allow-Origin' header on the server...
See here:
https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS[^]
I'm not questioning your powers of observation; I'm merely remarking upon the paradox of asking a masked man who he is. (V)
|
|
|
|
|
What is the web server? I had this same problem on a Tomcat server. I had to create a "filter" and "filter map" to resolve this.
|
|
|
|
|
hi thanks for your reply
i am using IIS , i was able to resolve the issue , but i had a to change my code a but to do this. my service is a Rest Web Api Service. So i was returning a String , i changed and returned an integer. So my Js code looks like this
$.ajax({
url: 'http://www.mysubdomain.mymaindomain.com/api/Registration/Create',
type: 'POST',
data: JSON.stringify(RegistrationModel),
contentType: "application/json;charset=utf-8",
success: function (data, textStatus, request) {
alert(data);
if (data != 0) {
alert("Your Reference number is ANP00" + data + " Keep it safe for Sure use");
ProcessPayment();
}
else {
alert("Already Registered,please renew");
}
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
I hope this helps someone in the future.
Thanks
Vuyiswa Maseko,
Spoted in Daniweb-- Sorry to rant. I hate websites. They are just wierd. They don't behave like normal code.
C#/VB.NET/ASP.NET/SQL7/2000/2005/2008
http://www.vuyiswamaseko.com
vuyiswa[at]dotnetfunda.com
http://www.Dotnetfunda.com
|
|
|
|
|
|
Greetings and Salutations!
I'm not sure if this is the right group for this, but if not, please let me know where I should post my questions.
I'm a novice to the world of jQuery and I've run into a snag (and can use some help). When I include the following line in my HTML file, the element doe not slide down as expected:
<script>
$(document).ready(function(){
$("#ContentHeader").slideDown(4000);
});
</script>
When I load the page the element appears without sliding down. I'm self taught using CodeAcademy and a text titled: "JavaScript & jQuery: The Missing Manual". Do I have the syntax correct?
Here is the full code I'm using:
<!DOCTYPE html>
<html lang="en">
<head>
<link type="text/css" rel="stylesheet" href="JQSwaggerStyle.css"/>
<script>
$(document).ready(function(){
$("#ContentHeader").slideDown(4000);
});
</script>
</head>
<body>
<div id="ContentHeader">
<h1>Andre Mitchell Stevens Swagger</h1>
<h2>Ain't it cool???</h2>
</div>
</body>
</html>
=======================
Every experience in life is a lesson to be learned
A. Stevens
B.S., Computer Science
|
|
|
|
|
You haven't posted your CSS, but the first thing I would check is that you have display:none; set for your #ContentHeader element.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard,
Thanks for your feedback. Unfortunately that did not work. If I include "display: none" (without the quotes) the element doesn't appear at all (and I also tried using "slow" as the parameter, rather than "4000").
I also tried:
$("#ContentHeader").hide().slideDown("slow");
but that didn't work either...
Here is my CSS (so far):
h1, h2{
color: #FF8000;
text-align:center;
}
#ContentHeader{
background-color: #000040;
border-color: #FF8000;
border-style:groove;
border-radius: 5pt;
border-width: 5pt;
}
=======================
Every experience in life is a lesson to be learned
A. Stevens
B.S., Computer Science
|
|
|
|
|
You definitely need the display:none; . As Graham mentioned, you also need a <script> tag to include jQuery. If you don't have a local copy, you can use a CDN - for example:
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
Here's a working example to play with: http://jsfiddle.net/Y5P7N/[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
If that is your complete page, then you haven't included the script tag to load jQuery itself. It should look something like this:
<script src="jquery.js"></script>
The actual src= filename and path may be different.
|
|
|
|
|