Error 404 while trying to POST JSON to PHP using JS - javascript

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

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.

PHP not receiving any data from XMLHttpRequest

I cannot seem to send any POST data to a PHP file via XMLHttpRequest. I have read many questions like this one but everyone had a different issue - none of them seem to be the case here.
I have boiled these two files down to their absolute core basics and it is still is not receiving any POST data. I have done this the exact same way in plenty of other instances before and I'm not sure how this one is any different.
index.php
...
<button id="login-button">Log in</button>
...
Javascript:
function login() {
let ajax = new XMLHttpRequest();
ajax.open('POST', 'login.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
ajax.onload = function() {
alert(this.response);
};
ajax.send({user:'hello', password:'there'});
}
document.getElementById('login-button').addEventListener('click', login)
login.php:
var_dump($_POST);
The alert message with the output, every single time, simply reads:
array(0) {
}
The JS and PHP are both in the same folder of the same website on the same server, running PHP 7 if that matters. What could I possibly be doing wrong here?
By using ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); you basically tell your request to expect url-encoded data.
Lets keep it very simple, you want to submit a username and password.
So the request should look like this ajax.send("username=hello&password=there")
In your sample code you tried to send I dont know what kind of object-notation. The go-to way to exchange data between frontend and backend is JSON.
To modify your example to work with json modify it in the following way:
ajax.setRequestHeader("Content-Type", "application/json");
let data = JSON.stringify({"username": "hello", "password": "there"});
ajax.send(data);
To get an object out of a valid JSON string you can use the json parse method
pe this helps you out :)

Upload Generated PDF with AJAX is Not Working or Timing Out

I am using JSPDF to dynamically generate a PDF with user information on my web app, which is built in React.js and hosted on Firebase.
On the final page, I would like to email this PDF to a list of addresses that the user specifies. This sounds straightforward, but I have encountered some issues. Firstly, I cannot send an email using just React.js. Doing some research has led me to create a request to a PHP file that uploads the file. In the PHP file, I then use the standard PHP mailer to send the emails.
JSPDF has these functions used to export the file:
var pdfInBase64 = doc.output('datauristring');
var pdfInRawFormat = doc.output();
Here are 2 of my attempts to solve this issue. Both use FormData.
var formData = new FormData();
formData.append("data", pdfInBase64); // also tried pdfInRawFormat
Using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'uploader.php', true);
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('completed');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
Using AJAX:
var $ = require ('jquery');
$.ajax({
type: "POST",
url: 'uploader.php',
data: formData,
dataType: 'json',
contentType: false,
processData: false
});
Both of the above methods don't seem to be working for me. When I go to my console and look at the "Networking" tab, I see that a request has been made, but it times out after 20+ seconds. I tried not uploading a file and just setting data as hello or any other string, and the PHP file successfully receives it. I'm thinking that the file that I have is too large, leading to a timeout.
Could someone please point me in the right direction on how to fix this? My end goal is to send an email with an attachment using JavaScript and PHP. Thanks!!

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

Trying to upload file stored using HTML 5 File API

I'm piecing together tutorials from the web to be able to build a tool where users can upload images offline in an HTML5 app to filesystem storage along with some personal details and when they are online, they can "sync" which uploads the files and their details to the server.
I've managed to get a simple page up that stores images in file storage & sizes them down but I am unable to figure out how to post them using XMLHttpRequest. I've managed to push just the file data and store it one by one by using php://input (taken from Upload file from HTML5 Filesystem by XMLHttpRequest) but I need it to be uploaded as a form field that I can retrieve via $_FILES.
This function in particular:
function (fileName, successFct) {
getFileSystem(function (fileSystem) {
var fd = new FormData();
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(this.responseText);
}
};
fileSystem.root.getFile(fileName, {}, function (fileEntry) {
fileEntry.file(function(file) {
fd.append('file' + i, file);
fd.append('name' + i, 'name' + i);
});
}, errorFct);
xhr.send(fd);
}
);
};
Full code can be seen # http://pastebin.com/W0x9q6YH
In upload.php if I do the following
print_r($_FILES);
print_r($_POST);
It just shows two empty arrays.
Struggling with a similar problem: one thing I noticed about your code, you do not set your Content-Type header to multipart/form-data.
I do not have a working sample yet, but I'm pretty sure to use FormData, you need that old multipart/form-data magic.

Categories

Resources