Ajax post xmlhttprequest "processing" - javascript

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!!

Related

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.

Post File to PHP File XMLHttpRequest Object Return Data Javascript

I'm trying to pass an image file using ajax post method to a php file. The script sends the object, but my parser doesn't get the $_FILES["avatar"]["name"] and the tmp_name. Is there a way to send the file via AJAX like a form would do?
My HTML:
<input type="file" id="avatar_file" name="avatar" />
<input type="file" id="title_file" name="title" />
<input name="myBtn" type="submit" id="save_changer" value="Submit Data" onclick="subForm();">
My Javascript:
function subForm(){
var hr = new XMLHttpRequest();
var url = "php_parsers/photo_system.php";
var fn = document.getElementById("avatar_file").files[0];
var formData = new FormData();
formData.append("avatar", fn);
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
alert(fn);
}
}
hr.send(formData);
}
And my PHP Parser (php_parsers/photo_system.php):
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
Remove this line
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
from your code and try again

$_POST not returning a value

I've been searching for an answer to this for several days now, but if I missed the answer in another post, let me know.
I'm trying to get into Ajax, so I have a very simple form in my index.php, with separate php and javascript files:
index.php
<div id="ajax-test">
<form action="ajax/ajax.php" method="POST">
<textarea name="someText" id="some-text" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
main.js:
function getXMLHttpRequestObject() {
var temp = null;
if(window.XMLHttpRequest)
temp = new XMLHttpRequest();
else if(window.ActiveXObject) // used for older versions of IE
temp = new ActiveXObject('MSXML2.XMLHTTP.3.0');
return temp;
}// end getXMLHttpRequestObject()
function loadDoc() {
var ajax = getXMLHttpRequestObject();
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
};
ajax.open("POST", "ajax/ajax.php", true);
ajax.send();
}
ajax.php:
<?php
print_r('\'' . $_POST['someText'] . '\' is what you wrote');
?>
Whenever I try to print, it prints: " '' is what you wrote " - what am I missing/not doing/doing incorrectly that isn't allowing me to access the content of someText? I've changed my naming convention, swapped from single quote to double quote, tried GET instead of POST, but nothing worked.
You can try to set a header request and also put the data inside the send. Here an example as like as-
ajax.open("POST", "ajax/ajax.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send("someText="+document.getElementById('some-text').value);
This is probably beacuse of the error
Undefined index: someText in C:\xampp\htdocs\ssms\sandbox\ajax\ajax.php on line 3
You had a couple of issues with your code which i don't have time to list out now. This should work fine, plus i used the onkeyup() function to display the text live without even clicking on the submit button.
The Index File
<div id="ajax-test">
<form method="POST" onsubmit="return false;">
<textarea onkeyup="loadDoc()" name="someText" id="someText" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
<script type="text/javascript" src="main.js"></script>
The Main Javascript file
function _(x) {
return document.getElementById(x);
}
function ajaxObj ( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
function loadDoc() {
var someText = _("someText").value;
var ajax = ajaxObj("POST", "ajax/ajax.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
}
ajax.send("someText="+someText);
}
The PHP AJAX File
if(isset($_POST['someText'])){
$someText = $_POST['someText'];
echo "\"$someText\"" . ' is what you wrote';
exit();
} else {
echo "An error occured";
exit();
}

error while sending POST request via ajax

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);
}
}
};

I can't find what's wrong with my javascript-ajax-php "upload file" code

this is my first question here (usually I like to find my own ways to solve problems) but I just can't find problem in my file upload code. It's supposed to use AJAX. I simplified everything so it would be easier for you to read. Here is HTML form:
<form id="fileForm" enctype="multipart/form-data" method="POST" action="php/uploadfile.php">
<p>Insert file: <input type="file" id="fileUp" name="fileUp" />
<button type="submit" id="uploadButton" onclick="sendFile();">Upload</button></p>
</form>
Now here goes javascript sendFile() function:
function sendFile()
{
var forma = document.getElementById("fileForm");
var failas = document.getElementById("fileUp");
var uploadButton = document.getElementById("uploadButton");
forma.onsubmit = function(event)
{
event.preventDefault();
}
uploadButton.innerHTML = "Uploading, please wait!";
var newFile = failas.files[0];
var formData = new FormData(forma);
formData.append("fileUp", newFile, newFile.name);
alert(newFile.name);// Here it says filename.jpg it means everything is ok at this stage
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST", "php/uploadfile.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(formData);
}
And php:
<?php
echo var_dump($_FILES);
?>
It should alert contents of $_FILES, but it says array(0){} even if I try $_REQUEST. So, if anyone could suggest what may be wrong, it would be appreciated :]

Categories

Resources