ASP.NET receive and respond to AJAX request - javascript

So I'm trying to setup ajax-exchange between a JavaScript frontend and ASP.NET backend. I've stumbled upon this example from w3schools:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
However, it's unclear to me how to handle this request on server side. What should my demo_get2.asp look like to process this request?

In Asp.NET, you can do this by clearing all the headers and response built so far by the framework then adding your custom data and header and flushing out the response without any other additional framework methods to be called (like, prerender, render methods) as below.
protected void Page_Load(object sender, EventArgs e)
{
// Add logic here to populate any data to send
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "text/plain"); // This can be your data type
Response.Write("This is plain text"); // This can be your data
Response.Flush();
Response.End();
}

Related

How to send POST request from browser? [duplicate]

This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
CORS Java server side implementation
(2 answers)
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed last year.
I'm trying to make a server in java that can handle requests sent from the browser. My problem is that I can't get the browser to actually send the request, all it sends is an OPTIONS request. Here's the error in the browser:
It isn't an actual website that I'm using, it's just an html page that would be opened by the java application. Here's the html:
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="sendRequest()">Click Me!</button>
<script>
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://172.26.48.1:9000/test", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({
"time": 16400
}));
}
</script>
</body>
</html>
And here's the java server that listens for the requests:
public class ServerTest
{
public static void main(String[] args) throws Exception
{
HttpServer server = HttpServer.create(new InetSocketAddress(9000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null);
server.start();
}
static class MyHandler implements HttpHandler
{
public void handle(HttpExchange exchange) throws IOException
{
System.out.println("Handling request: " + exchange.getRequestMethod());
if (exchange.getRequestMethod().equalsIgnoreCase("POST") ||
exchange.getRequestMethod().equalsIgnoreCase("OPTIONS"))
{
try
{
InputStream is = exchange.getRequestBody();
StringBuilder sb = new StringBuilder();
for (int ch; (ch = is.read()) != -1;)
sb.append((char) ch);
System.out.println(sb.toString());
String response = "OK";
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
exchange.close();
} catch (NumberFormatException e)
{
e.printStackTrace();
}
}
}
}
}
The server works fine, but it only receives the OPTIONS request. How can I make the html page send the actual POST request?
function sendRequest() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://172.26.48.1:9000/test", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = this.responseText;
}
};
xhttp..send(JSON.stringify({
"time": 16400
}));
}

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.

XMLHttpRequest - Hitting serverside aspx method - 505 Internal Server Error

I have coded an AJAX GET request using a XMLHttpRequest object. My problem is that the request is never hitting the server side code. I had a look at many forums and at stackoverflow and I dont really know what I am missing.
My JS code
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "login.aspx/GetData", true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(null);
}
Server side code - login.aspx
[WebMethod]
public static string GetData()
{
return "break here";
}
Looking at the Network tab in developer tools, I see that it cannot find the method as the error code is 505 (Internal Server Error)
Can this work within an aspx page? maybe only wrks in a asmx service?
Is there anything in the code that I have not done or is wrong?
Thanks

Consuming POST method of WCF REST service in Javascript or XmlHttpRequest

I am trying to access a WCF REST service with GET Method. The problem with this is, my parameter at times could be very long (more characters greater than maximum characters of URL String), So I am thinking to implement the same functionality with POST.
Note: I am consuming the service through JavaScript (I don't want to use JQuery - Since I am already using using Sencha (Sencha doesn't provide any POST method)) XmlHttpRequest.
function GetData() {
// alert("hello");
var xmlhttp = new XMLHttpRequest();
var url = "http://lclhost.com/WcfWebService.svc/doworks";
// alert("hello1");
xmlhttp.open("POST", url, true);
/// alert("hello2");
var params = "name=Jack";
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Status:"+xmlhttp.status+"State"+xmlhttp.readyState);
}
}
xmlhttp.onerror = function (e) {
//alert error
alert('error');
}
xmlhttp.send(params);
}
and my service is
[OperationContract]
[WebInvoke(Method="POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "doworks")]
string DoWorks(string name);
While consuming the javascript function through asp.Net web application, I am getting an alert of Status:0State4. I am not sure what is the problem. Can you guys help me how to consume this Service in POST through XMLHttpRequest/Javascript?

Sending data from javascript to php file

I have this function that gets text from a php file on the server and plonks it into an HTML page.
What changes do I need to make to it to SEND data (just a couple of javascript variables) to the php file rather than read from it ? Hoping not many !!
function process() {
if (xmlHttp) // the object is not void
{
try {
xmlHttp.open("GET", "testAJAX.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch (e) {
alert(e.toString());
}
}
}
Take a look at what all headers you can make use of. In your case, you would want to use POST instead of GET
xmlHttp.open("POST", "testAJAX.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//or JSON if needed
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(data);
You are probably better of using POST to send data it has less limitations. e.g:
var data = {
user: 'Joe',
age: 12
};
var httpReq = new XMLHttpRequest();
// true means async - you want this.
httpReq.open('POST', 'testAJAX.php', true);
// json is just a nice way of passing data between server and client
xmlhttpReq.setRequestHeader('Content-type', 'application/json');
// When the http state changes check if it was successful (http 200 OK and
// readyState is 4 which means complete and console out the php script response.
httpReq.onreadystatechange = function () {
if (httpReq.readyState != 4 || httpReq.status != 200) return;
console.log(httpReq.responseText);
};
httpReq.send(JSON.stringify(data));
And read it:
$name = json_decode($_POST['name']);
$age = json_decode($_POST['age']);
If it's just a couple of variables, you can pop them into the query string - although you'll want to make sure their values won't break your PHP script or open a security hole (for example, don't interpret user input as a SQL string). For more complicated data structures, use POST as others have suggested.
function process(var1value, var2value) {
if(xmlHttp) {
try {
xmlHttp.open("GET", "testAJAX.php?var1="+var1value+"&var2="+var2value, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch(e) {
alert(e.toString());
}
}
}

Categories