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
Related
I need to upload files and some other data, for which I used bellow code
HTML:
<intut type='file' id='file1'>
<intut type='file' id='file2'>
javascript:
var data = new FormData(),
categories = ['node.js','redis'],
roles = ['admin','HR'];
data.Append ($('#file1').Files[0].name, $('#file1').Files[0]);
data.Append ($('#file2').Files[0].name, $('#file2').Files[0]);
data.Append ('category', 'categories');
data.Append ('role', 'roles');
$.ajax({
url: baseaddress + 'DocRepo/GetAdminUploadData',
type: 'Post',
data: data,
cache: false,
dataType: 'json',
async: false,
contentType: false,
processData: false,
success: function (data) {
},
error: function (data) {
}
});
From here I have an action method in my MVC Controller (not webapi) GetAdminUploadData where I need to collect all data(files, category and roles) how can do it.
Assuming that you are only looking for how to get the non-file items (as the title says ... although is not mentioned in the body of the question) and that the server code is C# (as your note from 3-feb-15 hints) I'd say this question is a duplicate of and answered by: How can retrieve string formData js in c#.
Namely: HttpContext.Current.Request.Form["KEY"]
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.
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.
var req = $.ajax({
type: 'GET',
cache: false,
url: 'loc.aspx?count=' + str,
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
data:'{}',
success: function (data) {
alert(data.responseText);
}
});
req.fail(function (data) {
TINY.box.show({ html: 'Server Error. Try again: ' + data.responseText, animate: false, close: false, boxid: 'error', top: 100 });
});
the above code used to work right in jsp, now i am trying to use in asp.net c#, any way I am getting correct data in error block which i want it in success block. Even data.d is not helping,
If i write something like alert(data) i am getting the complete html, I need just the response text, When i use like this data.responseText, I am getting undefined. Someone help pls.
Thanks
Code below should work fine. I've added some comments where you are doing a mistake
var req = $.ajax({
type: 'GET',
cache: false,
url: 'loc.aspx?count=' + str,
dataType: 'html',// as you return a simple html dataType:json will throw an error as jquery will not be able to parse received string
contentType: "application/json; charset=utf-8",
async: false,
data:'{}',
success: function (data) {
alert(data);// data is not an XHR object. it is a processed response. In your case - simple string with HTML which, of course, has no method responseText
}
});
req.fail(function (data) {
TINY.box.show({ html: 'Server Error. Try again: ' + data.responseText, animate: false, close: false, boxid: 'error', top: 100 });
});
In .fail function you have data.responseText because in this case XHR object is passed as a first parameter (See this). At the same time, first parameter of success callback is a clean data received with request. If without details, you can think that data == xhr.responseText in success callback. See success property description in this section
upd
As appeared, problem is not only with JS. I guess you have a simple .aspx page which is called with ajax. There are two solutions:
1) Use webservice instead. It will be better because it does not go through complete page load cycle and should be executed faster. And it will not produce unused HTML
2) aspx page will output some HTML by default. Before you return a response for ajax request, you should clear response (so HTML which is already generated will not be sent to a server), write your response and immediately end it:
Response.Clear();
Response.Write("hello");
Response.End();
This way you should receive only hello in success.