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(),
Related
I have some HTML content and need to pass it to the back end via FormData.append. When I try to pass it like HTML contents it shows me Internal Server 500 error. When I pass just text then it successfully hit to the backend.
Code
var _description = "<p><b>Test Description</b></p>";
var formData = new FormData();
formData.append("Description", _description)
Then Send it to the backend via AJAX Call,
$.ajax({
url: $("#addNewsDetails").val(),
// cache: false,
type: "POST",
data: formData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
mimeType: 'multipart/form-data',
processData: false,
contentType: false,
success: function (status) {
//Success
}
});
The server is probably configured to not accept html. You could maybe try to change that setting, or alternatively you could encode the html before the ajax call. Then on the server you would need to decode it.
How to encode html in javascript: Encode html entities in javascript
How to decode html in C#: https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.htmldecode?view=netcore-3.1
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.
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.
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.
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"
};
}