jQuery AJAX POST to PHP works, XMLHttpRequest doesn't - javascript

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

Related

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.

Receive Single Data from xml

I have brought some data from the server using ajax.
Now I want to, not bring all the data, only the name is inter.
How can I do this?
that my code
const url = 'https://jsonplaceholder.typicode.com/users'
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
console.log(xhr.response);
}
xhr.open('GET', url)
xhr.send()
You could loop through the xhr response and get the name of the users.
xhr.onreadystatechange = () => {
if(xhr.response) {
let userResponse = JSON.parse(xhr.response);
for (index in userResponse) {
console.log(userResponse[index].name);
}
}
}
You can even save it in a temporary variable and make further manipulations.
But if you meant bringing just the name from the server, it is not possible unless the server exposes an API to do so.
If you have access to the server you could create an API to do this. But, if your server had used graphQL, it is possible to make queries while making API requests like you asked for.

Post request to webhook without redirecting

How can I make a post request (after validating some user input) to a webhook without redirecting the user to the webhook url?
Tis kind of request is generally done using AJAX.
If you are using jQuery, you should look at .post() method. See an exemple of it:
$.post( "/url.html", function( data ) {
# action on request response
});
If you are using raw javascript (without js libs), you should look at XMLHttpRequest() object. Example of use:
var post = function() {
var url = "http://www.example.com";
var request = new XMLHttpRequest();
request.open( "POST", url, true);
request.send(null);
}
Using this approach of request you will not be redirect, like the common case of HTML submitions.

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

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

Categories

Resources