error 400 bad request with AJAX form - javascript

JS:
function submitForm(){
var data = {
name: _("#name").value,
email: _("#email").value,
message: _("#message").value
}
var output = JSON.stringify(data);
var ajax = new XMLHttpRequest();
ajax.open( "POST", "/src/scripts/parser.php" );
ajax.setRequestHeader("Content-Type", "application/json'");
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
console.log('success')
} else {
console.log('fail')
}
}
ajax.send( output );
console.log(output)
}
When im trying submit form, i have error:
400 Bad Request
Your browser sent a request that this server could not understand.
Can somebody help me?
Thanks anyway :)

The key here is this statement: 'that this server could not understand'. This usually indicates that something is wrong on the server. But it could also be that your url is wrong. Either...
parser.php does not exist
parser.php exists in a different folder (other than 'src/scripts')
There is a url re-write module on the server that obfuscates the physical path of parser.php
parser.php returns a 400 error

Related

Received data through a POST Request always empty

I have server and a client the server uses node js the client send requests to the sever and the server should act accordingly.
However I came across a little bit of a confusing behavior and i want to know why its behaving like that!
The thing is when i send a json array or Object the received data by the server is always empty for some reason.
Here is the code of the request that raises the problem:
function Save()
{ // saves the whole global data by sending it the server in a save request
if( global_data.length > 0)
{
var url = "http://localhost:3000/save";
var request = new XMLHttpRequest();
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
console.log(this.responseText);
}
};
let object={ id: "101.jpg", RelativePath: "images/101.jpg", size: 61103 }; // this just an exemple of data
let data_json = JSON.stringify(object);
request.send(data_json);
}
else
{
console.log("Nothing to save");
}
}
And Here is the server code related to this request:
const server=http.createServer(onRequest)
server.listen(3000, function(){
console.log('server listening at http://localhost:3000');
})
function onRequest (request, response) {
/*function that handles the requests received by the server and
sends back the appropriate response*/
/*allowing Access-Control-Allow-Origin since the server is run on local host */
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Request-Method', '*');
response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
response.setHeader('Access-Control-Allow-Headers', '*');
console.log("a request received :" ,request.url);
let parsed_url = url.parse(request.url);
if(parsed_url.pathname == '/save')
{
console.log("Proceeding to save state : ...");
let received_data = '';
request.on('data', function(chunck) {
received_data += chunck;
console.log("another line of data received");
});
request.on('end', function() {
console.log(received_data); // why is this empty (my main problem)?
let jsondata = JSON.parse(received_data); // here raises the error since the received data is empty
console.log(jsondata);
response.writeHeader(200,{"content-Type":'text/plain'});
response.write("SAVED!");
response.end()
});
}
}
Just if anyone got the same problem: for me I couldn't solve it directly so I was forced to use query-string in order to parse the data instead of json.parse it seems the data received emptiness was related to the failure of the JSON parser somehow. so I installed it with npm install querystring and used const qs = require('querystring'); in order to invoque the parser by calling qs.parse(received_data.toString());.
Hope this helps anyone who got stuck in the same situation.

Login HttpRequest with credentials using c# (got working javascript code)

For the past 5 hours I've been trying to get JSON data from an API that requires login using .net C#.
Every combination I try results in "error 401 - unauthorized".
I have a working example in Javascript, maybe this would help.
function signin(){
username = $('#inputUsername').val();
pass = $('#inputPassword').val();
if(pass.length > 0 && username.length > 0){
//Build post request
$.post( source+"/login", {username: username, password:pass}, function( data, textStatus, jqxhr ) {
$("header div h4#header_username").html(username);
token = data.auth;
$('#main-content').show()
$('#form-signin').hide()
populateVehicles();
});
}
}
On c# I've tried many code combinations including:
NetworkCredential netCredential = new NetworkCredential("USERNAME", "PASSWORD");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = netCredential;
request.Method = "POST";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("USERNAME" + ":" + "PASSWORD"));
//request.PreAuthenticate = false;
//request.Proxy.Credentials = CredentialCache.DefaultCredentials;
//request.UseDefaultCredentials = true;
//string base64Credentials = GetEncodedCredentials();
//request.Headers.Add("Authorization", "Basic " + base64Credentials);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
Some of the code has "//" because I've tried various variations.
I'm clueless.
Thanks in advance!
Using doetnet core 2.1, here's a basic example. I checked jquery docs and I think your js example sends form encoded data. You can easily check that in your browsers developer tools > network tab.
Form Encoded
using (var client = new HttpClient())
{
var response = await client.PostAsync("https://myaddress.com/path", new FormUrlEncodedContent(new Dictionary<string, string>()
{
{ "username", "user" },
{ "password", "mypass" }
}));
if (response.StatusCode == HttpStatusCode.OK)
{
var responseString = await response.Content.ReadAsStringAsync();
// do something
}
}
"form url encoded" means, it will generate a request that looks like this:
say=Hi&to=Mom
with header Content-Type: application/x-www-form-urlencoded
s.a. https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
Json Content
using (var client = new HttpClient())
{
var response = await client.PostAsync("https://myaddress.com/path", new StringContent(JsonConvert.SerializeObject(new
{
username = "user",
password = "password"
}), Encoding.UTF8, "application/json"));
if (response.StatusCode == HttpStatusCode.OK)
{
var responseString = await response.Content.ReadAsStringAsync();
// do something
}
}
"json" means, it will generate a request, that looks like this
{ "say": "Hi", "to": "Mom" }
with header Content-Type: application/json
Note that HttpClient is thread safe and you should prefer a single instance if you do multiple requests.
If your're on dotnet core the following article will help you getting started with HttpClient: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.1
See https://stackoverflow.com/a/4015346/2085502 mentioned by #Archer to get an overview over different http client libs in c#.
To troubleshot if your backend working properly, check it by try sumbit the form with real usename and password and wrong email/password by clicking inside the . username and password must be inside the form too. Also in your form must be have action="" attribute with value of login url.
Try to set up, if login success some word. example, simply print 'success'
Then if failed, print another message. example 'failed', 'wrong password', 'email not exist' aor etc.
So after that. use this Javascript code.
function signin(){
var formData = new FormData();
formData.append('userame', document.getElementById('inputUsername').value);
formData.append('password', document.getElementById('inputPassword').value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.yoursite.com/login-url-here', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4){
var data = xhr.responseText;
if(data){
if(data == 'success'){
// yes your login page return success, do something below
document.getElementById('main-content').style.display = 'block';
document.getElementById('form-signin').style.display = 'none';
populateVehicles();
alert('login success')
} else {
alert('ops, failed to login, the page print this messages '+ data)
}
} else {
alert('ops your login page not print anything')
}
}
}
xhr.send(formData);
}

Cross Domain access to USPS API

I am trying to make a CORS request to USPS website with jquery, I have gotten it to work on my work pc, with internet explorer only for some reason. and I get a CORS error on the newer version of IE and also Firefox and Chrome.
In a question I wasn't allowed to comment on due to not having a rep, they suggested sending it to a server first then making the request instead of from the browser, Can somebody explain this to me? How can I host a server with javascript, I simply need to use this API to get tracking information and this stupid CORS restriction is a pain in my rear every time I try to do something like this.
Please help.
function sendTrackingRequest(x) {
var requestURL = "http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML="
var request = new XMLHttpRequest();
request.open( "GET", requestURL + trackNumberToBeTracked, true);
// various sanitizations should be employed on the backend when dealing with user input
request.responseType = "text/xml";
request.setRequestHeader( "Content-Type", "xml" );
request.addEventListener( "readystatechange", function() {
if ( request.readyState == 4 ) {
if ( request.status == 200 ) {
// process response
var trackingStatus = request.response
showResult(trackingStatus);
console.log(trackNumberToBeTracked);
} else {
alert("error")
}
}
}, false );
request.send();
}
});
Okay everyone.
Please bear with me I have made a huge beginner mistake and figured out what was wrong with Slakes help.
So in my code, I had a function with a similar name which was a .response not defined. I got this error after I listened to the first helper who said a contenttype was not necesarry for a Get request which he was right after further research.
After i removed all the bad functions which i was testing, I finally got my response to work. here is my code
$(document).ready(function() {
$('#trackButton').click(function() {
var enteredNumber = $('#trackingNumbers').value;
var trackNumberToBeTracked = '<TrackRequest USERID="648FOOTL0638"> <TrackID ID="9405510200839104436417"></TrackID></TrackRequest>'
sendTrackingRequest();
function sendTrackingRequest(x) {
var requestURL = "http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML="
var request = new XMLHttpRequest();
request.open( "GET", requestURL + trackNumberToBeTracked, true);
// various sanitizations should be employed on the backend when dealing with user input
request.addEventListener( "readystatechange", function() {
if ( request.readyState == 4 ) {
if ( request.status == 200 ) {
// process response
var trackingStatus = request.response
alert(trackingStatus);
console.log(trackNumberToBeTracked);
} else {
alert("error")
}
}
}, false );
request.send();
}
});
Here is the code that was below it, giving me the error after I took out set header type (which solved my CORS issue as POST requests are not allowed on the api)
function showResult(request) {
var xmlDoc = request.response.documentElement;
removeWhitespace(xmlDoc);
var outputResult = $("#BodyRows");
var rowData = xmlDoc.$("#Employee");
addTableRowsFromXmlDoc(rowData,outputResult);
};
});

access XMLHttpRequests send(data) in PHP backend

I have an XMLHttpRequest sending data to a PHP backend.
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send('query=messages'); // <-- i want to access this in php
i tried
print_r($_GET) and print_r($_REQUEST) but neither works.
anyone knows how to access this data?
You can only send data through the XMLHttpRequest.send()-method for POST-requests, not GET.
For GET-requests, you need to append the data to the url as query string.
url += "?query=message";
Then you can retrieve the data with PHP using:
$message = $_GET['query'];
More info: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Setting server response data to a variable to work with

Hey guys I am using a executePostHttpRequest function that looks exactly like the code posted below. Currently when I run the function I get a server response with the appropriate data but I am not sure how I can work with the response data? how do I store it in to a variable to work with?
Javascript executePostHttpRequest
function executePostHttpRequest(url, toSend, async) {
console.log("====== POST request content ======");
console.log(toSend);
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", url, async);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.setRequestHeader("Content-length", toSend.length);
xmlhttp.send(toSend);
console.log("====== Sent POST request ======");
}
Here is what I am doing to execute it. Using Javascript
var searchCriteria = JSON.stringify({
displayName : search_term
});
console.log("Search: "+searchCriteria) //Search: {"name":"John, Doe"}
var response = executePostHttpRequest("/web/search", searchCriteria, true);
console.log(response) //undefined
So currently the console.log for response shows undefined. But if I take a look at the network tab on Chrome Dev Tools and look at the /web/search call I see a JSON string that came back that looks something like this.
[{"id":"1","email":"john.doe#dm.com","name":"John, Doe"}]
I'd like to be able to display the data from this response to a HTML page by doing something like this.
$("#id").html(response.id);
$("#name").html(response.name);
$("#email").html(response.email);
I tried taking another route and using Jquery POST instead by doing something like this.
var searchCriteria = JSON.stringify({
displayName : search_term
});
console.log("Search: "+searchCriteria) //Search: {"name":"John, Doe"}
$.post("/web/search", {
sendValue : searchCriteria
}, function(data) {
$.each(data, function(i, d) {
console.log(d.name);
});
}, 'json').error(function() {
alert("There was an error searching users! Please contact administrator.");
});
But for some reason when this runs I get the "There was an error" with no response from the server.
Could someone assist me with this? Thank you for taking your time to read it.
Your executePostHttpRequest function doesn't do anything with the data it's receiving. You would have to add an event listener to the XMLHttpRequest to get it:
function getPostData(url, toSend, async, method) {
// Create new request
var xhr = new XMLHttpRequest()
// Set parameters
xhr.open('POST', url, async)
// Add event listener
xhr.onreadystatechange = function () {
// Check if finished
if (xhr.readyState == 4 && xhr.status == 200) {
// Do something with data
method(xhr.responseText);
}
}
}
I've added the method parameter for you to add a function as parameter.
Here's an example of what you were trying to do:
function displayStuff(jsonString) {
// Parse JSON string
var data = JSON.parse(jsonString)
// Loop over data
for (var i = 0; i < data.length; i++) {
// Get element
var element = data[i]
// Do something with its attributes
console.log(element.id)
console.log(element.name)
}
}
getPostData('/web/search', searchCriteria, true, displayStuff)

Categories