request.form is empty when posting to aspx page - javascript

I want to POST some data to an aspx page by javascript.
I send POST-httprequest to my aspx page and receive the request in my aspx page.
But the problem is that there is no parameter in my request. In other words my request.form is empty!
Here is my javascriptcode:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var http = new XMLHttpRequest();
var url = "https://myserver/1.aspx";
var params = "param1=something&param2=somethingelse";
http.open("POST", url, false);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.send(params);
And here is my aspx page:
<%
protected void Page_Load(object sender, EventArgs e)
{
var first = Request.Form["param1"];
var second = Request.Form["param2"];
var tot = first + second;
}
%>
This method work fine with http-GET-request!
Have any idea what the problem is?
Answer!:
The problem was not related to server and request handling in server!
Actually the problem was in var url = "https://myserver/1.aspx";
If you put ip there, the client will not send data, but it does not return error too!

Try this :
http.send(JSON.stringify({ "param1": "something", "param2": "something" }));

Related

How to get responsetext from a Page with Post method using XMLHttpRequest in asp.net?

I have a web page which sends a video file/blob to another web page in the using FormData using POST method and XMLHttpRequest. I want to return the response as string from the Posted URL in calling function. i.e after successfull upload file i want to return string to the caller.
index.aspx:
function SendFile(blob)
{
var file = new File([blob], "testfile123.webm");
var oData = new FormData();
oData.append("file", file,"testfile.webm");
var oReq = new XMLHttpRequest();
oReq.open("POST", "upload.aspx", true);
oReq.onload = function (oEvent)
{
if (oReq.status == 200)
{
alert("Uploaded"+oReq.responseText);
}
else {
alert("Error");
}
};
oReq.send(oData);
}
Upload.aspx:
protected void Page_Load(object sender, EventArgs e)
{
string folderPath = GetUploadFolderPath();
string filename = DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss") + ".webm";
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile postedFile = fileCollection[i];
var filePath = folderPath + filename; //postedFile.FileName;
postedFile.SaveAs(filePath);
}
}
In above code the file is created at specified location all works fine.I know its not possible in Page_Load event. please suggest correct method to send responsetext/string after file upload.
Help Appreciated.
This is a scraped together example on how to target specific functions inside aspx with jquery.ajax using vb.net. Sadly I am not fluent in C#.
Note that if you are using an ancient version of .net (two or lower), you have to add System.Web.Extensions in your web.config to make it work. Depending on the IIS either as httpModules or as modules.
AJAX.aspx
<WebMethod(EnableSession:=True)> _
Public Shared Function abc(def As String) As Boolean
''REM: Do stuff
Return True
End Function
xhr call using jquery
$.ajax({
type: "POST",
url: "AJAX.aspx/abc",
data: "{'def':'test'}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(response){...},
error: function(jqXHR, textStatus, errorThrown){...}
});
Yet, I still recommend to use generic handlers, like also shown here. It is more clean, slim and offers more control on what you actually want to do. Also the System.Web.Extensions are not required.

Running process after getting files in controller using Request.Form.Files

I've got a problem in my ASP.net Core application. I use MVC. I send a file from js to controller using:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Test/Sing", true);
xhr.send(fd);
then I got it in controller action:
[HttpPost]
public IActionResult Sing()
{
var file = Request.Form.Files[0];
byte[] filedata = null;
using (var target = new MemoryStream())
{
file.CopyTo(target);
filedata = target.ToArray();
}
\\some filedata processing
return RedirectToAction("Question");
}
The filedata is something that I need to process and then redirect to another action. When I put a breakpoint at the end of using (MemoryStream) I can see that the filedata is filled with data I need but when I want to redirect to action nothing happens. It looks like a process with the xmlhttprequest is still running on the client side and waiting for response. Am I right? How to get the file, cut the process, perform some file processing and be able to redirect to another action?
You should manually handle the redirect using window.location.href in success callback function of ajax/XMLHttpRequest .
If using XMLHttpRequest ,you can add listener for load events ,the listener must be added before the send() function:
function reqListener () {
window.location.href = "url";
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
If using AJAX redirect in success callback function :
success: function (response) {
window.location.href = "url";
}
Controller :
return Json("ok");
//Or return the url
return Json(new { redirectToUrl = Url.Action("action", "contoller") });

How to get JSON data at codebehind after I've made a ajax by using xmlHttpRequest?

I want to transfer some json data to server by using JavaScript xmlHttpRequest.
For simplify, assume that I've got a json like {"name":"John","country":"English"}, then I'm going to POST it back to the server. I use Request["name"] to get the request data but always result in NullOrEmpty, which means I cannot get inside #1. Thus leading to that #2 shows the entire HTML Document.
Here's my code:
**JavaScript:**
function AjaxTest()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);//**#2.**
}
};
xhttp.open("POST", "WebForm.aspx", true);
xhttp.setRequestHeader("Content-type", "application/json;charset=UTF-8");
var json = '{"name":"John","country":"English"}';
xhttp.send(json);
}
**Codebehind:**
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
string name = Request["name"];
string country = Request["country"];
if(!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(country))
{
//**#1.** I cannot get here.
}
}
}
I do know that I've done something wrong, but how can I get the reques data? As a newbie to Ajax, any help will be greatly appreciated.
Thanks in advance.

Porting function from java (Android) to AngularJs

I'm trying to write an old native Android app with Ionic and I need help for the http request. I'm newbie in AngularJS (js too).
My Android code has a function like:
String address = "http://www.example.com";
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("param", sParam));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(responsegetEntity().getContent()));
StringBuilder sBuilder = new StringBuilder();
String sLine = "";
while ((sLine = rd.readLine()) != null) {
sBuilder.append(sLine).append("\n");
}
String sContent = sBuilder.toString();
(...parsing sContent...)
} catch (Exception e) {
//something
}
and if there are more then one page I call a function like
String address = "http://www.example.com/result.do?page="+ iPage;
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("param", sParam));
Cookie ck = client.getCookieStore().getCookies().get(0);
pairs.add(new BasicNameValuePair("param_ck", ck.getValue()));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
(..parsing..)
}
So, I read the html content of a webpage (I'm not the owner) and I do somethings with that.
I tried $http.post but I'm not sure if it's the same
.factory('Service', function($q,$http) {
return {
getResult: function(param) {
var q = $q.defer();
var address = "http://www.example.com";
var sParam = "param";
$http({
url: address,
method: "POST",
data: {
'param' : sParam
}
})
.then(function(response) {
(...)
q.resolve(position);
},
function(error) {
(...)
q.reject(error);
});
return q.promise;
}
};
});
PS: I get the
No 'Access-Control-Allow-Origin' header is present on the requested resource.
with that.
Can you help me?
I am not entirely sure why you don't get a similar error with your Android code, or even if you were supposed to, as I am not familiar with native Android itself. But the reason that you get this with Angular in Ionic is that the server requires to implement CORS to get rid of that.
From MDN:
A resource makes a cross-origin HTTP request when it requests a resource from a different domain than the one which the first resource itself serves. For example, an HTML page served from http://domain-a.com makes an src request for http://domain-b.com/image.jpg. Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains.

Sending data to a webpage with Post Fails

I am trying to send an array of guids as postdata using a javascript function. The recieving aspx page needs to process this data.
The javascript that calls the page is as following:
function(webadress, guidarray) {
var params = 'menubar=no,status=no,toolbar=no,resizable=no, scrollbars=no';
var win = document.createElement("form");
win.target = 'Map';
win.method = 'POST';
win.action = webadress;
var winInput = document.createElement('input');
winInput.type = 'text';
winInput.name = 'guidcollection';
winInput.value = guidarray;
win.appendChild(winInput);
win.setAttribute("target", "_blank");
window.open(webadress, '', params);
win.submit();
}
The aspx page attempts to read the post data as following:
protected void Page_Load(object sender, EventArgs e)
{
object PostGuids = HttpContext.Current.Request.Form["guidcollection"];
// Do something with PostGuids
}
Somehow it fails, and when i debug the aspx page I see that HttpContext is not defined. Using fiddler I can determine that the sessionId is not set. I see the message 'This request did not send any cookie data.' in the Cookies tab.
What can i do to receive the post data? One of the requirements for the website is that cookie data on the client is not allowed. Is it possible to receive Post data without a sessionId? or should i look for alternatives like ViewState? Using a query string won't work because the length of the data will exceed the 2048 character limit of a querystring.
I have managed to get this working with the following changes:
function(webadress, guidarray) {
var params = 'menubar=no,status=no,toolbar=no,resizable=no, scrollbars=no';
var win = document.createElement("form");
win.target = 'Map';
win.method = 'POST';
win.action = webadress;
var winInput = document.createElement('input');
winInput.type = 'text';
winInput.name = 'guidcollection';
winInput.value = guidarray;
win.appendChild(winInput);
document.body.appendChild(win);
window.open(webadress, 'Map', params);
win.submit();
}
and server side:
protected void Page_Load(object sender, EventArgs e)
{
if (this.Request.Form.HasKeys())
{
object PostGuids = this.Request.Form["guidcollection"];
// Do something with PostGuids
}
}
I still have no idea why the HttpContext remains undefined, but this way i can access the guid data correctly. If some one can explain that to me, i'll be glad to accept that as the answer.

Categories