Javascript send post data in asynchronous environment - javascript

So my Problem is, that I get data from another server and im trying to send this received data to the same url to be able to retreive the data in PHP. I tried it with fetch(), $.post(), $.ajax(). Every time my xhr request is being cancelled by the browser for some unknown reason. Here is my current code:
function generateCodes()
{
var someVAR = document.getElementById("length").value;
var someResult = createDataPromise("someVAR=" + someVAR);
someResult.then((data) =>
{
var jsonData = JSON.stringify(data);
$.ajax(
{
url: "sameURL",
method: "post",
data: jsonData,
success: function(data)
{
console.log(data);
}
});
});
someResult.catch((error) =>
{
console.error("Server responded with error: " + error);
});
}
function createDataPromise(data)
{
return new Promise((resolve, reject) =>
{
const xhr = new XMLHttpRequest();
xhr.open("POST", "externalServer");
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = () => resolve(JSON.parse(xhr.responseText));
xhr.onerror = () => reject(xhr.statusText);
xhr.send(data);
});
}
Is there any other possible solution to access the javascript object in PHP? (It is not possible to convert the varible because the javascript is in a pure js file)

It's possible that the browser is blocking your request because of CORS. Modifying your request to be CORS compliant or making sure the remote response includes an Access-Control-Allow-Origin: * header would fix this.
Making sure your request is considered a simple request would eliminate the possibility that it is being denied by a preflight request since you only need to send data and not receive it back in the javascript.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Related

Correct content-type for sending this AJAX Post data

I am having problem sending base64 image data using ajax post
I think I have the wrong value for Content-Type but have tried application/json, text/json and image/jpeg without any success
Javascript
function sendFormData(fD)
{
var urls = fD.get('urls');
console.log('urls', urls);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/editsongs.update_artwork');
alert(urls);
xhr.setRequestHeader("Content-type", "image/jpeg");
xhr.send(urls);
}
Browser console shows
["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTExMWFhUXGRgbGBgXGR0aGRgXHRgYFx4YGxkYHiogGh4lGxgdIjEhJSkrLi4uGh8zODMtNygtLisBCgoKDg0OGhAQGy0lHSUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIANEA8QMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAEBQMGAAECBwj/xABGEAACAQIEBAQDBAUJCAIDAAABAhEDIQAEEjEFIkFREzJhcQaBkRRCobEjUsHh8AcVM2JygsLR8RZDRFNzg5KyJDSzw8T/xAAZAQADAQEBAAAAAAAAAAAAAAABAgMABAX/xAAqEQACAgEDBQACAQQDAAAAAAAAAQIRAxIhMQQTFEFRImGRYnGh8AUjMv/aAAwDAQACEQMRAD8AsoosJt9cSpSdeYKYEXxKlQs4E2kEx6dMWJFBEDr0OPey5nCrR58MalwJUpB1nENbJWthpTyQDG5H5Y0gGqNQOJLLXA7h9K9VypGITSPbD+tSGIFy4mSJx0xz7EXjE7UscacNamW30jAlbLsNxiscqZNwoCK4wDEzJjkLiuoQjGNEYnCY5ZcawkMY5bEkY5GGsUijG1XtjcYPyFAQWMbbdsac9Ks0Y2wQphlwTKLUZg2wAwFmq8m5HYY5HFTRph0VnBI1QDZZgsZGwEnHPmn/ANb+lMcVqLFWRafKMTU+L6bRb88V/LcY+0otQKVmbdcbq1wsSYkgDfc7C3fHIoRlDVIs5tSpFzyXEtcdCdvlhopwp4RSpwvcAf64bj0x5mbSpUjrhdbmicSU1xi08djEWylGRjRGOsC5uodl379sBK2F8HbMAJxUON5lqrQFMA4f1CVU62ke2FaZlWqXgAbepx29MtD1VZzZXaol4RwYKsuAWP4…
Java Server code
public String updateArtwork(Request request, Response response)
{
System.out.println("Received artwork");
for(String s:request.queryParams())
{
System.out.println("---"+s);
}
System.out.println("ReadParms");
return "";
}
just outputs
Received artwork
ReadParms
Updated to Send as Form Instead
// Once we got everything, time to retrieve our objects
function sendData()
{
var fD = new FormData();
// send Files data directly
var files = imgList.filter(
function isFile(obj)
{
return obj.type === 'file';
}
);
files.forEach(
function appendToFD(obj)
{
fD.append('files[]', obj.file);
}
);
// for elems, we will need to grab the data from the server
var elems = imgList.filter(
function isElem(obj)
{
return obj.type === "element";
}
);
var urls = elems.map(
function grabURL(obj)
{
return obj.element.src;
}
);
if (urls.length)
fD.append('urls', JSON.stringify(urls));
sendFormData(fD);
};
function sendFormData(fD)
{
// but here we will just log the formData's content
var files = fD.getAll('files[]');
console.log('files: ', files);
var urls = fD.get('urls');
console.log('urls', urls);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/editsongs.update_artwork');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(fD);
}
then on server I have
public String updateArtwork(Request request, Response response)
{
System.out.println("Received artwork");
for(String s:request.queryParams())
{
System.out.println("***"+s);
System.out.println(request.queryParams(s));
}
System.out.println("ReadParms");
return "";
}
and its outputs
Received artwork
***-----------------------------330219842643
Content-Disposition: form-data; name
"urls"
["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMSEhUSExIWFhUXFxgXGBcYFRgXFxkdGBcWGBgYFx0YHSggHR0lHRkYITEhJSkrLi4uFyA1ODMtNygtLisBCgoKDg0OFQ8PFSsZFRkrLSstLSstKysrLS03KystLSstKy03LSstLSstNzc3KysrLS0tKysrKysrKysrKysrK//AABEIAKoBKQMBIgACEQEDEQH...."]
-----------------------------330219842643--
ReadParms
So I'm now getting the data but I don't understand really understand how to parse the Content-Disposition part in Java.
This code wasn't originally written by me, as you can see the FormData is constructed it doesnt come from an actual form. My first attempt was to try and extract from FormData and send in different way, an alternative would be to not store in FormData in the first place but dont know how to do this.
Update 2
Tried just sending first url rather than formdata or an arrya of urls, because actually there is only ever one url.But it just doesnt work, nothing received by server ?
function sendFormData(urls)
{
console.log('urls', urls[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/editsongs.update_artwork');
xhr.setRequestHeader("Content-type", "text/json");
alert(JSON.stringify(urls[0]));
xhr.send(JSON.stringify(urls[0]));
}
You are trying to view data in the body using queryParams(), which will give you the query params that are located in the url.
Load data from the request body using body().

HTTP Post Request not working throwing error "XMLHttpRequest" is not defined

I'm pretty new to javascript and am working on an integration system.
This is a small integration system, so I can't use Ajax or add any other normal web technologies, I just need to use Javascript to send a HTTP POST and get response only after success, so my first goal is to be able to send that POST message
I have written code but i am getting error
Exception in map activity: org.mozilla.javascript.EcmaError: ReferenceError: "XMLHttpRequest" is not defined.
function abc(){
var url = "https://na10.saourt.com/se/sendData";
var method = "POST";
var postData ="[{\"name\":\"anderson\",\"ContactEmail\":\"ad#gmail.com\"}]";
var async = true;
var request = new XMLHttpRequest();
request.onload = function () {
var status = request.status;
var data = request.responseText;
}
request.open(method, url, async);
request.setRequestHeader("Content-Type", "application/json");
request.setRequestHeader("Authorization", "OAuth 123");
request.setRequestHeader("securityToken", "123#abs");
request.send(postData);
}
Have you tried sending an empty/basic post request?

Symfony 3 - Sending AJAX request as XmlHttpRequest() (javascript) does not pick up request as XmlHttpRequest in backend

I have an ExceptionListener implemented in Symfony3 (also works in Symfony2). The ExceptionListener identifies whether the request was normal HTTP or AJAX (XmlHttpRequest) and generates a response accordingly. When using jQuery .post() or .ajax(), the ExceptionListener returns $request->isXmlHttpRequest() as TRUE, but when using javascript var xhr = new XmlHTTPRequest(), the ExceptionListener returns $request->isXmlHttpRequest() as FALSE. I am using the latter in a small amount of instances where files need to be uploaded via AJAX (which cannot be done using .post() or .ajax().
I am looking for a solution (either frontend or backend) to resolve my ExceptionListener incorrectly picking this up as a normal HTTP request.
Frontend Code:
function saveUser()
{
var form = document.getElementById('userForm');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', '{{url('saveUser')}}', true);
xhr.onreadystatechange = function (node)
{
if (xhr.readyState === 4)
{
if (xhr.status === 200)
{
var data = JSON.parse(xhr.responseText);
if (typeof(data.error) != 'undefined')
{
$('#processing').modal('hide');
$('#errorMsg').html(data.error);
$('#pageError').modal('show');
}
else
{
$('#successMsg').html('User Successfully Saved');
$('#processing').modal('hide');
$('#pageSuccess').modal('show');
$('#userModal').modal('hide');
updateTable();
}
}
else
{
console.log("Error", xhr.statusText);
}
}
};
$('#processing').modal('show');
xhr.send(formData);
return false;
}
ExceptionListener.php (partial)
# If AJAX request, do not show error page.
if ($request->isXmlHttpRequest()) # THIS RETURNS FALSE ON JS XmlHTTPRequest()
{
$response = new Response(json_encode(array('error' => 'An internal server error has occured. Our development team has been notified and will investigate this issue as a matter of priority.')));
}
else
{
$response = new Response($templating->render('Exceptions/error500.html.twig', array()));
}
When using vanilla ajax you need to pass the following header to your ajax request
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

Sending a JSON to server and retrieving a JSON in return, without JQuery

I need to send a JSON (which I can stringify) to the server and to retrieve the resulting JSON on the user side, without using JQuery.
If I should use a GET, how do I pass the JSON as a parameter? Is there a risk it would be too long?
If I should use a POST, how do I set the equivalent of an onload function in GET?
Or should I use a different method?
REMARK
This question is not about sending a simple AJAX. It should not be closed as duplicate.
Sending and receiving data in JSON format using POST method
// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "hey#mail.com", "password": "101010"});
xhr.send(data);
Sending and receiving data in JSON format using GET method
// Sending a receiving data in JSON format using GET method
//
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "hey#mail.com", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
xhr.send();
Handling data in JSON format on the server-side using PHP
<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>
The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.
Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.
Using new api fetch:
const dataToSend = JSON.stringify({"email": "hey#mail.com", "password": "101010"});
let dataReceived = "";
fetch("", {
credentials: "same-origin",
mode: "same-origin",
method: "post",
headers: { "Content-Type": "application/json" },
body: dataToSend
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
return Promise.reject("server")
}
})
.then(dataJson => {
dataReceived = JSON.parse(dataJson)
})
.catch(err => {
if (err === "server") return
console.log(err)
})
console.log(`Received: ${dataReceived}`)
You need to handle when server sends other status rather than 200(ok), you should reject that result because if you were to left it in blank, it will try to parse the json but there isn't, so it will throw an error

Force "charset=x-user-defined'" on jQuery Ajax Post

I am trying to call a Hessian web service from a Javascript application, but I'm having issues parsing the response, since jQuery is treating the response as text and stripping the first bytes of it.
In my research, I have found out that you need to set the charset as 'charset=x-user-defined' in order to the browser leave my bytes as is. But, according the ajax docs:
Sending Data to the Server
By default, Ajax requests are sent using the GET HTTP method. If the
POST method is required, the method can be specified by setting a
value for the type option. This option affects how the contents of the
data option are sent to the server. POST data will always be
transmitted to the server using UTF-8 charset, per the W3C
XMLHTTPRequest standard.
And indeed, the charset is not changing regardless of the settings I used. I have tried the following, separately and all at once, with no luck
$.ajax({
type : 'POST',
url : url,
timeout : 3000,
data : parameters,
contentType : "x-application/hessian; charset=x-user-defined'",
mimeType: 'text/plain; charset=x-user-defined',
headers: {
Accept : "text/plain; charset=x-user-defined",
"Content-Type": "text/plain; charset=x-user-defined"
},
beforeSend : function(xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
Also I tried to mess around with the data converters and custom contenttypes defined in jQuery, with no succes.
It appears that as per the standard, I will not be able to do this. It works with GET but not with POST, and the Hessian protocol requires POST.
Do you have any ideas? Or do I need to start to build my XHR method form scratch?
Turns out that I was making a silly mistake somewhere else. But anyhow, I found a sweet way for handling binary data on request and responses, from here.
define(function() {
// Do setup work here
function configurationException(message) {
throw new Error(message + " missing from configuration object");
}
return {
post : function(config) {
if (config) {
var url = config.url || configurationException("url");
var done = config.done || configurationException("callback function");
var timeout = config.timeout || 10000;
var data;
if (config.data) {
data = config.data;
} else {
data = null;
console.warn('No data is specified in binaryPost');
}
var request = new XMLHttpRequest();
request.open("POST", url, true);
request.responseType = "arraybuffer";
request.setRequestHeader("Content-Type", "x-application/hessian;");
request.onload = function(oEvent) {
var arrayBuffer = request.response; // Note: not oReq.responseText
if (arrayBuffer) {
var byteArray = new Uint8Array(arrayBuffer);
done(byteArray);
}
};
request.send(data);
} else {
throw new Error("Configuration object is missing");
}
}
};
});
Hope you find it useful

Categories

Resources