PHP not receiving data from XMLhttprequest - javascript

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')

Related

Rss will not parse

I've been experimenting with xml data but I found an xml file with a structure that I've never seen before. I tried to call it using php and log it in the console but no luck any idea as to why? When I try this method with other files there seems to be no issue, for example, if you replace the url with this one "http://news.google.com/news?ned=us&topic=h&output=rss" it works fine. Code is below
PHP
$xml = "https://w1.weather.gov/xml/current_obs/display.php?stid=KATL";
echo file_get_contents($xml);
JS
var xhr = new XMLHttpRequest();
xhr.open("GET", "metar.php");
xhr.onload = function (response) {
var res = this.response;
console.log(res);
}
xhr.send();
This is not a problem with your script, but with the resource you are requesting. The web server is returning the "forbidden" status code.
You should probably check the https and the url.

XMLHttpRequest sends b'' instead of json data

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.

Error 404 while trying to POST JSON to PHP using JS

I am setting up a server using surveyjs library and am looking to connect it to an personal database that is hosted locally,
I am having trouble going from javascript and sending the json file to php and then sending that information to the database.
Have tried to you XLMHttp code to send json file but it wont post and I am getting a 404 not found error inside of the developer tools
This is my entire js file excluding the JSON
function sendDataToServer(survey) {
survey.sendResult('b48f3bcb-3978-4486-aa30-22cf94092850');
}
var survey = new Survey.Model(surveyJSON);
$("#surveyContainer").Survey({
model: survey,
onComplete: sendDataToServer
});
survey.onComplete.add(function (sender, options) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "connect.php", true);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(JSON.stringify(sender.data));
});
This is the php file
//Decode the JSON string and convert it into a PHP associative array.
$data = json_decode($_POST['sender'], true);
This is the specific line that is causing the error
xhr.send(JSON.stringify(sender.data));

IE11 XMLHttpRequest do not receive full data from server

I am currently working on a web application and I came across with a strange problem. The request that I send to my flask app from Google Chrome and Firefox with XMLHttpRequest works as intended but in IE11 and possibly older versions it looks like IE closes the connection before the data is fully transferred. I send post request like this:
function getData() {
var req = new XMLHttpRequest();
req.open("POST", "http://"+window.host+"/text", true);
req.responseType = "json";
req.addEventListener("readystatechange", function(e){
if (e.target.readyState == 4 && e.target.status == 200){
display(e.target.response.data);
}
});
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.send(JSON.stringify({"text": "some text"}));
}
and receive from flask app like this:
#app.route('/text', methods=["POST"])
def data():
if request.is_json:
if "text" in request.get_json():
for i in request.get_json()["text"]:
if not re.search(textIntegrity, i):
return jsonify({"status": "Unrecognized characters: {}.".format(i)})
break
data = reData(request.get_json()["text"])
return jsonify({"status": 200, "data": data})
else:
return jsonify({"status": "Key 'text' not found."})
else:
return jsonify({"status": "Request type is not in json format."})
In mozilla and firefox I get the full data and the XMLHttpRequest object states that the response type is json: Mozilla Response but in IE there is no response type and the reponse is cut if it is too long:
IE Response
I don't know whether it's the flask problem or the way that IE handles the request, maybe I need to add some headers to flask project but I don't know.
Use ActiveXObject objects instead of XMLHttpRequest for older IE:
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
I am not sure the above will solve the issue because you already have IE11 (newer version). Why don't you try AJAX call using JS frameworks and see if you get same issue.
I would say, instead of using XMLHttpRequest(), use any JS framework/library to make AJAX calls to your flask REST endpoint, because JS frameworks/libraries will take care of these kind of issues with IE. For example JQuery, AngularJS.
I ended up changing server side code and client side code a little and made the server to send json data as string and parsing it on the client side.
function getData() {
var req = new XMLHttpRequest();
req.open("POST", "http://"+window.host+"/text", true);
req.addEventListener("readystatechange", function(e){
if (e.target.readyState == 4 && e.target.status == 200){
display(JSON.parse(e.target.response));
}
});
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.send(JSON.stringify({"text": "some text"}));
}
#app.route('/text', methods=["POST"])
def data():
if request.is_json:
if "text" in request.get_json():
for i in request.get_json()["text"]:
if not re.search(textIntegrity, i):
return jsonify({"status": "Unrecognized characters: {}.".format(i)})
break
data = reData(request.get_json()["text"])
return json.dumps(data);
else:
return json.dumps({"status": "Key 'text' not found."})
else:
return json.dumps({"status": "Request type is not in json format."})
It maybe is just an issue about flask jsonify, the way flask handles the responses or the way IE handles the requests, I don't know, I had the opportunity to edit the server so I went with that way.

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

Categories

Resources