When is a HTTP response code actually 200 OK? - httpresponse

In creating an API (and other things), many client-side examples look like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
...
So that got me thinking, what is actually OK?
Specifically, if the request produces a programmed error for something like bad data, the request has technically worked so is this "OK"? And then, what should the severity of the error be to return a 400 - bad login?

Related

Taking value from text-field and sending it with AJAX request Javascript

I am trying to sync both client-side and server-side scripts that the client intakes a value from the textbox and sends it to the server, upon which the server displays that input as a cookie.
Here is the code that I have so far
function loadCookie() {
//[1] make a new request object
var xhttp = new XMLHttpRequest();
//[2] set the request options
xhttp.open("GET", "index.html", true);
//[3] define what you will do when you ge a response (callback)
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("input_response").innerHTML = this.responseText;
}
};
//[4] finally send out the request
xhttp.send();
}
I have the and the button but I am having issue of the page re-loading itself instead of taking the value of the input and showing it as a cookie in the server. I'm suspecting it is having to do with the URL by the index.html

AJAX script failing to put parameter

I have created a php script that I know works. I try communication to it with the following ajax call:
var request = new XMLHttpRequest();
request.open("GET", "http://larsbak.dk/schedule/GET/schedule.php");
request.setRequestHeader("Content-type", "application/json");
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
data = JSON.parse(request.responseText);
}
request.send("id=201303560&interval=100000");
When i use the above script the server respons with error with error 104, which means that id parameter is not set. Why is this happening?
You are making a GET request, so you can't have a request body. Change that to "POST" or move the data to the query string.
You are claiming you are sending "application/json", which "id=201303560&interval=100000" is not. You are sending "application/www-x-form-urlencoded" data.
You forgot to end (}) your onreadystatechange handler

AJAX Request gets cancelled with AngularJS and Spring Security

We're running an external Grails server-application with the Spring Security plugin.
The front-end is running locally on AngularJS.
Whenever I try to login, the request is immediately canceled.. Remarkably AngularJS sends a GET request first with the OPTIONS method; this returns a 200 OK response just fine.
The actual POST request does never reach the server though... what could possibly cancel my request?
The following code:
$scope.login = function() {
$http.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
$scope.loggingIn = true;
// Setup Config
var data = {
j_username: $scope.user.email,
j_password: $scope.user.password
}
var config = {method: 'POST', url: serverUri+'/j_spring_security_check/', data: data};
// Dispatch HTTP Request
$http(config)
.success(function(data, status, headers, config) {
if (data.status) {
// successful login
User.isLogged = true;
User.username = data.username;
}
else {
User.isLogged = false;
User.username = '';
}
$scope.loggingIn = false;
console.log("NOICE!");
})
.error(function(data, status, headers, config) {
$scope.loggingIn = false;
User.isLogged = false;
User.username = '';
if (status == 0) {
// Request got cancelled
console.log("Request got cancelled.");
return;
}
});
}
This is what the canceled request looks like: http://i.stack.imgur.com/kiWnb.png
This is what the OPTIONS request looks like: http://i.stack.imgur.com/FAj96.png
Apparently Chrome does not handle 302 Moved temporarily status codes efficiently when queried by AngularJS in my situation. Firefox properly shows there is a response where Chrome just shows the request as canceled with no response information whatsoever.
This question is solved, but there is still a mystery as to WHY AngularJS does not work. See my question here:
AngularJS $http ajax does not follow Location header

How to access POST data sent from a browser to Rikulo Steam Server

I ask the browser to POST JSON data to the stream v0.5.5 server using ajax. In the server side, how can I receive the data from the ajax request?
My client:(Google Chrome)
void ajaxSendJSON() {
HttpRequest request = new HttpRequest(); // create a new XHR
// add an event handler that is called when the request finishes
request.onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print(request.responseText); // output the response from the server
}
});
// POST the data to the server
var url = "/news";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(mapTOJSON()); // perform the async POST
}
String mapTOJSON() {
print('mapping json...');
var obj = new Map();
obj['title'] = usrTitle.value == null ? "none" : usrTitle.value;
obj['description'] = usrDesc.value == null ? "none" : usrDesc.value;
obj['photo'] = usrPhoto.value == "none";
obj['time'] = usrTime==null ? "none" : usrTime.value;
obj['ip']= '191.23.3.1';
//obj["ip"] = usrTime==null? "none":usrTime;
print('sending json to server...');
return Json.stringify(obj); // convert map to String i.e. JSON
//return obj;
}
My server:
void serverInfo(HttpConnect connect) {
var request = connect.request;
var response = connect.response;
if(request.uri.path == '/news' && request.method == 'POST') {
response.addString('welcome from the server!');
response.addString('Content Length: ');
response.addString(request.contentLength.toString());
} else {
response.addString('Not found');
response.statusCode = HttpStatus.NOT_FOUND;
}
connect.close();
}
Again, I don't want the browser to ask for data from the server!
What am I doing is to asking the browser to submit the JSON data via ajax, and I just don't know how the server (Rikulo Stream v0.5.5) gets the "content" of data? All code is written in Google Dart Language M3. No Javascript!
POST is not supported well in Dart SDK, but Dart team planned to enhance it. Please stargaze it here: issue 2488.
On the other hand, since what you handle is JSON, you can listen to HttpRequest (I'm assuming the latest SDK) and convert List to String and then to JSON. Rikulo Commons provides a utility to simplify the job as follows:
import "package:rikulo_commons/io.dart";
IOUtil.readAsJson(request, onError: connect.error).then((jsonValue) {
//handle it here
});

How to XMLHttpRequest in Wordpress?

I'm trying to send a variable to the server, using XMLHttpRequest.
I tested it on local on a non-Wordpress file and it works.
But on production, on my Wordpress file, the onreadystatechange AJAX status doesn't get to 200.
Is there anything I need to be aware when XMLHttpRequesting in Wordpress?
<script>
params = "parameter=" + value;
request.open("POST", "../myfile.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
console.log('Request completed');
}
else console.log("Ajax error: No data received")
}
else console.log("Ajax error: " + request.statusText );
}
};
request.send( params );
// 'request' is 'XMLHttpRequest()' or 'ActiveXObject("Microsoft.XMLHTTP")'
// depending on browser
</script>
To create the code I followed the 2nd example of my O'Reilly book.
Any suggestion'll be much appreciated!
Thanks
Ultimately there is nothing wrong with this script.
I think it was due to the work frame I was using (Roots theme for Wordpress).
I change it for Handcrafted and I solved the problem.

Resources