PHP not receiving any data from XMLHttpRequest - javascript

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

Related

How to add JSON data to GET request to XMLHttpRequest?

I have a problem with setting JSON data in a GET request.
I tried:
As POST request (with POST request it works)
xhr.open("GET", "http://localhost/test", true);
body = JSON.stringify({"email": "hey#mail.com", "password": "101010"});
xhr.send(body);
As query string:
var json = {"hello": "world"};
var url = "http://localhost/test?data=" + encodeURIComponent(JSON.stringify(json));
xhr.open("GET", url, true);
xhr.send();
On the backend method, req.json returns null, but I can see the query string.
Also, it works in Postman if I set JSON data to the body. On the backend, I see JSON data in the request.
P.S.: In my previous project I used the same backend framework but the frontend was based on jQuery instead of pure JS and the ajax method worked correctly.
2 months without web development born such stupid questions. I don't use node.js but I think node.js acts so. I remembered the right way. I have tried to use "localhost?data={a: 9}" but the correct way is "localhost?a=9". The backend will parse all query variables as input in the Rest interface. Thanks to #evolutionxbox for kicking to the right side.

Can't send large json data via XMLHttpRequest - javascript

I need to pass a json variable as a paramater to a php script that will process the json data and store it in Database.
So first, in javascript, i was testing sending data like this :
$('#sendResult').load('http://localhost/myurl/phpFile.php?mrData=' + jsonArrFinal);
This was working well when passing small records (records can vary, it depends the data that user insert).
But when i increased the records, it started appearing this error in console:
414 (Request-URI Too Long)
I've changed the js code to:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/myurl/phpFile.php?mrData=' + jsonArrFinal );
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.send();
But still appearing the same error with POST method.
I've checked the json param and it has 5439 characters.
How can i resolve this? Thanks in advance.
Please note that the length can be 8x more than 5439 characters.
Don't use a GET request.
You're storing data, so you should be using a POST request anyway.
Use $.post instead of $.load and write your own logic to display the response in the done() handler.
I've changed the js code to:
You need to put the data in the body of the request. POST requests don't change the rules for how much data you can put in the URL.
$.post("http://localhost/myurl/phpFile.php", { mrData: jsonArrFinal })
.done( data => $("#sendResult").html(data) );

How to send XMLHttpRequest to specific php function?

I am trying to do a image uploading with ajax. I have run into a bit of problem. I have two functions in func-ajax.php : function doSth(){} and function doSthElse(){}. I want to target the doSth() function
This is my javascript side:
var xhr = new XMLHttpRequest();
xhr.open("POST", 'func-ajax.php', true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
How can I specify whick function to send the request?
You cannot run a specific function from the func-ajax.php file.
What you should do is create something like ajax-controller.php, containing
$functionName = $_POST["func"]; // func parameter should be sent in AJAX, determines which function to run
if (function_exists($functionName)) { // check if function exists
$functionName(); // run function
}
And send all requests from JS to this file xhr.open("POST", 'ajax-controller.php', true);
Hope you get the idea.
You want to send GET/POST parameters along with your request, and catch those in the PHP script.
You can't send an HTTP request to a function.
You make a request for a resource. That request can include POST data and it can include HTTP headers.
The server then decides how to respond the request. It might choose to run a PHP program.
It is up to the PHP program to look at the requested resource / POST data / headers and determine which function(s) to run.
You can add a parameter in the data being sent and that you check for in some sort of if block that you call the function manually from. You could also introduce a framework like Slim, to create an REST-api point that you can hit.

How to create an in memory file and upload to server using client side javascript?

I have a test suite written in JavaScript running in a browser that runs on an embedded system. The test suite collects a lot of data and I want to push that to the server. I could use a simple HttpRequest, post-method, but that would require a lot of character escaping to send the content. It would much simpler to upload it to the server as a file using http-file-upload.
Is there a way to create an in memory file and use http-file-upload to push it to a server, using client-side JavaScript?
Since the browser of the embedded system is Ekioh and the system itself is a minimal one, technologies such as flash, JavaApplet, SilverLight are not available. Only pure HTML5 and JavaScript are available.
I think a post would be the better way to do this. Dealing with escaped data is a much easier, more established problem then in-memory files and pushing files to the server with client side javascript. Moreover, escaping data is done for a reason. What you're trying to do is going to welcome a lot of security vulnerabilities.
Try doing something like this.
Snippet taken from Write javascript output to file on server
var data = "...";// this is your data that you want to pass to the server (could be json)
//next you would initiate a XMLHTTPRequest as following (could be more advanced):
var url = "get_data.php";//your url to the server side file that will receive the data.
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);//check if the data was revived successfully.
}
}
http.send(data);
This worked for me. The key part is to create a file and blob. I use angular JS to do the actual http call. However, once you have a file in memory, it shouldn't be too hard to send the data using your http client.
Note: I do the http call to https://httpbin.org/post. This echoes what the server received/parsed, which is useful while iterating to figure your problem out.
function multiPartPost(bodyObj) {
const url = 'https://httpbin.org/post';
const bodyJson = JSON.stringify(bodyObj);
const blob = new Blob([bodyJson], {
type: 'application/json;charset=UTF-8'
});
const fileName = 'jsonAttrs';
const file = new File([blob], fileName, {type: "text/json;charset=utf-8"});
const formData = new FormData();
formData.append(fileName, file);
return this.$http.post(url, formData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
}

Struggling to communicate with the utorrent web API

I am trying to access utorrents web api, it uses a token authentication system which is detailed here
the JavaScript on my page is
<script>
$.getJSON("http://XXX.XXX.XXX.XXX/lib/token.php", function(response) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
//script.onreadystatechange = function () {
// if (this.readyState == 'complete') utorrent();
//}
//script.onload = utorrent();
script.src = 'http://XXX.XXX.XXX.XXX:8080/gui/?list=1&token=' + response.token;
head.appendChild(script);
});
</script>
simply retrieving the token from a php file and passing it along the chain, i have confirmed that the token is being passed and is not being poisonned, my PHP document is below
<?php
header('Content-type: text/json');
$token = file_get_contents('http://[username]:[password]#XXX.XXX.XXX.XXX:8080/gui/token.html');
$token = str_replace("<html><div id='token' style='display:none;'>", "", $token);
$token = str_replace("</div></html>", "", $token);
$response = array('token' => $token);
echo json_encode($response);
?>
this gives me a confirmation of the token
Object {token: "GMt3ryaJE64YpXGN75-RhSJg-4gOW8n8XfTGYk_ajpjNLNLisR3NSc8tn1EAAAAA"}
but then i receive a 400 error code when retrieving the list
GET http://XXX.XXX.XXX.XXX:8080/gui/?list=1&token=GMt3ryaJE64YpXGN75-RhSJg-4gOW8n8XfTGYk_ajpjNLNLisR3NSc8tn1EAAAAA 400 (ERROR)
Any help/thoughts/idea's would be greatly appreciated
just adding my 2 cents.
I've been doing a similar implementation in .NET MVC - I was able to get the token as you did, but the list=1 feature didn't work for me either, getting the 400 bad request code (as you have found).
The solution for me:
In the token.html response, there is a token in the div and also a GUID in the header.
To break it down:
Call token.html with uTorrent credentials
In the response content, parse the html to get the token
in the response header, there is a value with key Set-Cookie, which looks like
Set-Cookie: GUID=<guid value>
I needed to use this value (GUID=<guid value>) in all requests being sent back, as well as the token and it worked!
I'm not sure what the implementation is in PHP to do this however :)
Also quick note, I've been trying to get values through jQuery's $.getJSON and $.Ajax method without any success, because the browser (chrome) I'm using has strict guidelines on cross domain requests, and it doesn't look like uTorrent is implementing JSONP.
Hope this helps!
The 400 Error message means you are communicating with a bad request.
The MIME media type for JSON text is application/json .
use text/plain or application/json, not text/json.
application/json sometimes causes issues on Chrome, so you might want to stick with text/plain in this case.
Have you tried changing the order of the query parameters?
eg: http://localhost:8080/gui/?token=<token_uuid>&list=1
Reference: https://github.com/bittorrent/webui/wiki/TokenSystem#examples
UPDATE
I ran into a similar problem trying to create and XMPPBot for utorrent client in python.
#m.t.bennett was correct. You need to save the session information as well.
When you receive the response from token.html, capture the cookie information as well.
Usually there are 2 params: GUID and sessions. You need to put them in the header for all your subsequent requests -- List API, Getfiles API, etc.
This should fix your problem!

Categories

Resources