Can't seem to figure this one out.
I have a web service defined as (c#,.net)
[WebMethod]
public string SubmitOrder(string sessionid, string lang,int invoiceno,string email,string emailcc)
{
//do stuff.
return stuff;
}
Which works fine, when I test it from the autogenerated test thingy in Vstudio.
But when I call it from jquery as
$j.ajax({
type: "POST",
url: "/wservice/baby.asmx/SubmitOrder",
data: "{'sessionid' : '"+sessionid+"',"+
"'lang': '"+usersettings.Currlang+"',"+
"'invoiceno': '"+invoicenr+"',"+
"'email':'"+$j(orderids.txtOIEMAIL).val()+"',"+
"'emailcc':'"+$j(orderids.txtOICC).val()+"'}",
contenttype: "application/json; charset=utf-8",
datatype: "json",
success: function (msg) {
submitordercallback(msg);
},
error: AjaxFailed
});
I get this fun error:
responseText: System.InvalidOperationException: Missing parameter: sessionid. at
System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection) at
System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request) at
System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at
System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
data evaluates to: {'sessionid' : 'f61f8da737c046fea5633e7ec1f706dd','lang': 'SE','invoiceno': '11867','email':'steve#jobs.com','emailcc':''}
Ok, fair enough, but this function from jquery communicates fine with another webservice.
Defined:
c#:
[WebMethod]
public string CheckoutClicked(string sessionid,string lang)
{
//*snip*
//jquery:
var divCheckoutClicked = function()
{
$j.ajax({
type: "POST",
url: "/wservice/baby.asmx/CheckoutClicked",
data: "{'sessionid': '"+sessionid+"','lang': '"+usersettings.Currlang+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
divCheckoutClickedCallback(msg);
},
error: AjaxFailed
});
}
data: {sessionid: sessionid,
lang: usersettings.Currlang,
invoiceno: invoicenr,
email: $j(orderids.txtOIEMAIL).val(),
emailcc: $j(orderids.txtOICC).val()
},
Refer to http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/
Short version is,
Be sure to set data as a string using this format
// RIGHT
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
url: 'WebService.asmx/Hello',
data: '{ FirstName: "Dave", LastName: "Ward" }'
});
it has to be double quotes inside the string.
You can simplify the JSON creation and make it less brittle by using JSON.stringify to convert a client-side object to JSON string. JSON.stringify is built into newer browsers as a native feature, and can be added to older browsers by including Douglas Crockford's json2.js.
Take a look at this post on using JSON and data transfer objects with ASMX ScriptServices for some examples. Its examples start in almost exactly the same predicament that you're currently in, so hopefully it will be helpful.
remove the single quotes;
data: "{sessionid : "+sessionid+","+
"lang: "+usersettings.Currlang+","+
"invoiceno: "+invoicenr+","+
"email:"+$j(orderids.txtOIEMAIL).val()+","+
"emailcc:"+$j(orderids.txtOICC).val()+"}",
contenttype: "application/json; charset=utf-8",
and move the curly brace outside the quotes
data should be more like data: {sessionid : sessionid, lang: usersettin...
the way you're sending it now, it's a string.. so your application is NOT getting the variable sessionID and it's value.
Thus, it's reporting an error. this error is not json, so responseText is throwing an error.
Related
contentType: "text/html; charset=utf-8",
url:"secret.aspx?plu="+$("#Text1").val()+"&gh="+$("#TextBox1").val()+"&sid="+$("#TextBox2").val(),
processData: false,
dataType: "html",
success: function(data)
is it the above syntax correct to send the data
recieved by the code below
string sid=Request.QueryString["sid"];
string id = Request.QueryString["plu"];
int ide =Convert.ToInt32(Request.QueryString["gh"]);
Response.write(sid);
Response.end();
or is there any other way to achieve the same
The only problem with that request is that it will break if you have any special characters in your input values.
A solution to that would be to pass a data object:
type:"GET",
url:"secret.aspx",
data: {
plu : $("#Text1").val(),
gh : $("#TextBox1").val(),
sid : $("#TextBox2").val()
},
dataType: "html",
This encodes special characters to avoid breaking the key/value format. Alternatively you could keep them in the url but wrap each in encodeURIComponent(), which would have the same effect.
You need to serialize your form data into the 'data' option of the ajax method. Also, specify the type of request as GET if you want to use the query string.
type: 'GET'
contentType: "text/html; charset=utf-8",
url:'secret.aspx',
processData: false,
dataType: "html",
data: $('#myForm').serialize(),
I have some problem with posting formData to server side action method. Because ajax call doesn't send files to server, I have to add file uploader data to formData manually like this
It is impossible to call a server method
[WebMethod]
public HttpPostedFileBase Name(HttpPostedFileBase file)
{
string ret = "test";
return file;
}
Errors on the client side no
I wrote jQuery function that need to post form data to server using ajax call.
this is my script:
data.append(self.idFileInput, file[f]);
$.ajax({
type: "POST",
url: "/AddContract.aspx/Name",
data: data,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
}
});
Any tips, link or code example would be useful.
Thank you in advance!
try to use contentType: 'application/json; charset=utf-8',
$.ajax({
type: "POST",
url: "AddContract.aspx/Name",
data: { field1: self.idFileInput, field2 : file[f]} ,
dataType: 'json',//Remove this line this line is causing issue.
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (data) {
}
});
In a previous answer I said something stupid about ASPX not supporting WebMethod calls, which they do.
Now a real answer:
In order to post a file you need to use the ajaxSubmit method. See this reference.
This is supposedly very easy but for some reason it has taken me about 2 hours and countless searches and nothing is working
I am trying to call a WebMethod from ajax, and it works quite well.
As soon as I try to change the c# function to accept parameters and send one from ajax everything fails
Code:
c#:
[WebMethod]
public static string GetBGsForSelectedCrop(string cropName)
{
return "asdasd";
}
jquery:
$().ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: "Wheat",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
});
I have tried datatype: "json", contentType: "application/json; charset=utf-8", and tried without both and datatype: "string" and datatype: "text", GET, data: "{'ABCD'}, data:{"cropName: Wheat"}, and data: json.Stringify("Wheat").
I get undefined for msg.d and sometimes HTTP error 500 if I take it too far.
What am I missing? It is just a simple task and should've been done in seconds..
As the guys in the comments says, you need to change your code for:
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: JSON.stringify({ cropName: "Wheat" }),
dataType:'text',
contentType: "application/json; charset=utf-8",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
Your error is the data is no good encoded, and you are missing the datatype.
What is the stringfy It Convert any value to JSON.
I don't get why $.ajax() function cannot reach my [WebMethod].
Here is the jQuery below:
$('.BasketUpdaterSubmit').click(function() {
$.ajax({
url: '/Ajax/AjaxCalls.aspx/UpdateAsyncBasket',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'name' : 'Ivan'}",
success: function(data) { alert(data); },
error: function(xhr) { alert("Damn!"); }
});
Here is the C# code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string UpdateAsyncBasket(string name)
{
// random stuff
return "Received : \t " + name;
}
When I place a breakpoint on the return statement I never seem to get there.
What am I doing wrong?
Based on the experience I've had with this stuff, I THINK the JS has to be put inside inside .NET's page load javascript function to access C# web methods.
function pageLoad(sender, eventArgs) { }
Try a GET instead of a POST. I have a few web methods that work fine using similar javascript, but have decorated the method with this instead of just [WebMethod]:
[WebMethod, ScriptMethod(UseHttpGet = true)]
And then make sure your ajax call specifies GET:
$('.BasketUpdaterSubmit').click(function() {
$.ajax({
url: '/Ajax/AjaxCalls.aspx/UpdateAsyncBasket',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'name' : 'Ivan'}",
success: function(data) { alert(data); },
error: function(xhr) { alert("Damn!"); }
});
Try this code,
$(document).on("click",".BasketUpdaterSubmit",function(){
$.ajax({
url: '/Ajax/AjaxCalls.aspx/UpdateAsyncBasket',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'name' : 'Ivan'}",
success: function(data) { alert(data); },
error: function(xhr) { alert("Damn!"); }
});
});
And the web.config you have to add following section inside the system.web section
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Above code should work(tested in my machine). My best suggestion for you is create a web service for this. so you can omit the page life cycle.
You can refer following sample to learn how to do it properly
http://tutorials.cmsnsoftware.com/2011/01/how-to-call-csharp-function-in-ajax.html
We figured out what's going on.
It seems that there is a default ajax setup function which was interfering with my jquery function and didn't proceed when testing. Most probable reason is improper parameter handling.
Sorry for the late response. Thank you all.
How can i send a JSON object to a webmethod using jQuery?
Please refer to this article by Dave Ward. It is a complete tutorial on doing this stuff. Also you will find there other great jquery/ASP.net stuff.
EDIT:- Dave is calling method without any arguments, you can replace empty data property with actual data you want to send:
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{'name':'tiger1','hobbies':['reading','music']}",//PUT DATA HERE
contentType: "application/json; charset=utf-8",
dataType: "json",
WebMethods expect a string containing JSON that will be parsed on the server-side, I use the JSON.stringify function to convert a parameters object to string, and send the data, I have a function like this:
jQuery.executePageMethod = function(location, methodName, methodArguments,
onSuccess, onFail) {
this.ajax({
type: "POST",
url: location + "/" + methodName,
data: JSON.stringify(methodArguments), // convert the arguments to string
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status) {
var jsonData = JSON.parse(data.d);
onSuccess(jsonData, status);
},
fail: onFail
});
};
I recommend you to include the json2.js parser in your pages, to have the JSON.stringify function cross-browser available.
Another library you can use is the jquery-json library. Once included:
var json = $.toJSON(your_object);
The most convenient solutions I've seen simplify this by using the open-source JSON2.js library to parse and 'stringify' complex object data.
These two excellent articles go into detail:
Using complex types to make calling services less… complex by Dave Ward.
JavaScript Arrays via JQuery Ajax to an Asp.Net WebMethod by Chris Brandsma.
The second article might be especially relevant for you, though it calls a web service method with the following signature ...
public void SendValues(List<string> list)
... it demonstrates how to use the JSON2.js library to render a List<string> in javascript (using jQuery, this example is taken directly from the second article):
var list = ["a", "b", "c", "d"];
var jsonText = JSON.stringify({ list: list });
// The 'list' is posted like this
$.ajax({
type: "POST",
url: "WebService1.asmx/SendValues",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() { alert("it worked"); },
failure: function() { alert("Uh oh"); }
});
Just use your webmethod URL in lieu of the web service's.
You'd need to post it using Ajax and accept the incoming string on the webmethod. Then you'd need to use the JavaScript deserializer to convert it into an object on the server side.
JSON.stringify does help, but:
it's not cross-browser
take a look here:
http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/#
For browser in-built functions - every browser will have its problems. If You use the above serialization You will need to:
remove newlines with regexp in strings
take care about " in strings
Sample code is here:
var dataString = JSON.stringify({
contractName: contractName,
contractNumber: contractNumber
});
$.ajax({
type: "POST",
url: "CreateQuote.aspx/GetCallHistory",
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.CallHistoryDescription);
OpenLightBox('divDelete');
}
});
[System.Web.Services.WebMethod]
public static object GetCallHistory(string contractName, string contractNumber)
{
return new
{
CallHistoryDescription = "Nalan"
};
}