Post method with ajax - javascript

I would like to send the data to another php page using javascript but it does not work as expected.
Let just say I have the form:
<form id="myForm">
<label for="name">Username</label>
<input type="text" name="name" id="name">
<label for="pass">Password</label>
<input type="password" name="pass" id="pass">
<button id="submit" type="submit" >OK</button>
</form>
and the script:
const myForm = document.getElementById('submit');
myForm.addEventListener('submit', function(e){
e.preventDefault();
const data = new FormData(this);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'getData.php', true);
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send(data);
});
The php file is unable to recieve the data at the moment. How can it fix with ajax or any other equivalent code?

Make change in button
<button id="submit" type="button" onclick="sendData()" >OK</button>
Then add javascript function.
<script>
function sendData(){
var name = document.getElementById("name");
var password = document.getElementById("pass");
if (name) {
$.ajax({
type:"POST",
url:"path-to-php-file.php",
data:'name='+name+'&pass='+password,
success:function(data){
alert(data);
}
});
}
</script>
Then create php file where you will get data.
path-to-php-file.php
<?php
$name = $_POST['name'];
$password = $_POST['pass'];
echo $name .'--'.$password;
?>

I cannot tell exactly what is the problem without looking at your php code.
Maybe there is something wrong with the Content-Type header.
document.getElementById('submit').addEventListener('submit', (e) => {
e.preventDefault();
const data = new FormData(this); // Here 'this' will not work, you gotta loop through the inputs and append them to the FormData object.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
// do something
}
xhr.open('POST', 'getData.php', true);
// the default content type is application/x-www-form-urlencoded
xhr.setRequestHeader("Content-Type", "<content type here>")
xhr.send(data);
});
Extra
What I suggest is in your case you won't really need a form element here. You could make the button a normal button and make the form a div(not special benefit, just for clean code). Assign a function to the onclick event of the button and loop through the inputs and append them to the form data(if the content type is application/x-www-form-urlencoded) object and send it to the server.Use this method if you have a complex form like a interactive form like Google or Microsoft have.
And also you do not want to use preventDefault() method if you follow my method.
This is what most professionals would do.

Related

How Do I Post A Form Without Redirecting Using Raw Javascript?

I've seen several posts about how to post a form using AJAX, but I am curious about options for simplification.
Here's a trimmed down version of what I'm trying:
<form id="message-form" method="POST" action="/send-message" onsubmit="return false;">
<input type="text" name="message"><br/>
<input type="text" name="phone_number"><br/>
<button type="button" onclick="return trysubmit()">Send Message</button>
</form>
<script>
function trysubmit()
{
document.getElementById("message-form").submit();
//notify user of success
//cancel the redirect
return false;
}
</script>
In this case, the form gets submitted, but the redirect still happens.
Is something like the above even possible, or do I have to manually build an AJAX request like this?
form serialize javascript (no framework)
var form = document.getElementById('message-form');
var data = new FormData(form);
var req = new XMLHttpRequest();
req.send(data);
Unless resorting to hacks like posting to a dummy target, AJAX is the way to go.
This works:
const form = document.querySelector("#message-form");
form.addEventListener("submit", event => {
event.preventDefault()
let status = "";
const data = new FormData(form);
const req = new XMLHttpRequest();
try{
req.open("POST", '/send-message');
req.send(data);
status = "success";
}
catch{
status = "failure";
}
notifyuser(status);
});

Javascript formData array returns empty

I have an issue with my AJAX formData object. If select a file in the input and I send this with AJAX the array is empty. I hope somebody can help me with this. Below my code
HTML and JavaScript
<form method="post" id="quoteform">
<input type="file" name="uploadfile" id="quote"/>
<input type="submit" value="upload"/>
</form>
<script type="text/javascript">
document.getElementById("quoteform").addEventListener("submit", function(){
var files = document.getElementById("quote").files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i]
formData.append('files[]', file);
}
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "linktophpfile.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('upload='+formData);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
}
event.preventDefault();
});
</script>
PHP
<?php
if(isset($_POST['upload'])){
print_r($_FILES);
}
?>
The PHP file returns
Array
(
)
when you upload files then you can't use application/x-www-form-urlencoded you have to use multipart/form-data
you shouldn't mix strings with formData send('upload='+formData) it will only result in you uploading a string equal to upload=[Object object]
you should instead just send the formData and let the XHR or Fetch handle the content-type for you automatically.
If you want an array then i presume you also want the attribute mulitple? You could always add in the required and accept="image/*, .txt" for good measure
You don't manually have to add in all files to a formdata if you just use the first constructor argument that accepts a form element, everything from the form will be added
<form method="POST" action="https://httpbin.org/post" id="quoteform" encoding="multipart/form-data">
<input multiple type="file" name="files[]" id="quote" required />
<input type="submit" value="upload"/>
</form>
<script>
// html (xml) should mark the settings, behavior as it mostly always have done
// in all years way back and the js should provide enhancement and
// be more generally written to enhance the site (if js where
// to be turned off - most unlikely, I for once have it disabled in my phone)
// static sites works better without ads + annoying cookie popups
// it's a good thing Brave have quick toggle to enable scrips for js-only pages
function ajaxify (evt) {
evt.preventDefault()
var form = evt.target
var formData = new FormData(form)
fetch(form.action, {
method: form.method,
body: formData
}).then(res => res.text()).then(alert)
}
document.getElementById("quoteform").addEventListener("submit", ajaxify)
</script>

Undefined data when sending Javascript Object with Ajax

Let's say I'm trying to send a data to PHP and receive it using pure Javascript.
So when I'm sending a string "login="+1+"&username="+username+"&password="+password; with Ajax It's all ok but what about an Object? in this case, my PHP code always telling username and password are Undefined indexes.
HTML Document :
<body>
<form id="loginform">
<input type="text" placeholder="username" id="username" required autocomplete="off"><br>
<input type="password" placeholder="password" id="password" required><br>
<input type="submit" id="submit">
</form>
<script>
document.getElementById("loginform").addEventListener("submit", function(e) {
e.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var data = {// ---- there is my Object -----
login: 1,
username: username,
password: password
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log(this.responseText);
}
xhr.send(data);
});
</script>
</body>
PHP Document :
<?php
if(isset($_POST["login"])) {
$username = $_POST['username'];
$password = $_POST['password'];
echo($username . " , " . $password);
}
?>
what about an Object?
send() doesn't expect to be passed a plain object, so it converts it by calling its toString() method, which gives you "[object Object]", which (obviously) isn't URL encoded data.
Not only does PHP not understand it, but the data you want to send isn't included in it in the first place.
If you have an object, you need to convert it into a format that you can decode on the server.
Continuing to use form encoded data is the simplest approach.
var data = {
login: 1,
username: "example",
password: "example"
};
var key_value_pairs = [];
Object.keys(data).forEach(function(key) {
key_value_pairs.push(
encodeURIComponent(key) + "=" + encodeURIComponent(data[key])
);
})
var url_encoded_string = key_value_pairs.join("&");
console.log(url_encoded_string);
You could also send the data using a different format. PHP understands multipart MIME encoding which you can generate with a FormData object.
var form_data = new FormData(document.getElementById("loginform"));
form_data.append("login", "1");
xhr.send(form_data);
If you do this, do not override the Content-Type with:
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
XMLHttpRequest will generate the correct-content type, with the multipart MIME boundary parameter from the FormData object.
You could also encode the data with a different data format, such as JSON:
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));
… but, and this is a big but, PHP does not know how to decode JSON formatted requests and will not automatically populate $_POST.
You would need to change the PHP to read the data:
$json = file_get_contents('php://input')
$data = json_decode($json));
var_dump($data);

Send PHP POST using Javascript AJAX

My data is not inserting into database, I get a blank response from the console log and network. I'm kinda lost my javascript source code is mix with other stack overflow answers as well as my PHP code.
<form id="requestForm">
<input type="text" name="fName" id="name">
<input type="text" name="fAddress" id="address">
<input type="text" name="fComment" id="comment">
<input type="submit" value="Submit" name="nameSubmit">
</form>
<script>
document.querySelector('#requestForm').addEventListener('submit', postRequest);
function postRequest(e){
e.preventDefault();
const params = {
fName: document.querySelector('#name').value,
fAddress: document.querySelector('#address').value,
fComment: document.querySelector('#comment').value,
};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'addRequest.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function(){
console.log(this.responseText);
}
xhr.send(params);
}
</script>
</body>
Here's the PHP code:
require_once 'Database.php';
var_dump($_POST); // returns `array(0) {}`
if (isset($_POST['nameSubmit'])) {
var_dump($_POST); // shows no response
$r = $_POST['fName'];
$o = $_POST['fAddress'];
$p = $_POST['fComment'];
$query = "INSERT INTO user_request(name, address, comment) VALUES(?,?,?)";
$stmt = $db->prepare($query);
$insert = $stmt->execute([$r, $o, $p]);
if($insert){
echo 'Success';
}else{
echo 'Error';
}
}
I believe the post parameter nameSubmit does not exsist.
Use the var_dump() function for dump all $_POST
From my prespective, the only parameter given was
fName
fAddress
fComment
Why not check for request method instead?
This is better than checking if a variable exsisted or not.
You can do the checks for required parameter later after you're sure this is a POST request.
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// Do whatever you want when POST request came in
}
UPDATE :
Here is the answer you wanted!
<form id="requestForm">
<input type="text" name="fName" id="name">
<input type="text" name="fAddress" id="address">
<input type="text" name="fComment" id="comment">
<button onclick="sendData();" type="button">Submit</button>
</form>
<div id="testdiv"></div>
<script>
function sendData(){
var data = new FormData();
data.append('fName', document.getElementById("name").value);
data.append('fAddress', document.getElementById("address").value);
data.append('fComment', document.getElementById("comment").value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test.php', true);
xhr.onload = function () {
if(xhr.status !== 200){
// Server does not return HTTP 200 (OK) response.
// Whatever you wanted to do when server responded with another code than 200 (OK)
return; // return is important because the code below is NOT executed if the response is other than HTTP 200 (OK)
}
// Whatever you wanted to do when server responded with HTTP 200 (OK)
// I've added a DIV with id of testdiv to show the result there
document.getElementById("testdiv").innerHTML = this.responseText;
};
xhr.send(data);
}
</script>
</body>
The PHP code :
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
var_dump($_POST);
}else{
header('HTTP/1.0 403 Forbidden');
}
?>
To add another field, add another data.append function below data var.
The submit button MUST BE CLICKED. To allow the use of enter, add an event listener for it!.
What it looks like on my end : https://image.ibb.co/gfSHZK/image.png
Hope this is the answer you wanted.
Two issues:
1.) Params not sent properly/at all because lack of serialization. When you use form content-type your params object need to be in a particular format name=value&name2=value2. So to facilitate that you need to transform your ojbect using something like:
function getReadyToSend(object) {
var objList = [];
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
objList.push(encodeURI(prop + '=' + object[prop]));
}
}
return objList.join("&");
}
So your sending becomes: xhr.send(getReadyToSend(params));
2) Your php is expecting the submit button to be sent. if (isset($_POST['nameSubmit'])) {
You don't have a variable being sent called nameSubmit you can fix this by either including it or check that each variable is set instead. I would suggest the latter that way you can error handle should 1 or more are not passed.
Suggestion: Update your onload to check status:
if (xhr.status === 200)
{
console.log(xhr.responseText);
}
else if(xhr.status !== 200)
{
console.log('Request failed. Returned status of ', xhr.status);
}
Example fiddle: http://jsfiddle.net/qofrhemp/1/, open network tab and inspect the call you will now see the params in form data for the call that fires when submit clicked.

multipart/form-data possible to send with javascript?

I am sending a file over POST together with text "name" using this form:
<form enctype="multipart/form-data" action="https://site[DOT]net/upload" method="post">
<input id="name" type="text" />
<input id="data" type="file" />
<button type="submit" name="submit" />
</form>
I would like to do the exect same using javascript. In addition I dont want to be redirected. I want to stay on the html page and just show a popup "Upload done". How can I do this in javascript (no jquery)?
EDIT:
I tried this code but the POST is not working:
<script>
function uploader {
var formData = new FormData();
formData.append("name", "Smith");
formData.append("data", fileInputElement.files[0]);
var request = new XMLHttpRequest();
request.open("POST", "https://site[DOT]net/upload");
request.send(formData);
}
</script>
<form>
<input id="name" type="text" />
<input id="data" type="file" />
<button type="submit" name="submit" />
<button onclick="uploader()">Click</button>
</form>
In case any wants to do this with the new fetch instead of xhr this is the equivalent. Also see: How do I POST with multipart form data using fetch?
var form = document.getElementById('formid');
form.onsubmit = async (e) => {
e.preventDefault();
const form = e.currentTarget;
const url = form.action;
try {
const formData = new FormData(form);
const response = await fetch(url, {
method: 'POST',
body: formData
});
console.log(response);
} catch (error) {
console.error(error);
}
}
<form id="formid" enctype="multipart/form-data" action="#" method="post">
<input id="name" type="text" />
<input id="data" type="file" />
<button type="submit" name="submit">Submint</button>
</form>
Uploading the entire form with javascript, including the files, can be done by using the FormData API and XMLHttpRequest
var form = document.getElementById('myForm'); // give the form an ID
var xhr = new XMLHttpRequest(); // create XMLHttpRequest
var data = new FormData(form); // create formData object
xhr.onload = function() {
console.log(this.responseText); // whatever the server returns
}
xhr.open("post", form.action); // open connection
xhr.send(data); // send data
If you need to support IE10 and below, it gets increasingly complicated, and would in some cases require posting through iFrames etc.

Categories

Resources