i know how to send post forms and process it server side with php... something like
<!-- html form -->
<form action='getform.php' method='post'>
your first name: <input name='fName'/>
your last name : <input name='lName'/>
<input type='submit'/>
</form>
//--- getform.php ---
print_r($_POST);
// prints something like:
// Array(
["fName"]=>["John"],
["lName"]=>["Doe"]
// );
echo "your full name is: {$_POST['fName']} {$_POST['lName']}";
// prints something like "your full name is: John Doe"
i am just developing it on my php server... the actual form has many more inputs and later i have to flash into an embedded system, so to make it more efficient (memory usage, responsiveness, etc) i decided to do it with AJAX...
to simplify things, i read that you can create a FormData directly from <form> and pass it directly to send() method, something like
<!-- html form -->
<form onsubmit='ajaxPost(this);return false;'>
your first name: <input name='fName'/>
your last name : <input name='lName'/>
<input type='submit'/>
</form>
<script>
function getResponse(ans){
alert('your full name is: ' ans);
}
function ajaxPost(myForm){
var xhr = new XMLHttpRequest();
xhr.onload = function(){getResponse(this.responseText);};
xhr.open('POST', 'getform.php');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(new FormData(myForm));
}
</script>
//--- getform.php ---
echo $_POST['fName'].' '.$_POST['lName'];
however the form data i recieve with php is something with weird format like
// print_r($_POST);
Array(
[------WebKitFormBoundaryDP16ROTp3RJIUWFf
Content-Disposition:_form-data;_name] => "fName"
John
------WebKitFormBoundaryDP16ROTp3RJIUWFf
Content-Disposition: form-data; name="lName"
Doe
------WebKitFormBoundaryDP16ROTp3RJIUWFf--
);
it seems like php uses parse_str()
function internally to convert received request from querystring format to store in $_POST array, but as the request seem chunked instead it fails, i tried by changing Content-Type
in XHR and <form> but nothing changes
the question: using just ajax and plain javascript, how can i get rid all of those 'boundaries' and 'disposition' chunked things and send a normal querystring format POST, parsed by php like a normal array like ["fName"=>"John", "lName"=>"Doe"] ???
... i had searched some help or documentation on internet but i hadn't found anything about this :( ... thanks in advance
CodePudding user response:
@atesin: i am yourself from the future, bringing you the answer you searched for
you can use URLSearchParams()
before to transform FormData into urlencoded format, this way
xhr.send(new URLSearchParams(new FormData(myForm)));
this answer was taken from here: FormData change from multipart/form-data to form-urlencoded?