XMLHttpRequest sends b'' instead of json data - javascript

I'm trying to send json data from my web app to my python flask api, my server is receiving the POST rqeuest & is receiving data, the issue is that it's not receiving json data rather the string b''
This is the javascript code I got to send the json data to my api
function onSubmit() {
document.getElementById("orderbutton").disabled=true;
setTimeout('document.getElementById("orderbutton").disabled=false;',3000);
var request = new XMLHttpRequest();
var url = "http://127.0.0.1:5000/api/order";
request.open('POST', url, true)
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.onload = function() {
var response = JSON.parse(request.responseText)
console.log(response)
}
request.send(JSON.stringify({"id": document.getElementById("order").value.trim()}))
}
edit: it's not an issue with document.getElementById("order").value.trim() because when I console.log it, I get the input I put in my <input> field

Try editing your send() line to
request.send(JSON.stringify({id: document.getElementById("order").value.trim()}));
Change is from "id" to id

use .decode('utf-8'), Let me know the result.

Related

jQuery AJAX POST to PHP works, XMLHttpRequest doesn't

I'm currently refactoring some of my previous code to move away from jQuery's AJAX function towards XMLHttpRequest in vanilla JS. From my understanding, the following code blocks should be identical. However, while the jQuery version works, XMLHttpRequest doesn't. If successful, you should see an array returned by PHP in the network tab in dev tools.
jQuery
$("#submit").click(() => {
$.ajax({
type: "POST",
url: "http://arig.asuscomm.com/mn/PHP/submitNames.php",
data: {
first: "Hi!"
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="submit">
Submit
</button>
Vanilla JS
function send() {
var data = {
"first": "Hi!"
};
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://arig.asuscomm.com/mn/PHP/submitNames.php", true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.send(JSON.stringify(data))
}
<button id="submit" onclick="send()">
Submit
</button>
Note that my server is running locally, but I will try to keep it up until my question is answered. And, because my server doesn't have HTTPS quite yet, you might need to send the request from an HTTP source. Thanks!!!
Edit: I'm using code found here.
jQuery encodes data using the application/x-www-form-urlencoded data format, not JSON.
You can encode data in that format using the URLSearchParams object.
const data = {
"first": "Hi!"
};
const params = new URLSearchParams();
Object.entries(data).forEach(
([key, value]) => params.append(key, value)
);
const encoded_data = params.toString();
console.log(encoded_data);
Problem is with your server not the data itself as I'm getting the response (it's just an empty array)
You can either use the same method for sending data like with ajax and use form-data for which I'm getting the same response as with Ajax
function send() {
var formData = new FormData();
formData.append("first", "Hi!");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://arig.asuscomm.com/mn/PHP/submitNames.php", true);
xhr.send(formData)
}
Or you will need to handle json input on your server

XMLHttpRequest Returning Bad Request (400) while calling from java script , if i am calling from Java or Postman client it working fine

I am trying to call Spring rest method using java script.
I am getting:
POST http://www.davco.com/search/loginAuthentication 400 (Bad Request)
Below is my Java scrpt Code to invoke Spring REST service that I have
var userEmailId= $("#emailAddress").val();
var userPwd= $("#userPassword").val();
if (empty(userPwd)) {
alert("Please enter password");
return false;
}
var http = new createXMLHttpRequest();
var url = "/search/loginAuthentication";
var params = 'eid=' +userEmailId+'&pwd='+userPwd
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/xml");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
When i am trying to call same method from Google Postman client I am able to hit services and get the response..
I am not able to understand what wrong i am doing while i am calling it form Javascrpt. I have refer this link, this link as well.
I tried different Content-type header like :
http.setRequestHeader("Content-type", "text/html");
http.setRequestHeader("Content-type", "application/json");
http.setRequestHeader("Content-type", "Accept=application/xml");
I am seeing from browser request and request payload for POST call is going like below that is correct :
Below is my Spring Rest Services Code:
#RequestMapping(method = RequestMethod.POST, value = "/loginAuthentication" ,headers = "Accept=application/xml, application/json, text/html")
public #ResponseBody String loginAuthnticationForHTEtb(#RequestParam("eid") String userEmailId,#RequestParam("pwd") String password
,HttpServletRequest request, HttpServletResponse response) {
StringBuffer result = new StringBuffer();
try {
String domainVraiable=Context.getDomainName();
int inxexOfDot=domainVraiable.indexOf(".")+1;
int lastIndexOf=domainVraiable.lastIndexOf(".");
....
I am just wondering why it working and i am able to call from PostMan Client but not working while i am trying to call from java script? As you can see in below screenshot.
Thanks in advance for any kind of clue or information to get rid of this. I spend almost a day but could not figured out.
try it:
var params = {
eid:userEmailId,
pwd:userPwd
};
http.send(params);
or:
var formData = new FormData();
formData.append("eid", userEmailId);
formData.append("pwd", userPwd);
http.send(formData);
After spending a lot of time,still I am not able to figure out what exactly the problem in above implementation.
But now I change like this and working fine with below style :
var response = $.post("/search/loginAuthentication",{"eid":userEmailId, "pwd" :userPwd},
function(data,status){
processAuthenticationResponse(data);
},'json');
}
I had same problem. But then I sent string of JSON instead of JSON object. Then it worked.
request.send(JSON.stringify(json));

PHP not receiving data from XMLhttprequest

Hi I am sending data to a php script like so:
function ajax(url,data,success) {
var request = new XMLHttpRequest();
request.open("POST", url);
request.onreadystatechange = function(object) {
if(request.readyState === 3) {
success(request);
}
};
request.setRequestHeader("Content-Type","application/json")
request.send(data);
}
The data being sent is a stringifyed javascript object. The post definitely works and the object shows in the payload section in chromes dev tools. But the php script I am sending to request object is empty. The php script's content type is set to json.
Sounds like you're experiencing quite a well-known issue (some info here: PHP "php://input" vs $_POST)
You should be able to access the data with file_get_contents('php://input')

What should a proper GET request and response look like in Node.js

I am working on a small project using Node.js.
The objective is to send an HTTP Request to an array of websites and display what they return to me.
First someone helped me to figure out that I needed a specific Node.js module (XMLHttpRequest). So I "required" it after installing it with NPM. Then I instantiate it.
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
//I don't think I need this
xmlHttp.send(null);
//Log some stuff to the console, namely the "response"
console.log(xmlHttp.responseText);
console.log(xmlHttp.statusText);
console.log("Finished!");
Now I believe what this will do is send a GET message to "theUrl", and then save the response in the xmlHttp Object's responseText member.
So now I should have a response. I should be able to print that as text (console.log(xmlHttp.responseText);). What should be in this response?
I expect to get something like "200 OK" but that is nowhere in the response I get. Am I going about this in the right way?
I plan on using the Async Node.js module to send a request like this to an array of URLs, trim up their response (name of the website name, the response status code, and each of the response headers).
You can use below;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
// responseText => response body as string
// status => 200 is OK, 404 page not found
}
};
xhr.open("GET", "yor_url");
xhr.send();
responseText: response body as string
status: 200 is OK, 404 page not found

How to Call a WebService in titanium using javascript

I am new to titanium and and want to call a web service from my titanium app.
The webService returns the json response.
As I am aware of calling the webService using XMLRPC but very confused regarding json.
Until now, I know that we have to create the HTTPClient.
var request = Titanium.Network.createHTTPClient();
request.open("POST", "http://test.com/services/json");
request.onload = function() {
var content = JSON.parse(this.responseText);//in the content i have the response data
};
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //did not understand this line
request.send();
Now the problem is if my url(endpoints) have many WebServices, so where i will give the method name i.e WS name which is to be called.
From the API documentation of Titanium mobile the function open i.e. request.open accepts 3 parameters:
method name (http method name)
url of request
async (boolean property) by default true.
In the above code what is "POST" doing there?? and if my WS name is system.connect then where i will be mentioning that in code?
And what if the WS needs parameter, so how can we send the parameter to the webService form the above code.
I know that request.send() can be used to send parameter but how ??
To invoke a webservice you should:
// create request
var xhr = Titanium.Network.createHTTPClient();
//set timeout
xhr.setTimeout(10000);
//Here you set the webservice address and method
xhr.open('POST', address + method);
//set enconding
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
//send request with parameters
xhr.send(JSON.stringify(args));
// function to deal with errors
xhr.onerror = function() {
};
// function to deal with response
xhr.onload = function() {
var obj = JSON.parse(this.responseText);
};
address is your webservice url.
method is the method you desire to invoke.
address+method is a URL, in your example: "http://test.com/services/json" the method invoked would be named json.
args: is a json object where it's variable names should have the exact same name as the webservice parameters. You can create a the parameters object like this:
var args = {};
args.parameter1 = 'blabla';
args.parameter2 = 'blaaaa';

Categories

Resources