error while sending POST request via ajax - javascript

I want to send a post request and get an echo from a php file. But i cannot find my mistake, always get a notice:undefined index...
please not jquery...
<form id="register" method="POST" action="register-action.php">
<input type="text" name="first_name" placeholder="Onoma"><br>
<input type="text" name="last_name" placeholder="Epitheto"><br>
<input type="text" name="mail" placeholder="E-mail"><br>
<input type="password" name="pass" placeholder="password"><br>
<select name="eidikotita_id">
<?php while($eid = $eidikotites->fetch( PDO::FETCH_ASSOC )):
echo "<option value={$eid['id_eidikotitas']}>{$eid['titlos']}</option>";
endwhile; ?>
</select>
<input type="submit" value="Register"><br>
</form>
///////////////////////////////////////////////////////////////
var mail_input = document.querySelector("#registerinput[name='mail']").value;
alert(mail_input);
document.querySelector("#register input[name='first_name']").focus();
document.querySelector("#register input[name='mail']").onblur = function() {
var request = new XMLHttpRequest();//instantiate an XMLHttpRequest object
request.open("POST", "register-action.php", true);//Specifying the Request
request.setRequestHeader("Content-Type", "text/plain");//POST requests,for example, need a “Content-Type” header
request.send(mail_input);//specify the optional request body. GET requests never have a body, so you should pass null or omit the argument.
};
/////////////////////////////////////////////////////////////////////////////
<?php
echo $_POST['mail'];
?>

Just print_r() POST data to see what is the problem.
xhr.send() should look like this: xhr.send('mail=' + encodeURIComponent(email)) because you want $_POST['mail']. Also there is a problem with your selector which should be "#register input[name='mail']".

document.querySelector("#register input[name='first_name']").focus();
document.querySelector("#register input[name='mail']").onblur = function() {
var mail_input = document.querySelector("#register input[name='mail']").value;
var request = new XMLHttpRequest();//instantiate an XMLHttpRequest object
request.open("GET", "register-action.php?mail="+mail_input, true);//Specifying the Request
request.setRequestHeader("Content-Type", "text/plain");//POST requests,for example, need a “Content-Type” header
request.send(encodeURIComponent(mail_input));//specify the optional request body. GET requests never have a body, so you should pass null or omit the argument.
//////send succcess
if (request.readyState === 4 && request.status === 200) {
request.onreadystatechange = function(){
console.log(request.responseText);
}
}
};

Related

Why is $_FILES[] always empty?

The problem
I'm trying to make an AJAX file uploader with Php and Javascript. The problem I'm having is that in my upload.php script where I'm trying to use the move_uploaded_file function, the $_FILES array is always empty.
Here's what I've tried thus far
Checked file_uploads = On in /etc/php/7.2/apache2/php.ini
Checked the current working directory of uploader.php and upload.php
Checked the file permissions of uploads
Changed the uploads_tmp_dir in /etc/php/7.2/apache2/php.ini
The MWE
Html in uploader.php:
<form class="form" id="upload_form">
<input type="file" name="file_to_upload" id="file_to_upload"><br>
<input class="button" type="submit" value="Upload">
</form>
Javascript in uploader.php:
<script>
var upload_form = document.getElementById('upload_form');
var file_to_upload = document.getElementById('file_to_upload');
upload_form.addEventListener("submit", upload_file);
function upload_file (e) {
e.preventDefault();
var xhr = new XMLHttpRequest()
xhr.open("POST", "upload.php");
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(new FormData(upload_form));
}
</script>
upload.php:
<?php
//$target_path = "uploads/".basename($_FILES["file_to_upload"]["name"]);
$uploaded_file = $_FILES['file_to_upload']['tmp_name'];
var_dump($_FILES); // This is always array(0) { }
if(file_exists($uploadedFile)) {
echo "file uploaded to temp dir";
} else {
echo "file upload failed"; // This is always the outcome
}
//move_uploaded_file($_FILES["file_to_upload"]["tmp_name"], $target_path);
?>
According to the PHP docs, you must specify enctype="multipart/form-data". You must also specify method="post" -- see this answer for an explanation.
So your <form> should read:
<form class="form" id="upload_form" enctype="multipart/form-data" method="post">
In one of my projects using Framework-7. I was doing the same to get file upload form submission using ajax.
Do what #kmoser suggest in his answer but do as below as well.:)
<form class="form" id="upload_form" enctype="multipart/form-data" method="post">
<input class="button" type="submit" id="submission" value="Upload">
Now, my code:
$$('#submission').on('click', function(){
//alert('here');
//var test = $('#upload_form').serializeArray();
var fileInputElement = document.getElementById('file_to_upload');
var formData = new FormData();
formData.append('myfile', fileInputElement.files[0]);
var request = new XMLHttpRequest();
request.open("POST", "https://yourwebsite/upload.php");
request.send(formData);
//console.log(request.response);
request.onreadystatechange = function() {//Call a function when the state changes.
if(request.readyState == 4 && request.status == 200) {
alert("File has been uploaded successfully!");
//console.log('here');
location.reload();
}
}
});
and at last on upload.php file write below code:
if(isset($_FILES['myfile'])) {
//echo "uploaded something";
if($_FILES['myfile']['tmp_name'] != '') {
$tmp_filenm = $_FILES['myfile']['tmp_name'];
$file_name = time()."_".$_FILES['myfile']['name'];
$file_fullpath = $today_dir."/".$file_name;
//echo $file_fullpath;
move_uploaded_file("".$tmp_filenm,"$file_fullpath");
}
}

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.

Javascript xmlhttp send api requests from forms

I have a server running locally which has an in built rest api. To login through this api, we need to send username, password and organization as parameters to url localhost:8090/ehr/api/v1/login via POST method and server returns an auth token as response. when I try to do this directly without user input from form through the following code:
<html>
<body>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=admin&password=admin&organization=123456");
</script>
</body>
</html>
It works perfectly fine and auth token is returned as json, but if I try to do the same through user form input via following code:
<html>
<body>
<form method="POST">
<input type="text" name="username" id="username" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<input type="text" name="organization" id="organization" placeholder="Organization">
<button id="submit" onclick="login()">Let me in!</button>
<br><br>
</form>
<script type="text/javascript">
function login() {
var user=document.getElementById("username").value;
var pass = document.getElementById("password").value;
var org = document.getElementById("organization").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param = "username="+user+"&password="+pass+"&organization="+org;
xhttp.send(param);
}
</script>
</body>
</html>
this code throws error
login.html:26 XHR failed loading: POST "http://localhost:8090/ehr/api/v1/login"
What is wrong with the second code and how to correct it?
send your params in this way
xhttp.send('username=user&password=pass&organization=org');
I figured it out myself, I just removed form tag from html and used simple input tags instead. This solved the problem maybe because forms on submission try to load a new page instead of staying on the same page, but the parameters were intended to get fetched from the original page. Which was not able to happen as new page got loaded every time submit button was clicked.

AJAX Request Body Empty (No jQuery)

I am trying to solve this problem without using jQuery so that I can have a better understanding of how things work.
I am sending an AJAX request to a node server with a JSON object. The server can receive the request and respond but the request body is always empty. I have tried setting the request header to 'application/json' but for some reason this changes the form submission to POST the parameters to the URL, rather than use the Javascript function. If anyone could tell me why that is happening as well it would be much appreciated.
Form
<form onsubmit="sendEmail(); return false;">
<input type="text" name="fromEmail">
<input type="text" name="subject">
<textarea name="message" rows="14"></textarea>
<input type="submit" value="SEND">
</form>
Email Function
function sendEmail() {
var emailContent = JSON.stringify(
{
email: $('input[name=fromEmail]').val(),
subject: $('input[name=subject]').val(),
message: $('textarea[name=message]').val()
}
);
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.open('POST','/message', true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
alert(httpRequest.responseText);
}
}
httpRequest.send(emailContent);
}
Node JS Routing
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// set body parser
app.use(bodyParser.json());
// Process email form
app.post('/message', function(req,res) {
console.log('Request received by email path.');
console.log(req.body);
res.send('{"success": true}')
console.log('Response sent.')
});
I think I understood your problem, what you need is to call the function sendEmail() without doing a postback. Well, for this you will nead a regular html button instead of a form submit. Forms are used to execute server requests to an specific url and generate another postback.
You have two options:
1) Do a client side call using a button and an ajax request (XMLHttpRequest):
<input type="text" name="fromEmail">
<input type="text" name="subject">
<textarea name="message" rows="14"></textarea>
<input type="submit" value="SEND">
<button type="button" onclick="sendEmail()">Send</button>
2) Use a form submit and call the service directly form the form. The parameters will be taken from the form and will be sent in the request:
<form action="/message" method="post">
<input type="text" name="fromEmail">
<input type="text" name="subject">
<textarea name="message" rows="14"></textarea>
<input type="submit" value="SEND">
</form>
Then in the server side you can access the data using the names you gave to the fields:
fromEmail = req["fromEmail"]
If you are trying to send json response, you need to set the content type of response as json.
res.setHeader('Content-Type', 'application/json');
You can try this:
httpRequest.open('POST','/message', true);
httpRequest.setRequestHeader("Content-Type","application/json");
httpRequest.send(emailContent);
Reference:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Ajax post xmlhttprequest "processing"

I've got this code:
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
<html>
<head>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
First Name: <input id="first_name" name="first_name" type="text"> <br><br>
Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>
However, I only get "processing" in the browser when running the code. Is there anything wrong? I am running it on XAMPP, if that might be a part of the problem. Thanks for the help!!

Categories

Resources