I send a Formdata with an Ajax request and try to read it in my php file. But in the php file, when i try to read what is in the $_POST with my key i see nothing. I don't understand why.
I did some research on the forum and tried to see why my code isn't working as i wanted to.
EDIT :
I saw the differents links but i was wondering i there is any ways to do it without JQuery.
My ajax call
function pageSend_DataRun ()
{
var formElement2 = document.forms.namedItem("data_to_send_general");
ajaxCallUrl ( "send.php",new FormData(formElement2), pageconfig_acq_generalDataCallback );
}
function ajaxCallUrl ( url, params, callback /*, ... */ )
{
var xhr = new XMLHttpRequest();
xhr.callback = callback;
xhr.arguments = Array.prototype.slice.call( arguments, 3);
xhr.onload = ajaxSuccess;
xhr.onerror = ajaxError;
xhr.open( "POST", url, true );
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send( params );
}
EDIT2 :
I found the solution there : [Using FormData object, the server receives an empty POST
I deleted the line to "setRequestheader" in my ajax configuration and it started working.
function ajaxCallUrl ( url, params, callback /*, ... */ )
{
var xhr = new XMLHttpRequest();
xhr.callback = callback;
xhr.arguments = Array.prototype.slice.call( arguments, 3);
xhr.onload = ajaxSuccess;
xhr.onerror = ajaxError;
xhr.open( "POST", url, true );
xhr.send( params );
}
I edit the answer of my question in the "EDIT2" section.
Hope it will help !
Related
I need to check if my xhr request returning me the response as #document, or as an error.
it can be other errors, like on image above (#403, net:ERR...)
Well.
I'll attach my code and will tell you where I need the help.
my function to getHTML.
let getHTML = function ( url, callback ) {
// Feature detection
if ( !window.XMLHttpRequest ) return;
// Create new request
let xhr = new XMLHttpRequest();
// Setup callback
xhr.onload = function() {
if ( callback && typeof( callback ) === 'function' ) {
callback( this.responseXML );
}
}
// Get the HTML
xhr.open( 'GET', url );
xhr.responseType = 'document';
xhr.send();
};
const domains = [];
and where I need help:
getHTML('https://www.brandnames.net/shop/?count=5', function (response) {
const nodeListDomains = Array.from(response.querySelectorAll( '.product-loop-title' ));
for(let i=0; i<nodeListDomains.length; i++){
getHTML(`http://${nodeListDomains[i].text}`, function (response){
if(response){
console.log(response)
}
**WHAT TO WRITE HERE TO GET ONLY WORKING RESPONSE, BUT NOT ERRORS? AND THE SAME FOR ERRORS, BUT NOT WORKING RESPONSE**
})
}
})
The main task: My client have a site where he's selling domains(brandnames.net/shop/), and we redirect all of domains to our landing page, but some of domains are not pointing to lander, so I need to check what exactly. Hope you will understand what I tried to tell.
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().
As indicated in the code snippet below, I am trying to extract a token from the response obtained from the first call made on XMLHttpRequest. I then want to send the token in the second POST call ensuring that cookies are the same. But, I am not able to figure out a way to preserve the cookies yet. Could someone share what I am missing here?
//First XMLHttpRequest below
xhr = new XHR();
xhr.onreadystatechange = extractLoginToken;
xhr.open( "GET", url );
xhr.setRequestHeader('Set-Cookie', "abc");
xhr.withCredentials = true;
xhr.send();
function extractLoginToken() {
var params = "token=" + this.responseText.query.token;
var cookie = xhr.getResponseHeader('Set-Cookie');
//Second call
xhr = new XHR();
xhr.withCredentials = true;
xhr.open( 'POST', url_1 );
xhr.setRequestHeader('Set-Cookie', cookie);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send( params );
}
I've looked at several answers here and they all use jQuery's .ajax() method. Below I have a vanilla JS method that is a trimmed down version which I am using with some success.
function ajax(options){
var settings = {
method : 'POST',
url : 'endpoint.php',
data : null,
done : function(){},
fail : function(){},
complete : function(){}
};
if(options) for(option in options) settings[option] = options[option];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if (xhttp.readyState == 4){
if(xhttp.status == 200){
settings.done(xhttp.responseText);
} else {
settings.fail(xhttp.responseText);
};
settings.complete(xhttp.responseText);
};
};
xhttp.open(settings.method, settings.url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhttp.send(settings.data);
};
Next is the function that assigns the file to a new FormData() object.
function beginUpload(index){
var file = files.files[index];
var pkg = new FormData();
pkg.append('file', file);
pkg.append('size', file.size);
ajax({
data : pkg,
done : function(res){
console.log(res);
}
});
};
Now, here's the problem: All tutorials and examples I've found say that the file will be found in the $_FILES global variable after the request is completed. I get a 200 response doing a var_dump() and $_FILES for me is empty but $_POST is not. $_POST has what looks like the file inside of it. Checked all the php.ini settings from this question.
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
Don't set that. XHR will recognise the FormData object and set it to the correct value (which that is not).
How do i use ajax to send POST requests to the server instead of GET?
Since I think that you're using the XHR object directly, you can make an 'postRequest' function easily:
We need the request url, the parameters to be send (params), and at least two callback functions success, which receives the responseText as the first argument when the request is completed successfully, and the error callback, which receives the XHR object and the status text:
function postRequest (url, params, success, error) {
var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") :
new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
success(xhr.responseText);
} else {
error(xhr, xhr.status);
}
}
};
xhr.send(params);
}
Sounds like you really should sit down and read about Ajax if you can not figure out how to move from a GET to a POST. That is Ajax 101 stuff:
https://developer.mozilla.org/En/AJAX
Put POST in as the first argument to xmlhttp.open() assuming you're using pure javascript:
xmlhttp.open('POST', 'example.php', true);
You can do it using jquery:
$.post("pageToPost.php", { firstParam: "Foo", secondParam: "Foo2" }, function(result){
alert("Response from pageToPost: " + result);
});
YUI connection manager would also be worth taking a look at as an alternative to jQuery. Using that you can make an ajax POST request as follows:
YAHOO.util.Connect.asyncRequest('POST', 'php/post.php', callback, "new=1&old=2");