First off, here's my code:
HTML ("formdata-index-test.html"):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Test page</title>
</head>
<body>
<form id="the-form" method="post" action="formdata-validation-test.php">
<input type="text" id="the-text">
<input type="submit" value="Upload">
</form>
<script src="formdata-fields-control-test.js" type="text/javascript"></script>
</body>
</html>
JS ("formdata-fields-control-test.js"):
var form = document.getElementById("the-form");
form.onsubmit = function() {
var q = document.getElementById("the-text").value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200)) {
alert(xhr.responseText);
}
}
xhr.open("POST", "formdata-validation-test.php", false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send("q="+q);
}
PHP ("formdata-validation-test.php"):
<?php
$example = $_POST['q'];
echo $example;
if (empty($example)) {
echo "Empty";
}
?>
Now, at the beginning, I wasn't getting anything as response, but after a few tries and changes in my code, I'm being able to receive that alert in the JS file. The weird thing is that, even receiving the alert, I'm still getting the "Empty" echo when the PHP page is loaded after the form submission. Does anyone know why is it happening? My final goal is just to send the text from the HTML file to the PHP file, and then to database (that is, the "responseText" is not really necessary, and it's here just with test purposes), but apparently, PHP is not really receiving what JS sends, while JS receives what PHP sends. Does it make any sense?
The submit button is clicked and a submit event fires on the form.
The JavaScript is running. It is making an HTTP request to the PHP script with the data in it. Since you have forced it to be a synchronous request (don't do that, it locks up the event loop), the browser waits for the response before continuing. The JS is then processing the response, and alerting the value.
Then the form is submitted. It doesn't have a control with name="q", so for the second request to the PHP script, empty($example) will always be true.
If you want to stop the form being submitted then call preventDefault on the event object.
form.onsubmit = function(event) {
event.preventDefault();
try this :
1) in formdata-fields-control-test.js , make your script as a function :
function testFunction() {
var q = document.getElementById("the-text").value;
var params = "q="+q;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200)) {
alert(xhr.responseText);
}
}
xhr.open("POST", "formdata-validation-test.php", false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
};
2) in formdata-index-test.html , set action to empty and call the javascript function onsubmit :
<form id="the-form" onsubmit="return testFunction()" method="post" action="">
<input type="text" id="the-text">
<input type="submit" value="Upload">
</form>
the issue i think was with the form having an action and a onsubmit function together.
Related
A strange problem has started on a page where the code hasn't been changed. I have stripped things back and have now isolated the issue, but I can't make sense of it.
On this form if I only input the text field, Safari wont send the form (although no errors occur). It does send in Firefox when only the text field is entered.
Safari will send the form if the image field has a file or if I remove the image filed altogether. So for some reason the lack of data in the image field is causing the form to not send in Safari.
It seems to matter that the text field is created by Javascript, if I just make the page with a regular text input to start with the problem doesn't occur.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" language="javascript">
function sendForm(){
var formElement = document.querySelector("#upload");
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "test.php");
request.send(formData);
}
</script>
</head>
<body>
<form name="upload" id="upload" >
<h2>Image</h2>
<input name="image" type="file" />
<p onclick="sendForm()" />SEND</p>
</form>
<script>
for (var f = 0; f < document.forms.length; f++) {
new_input = document.createElement('input');
new_input.type = 'hidden';
new_input.name = 'title';
new_input.value = 'test';
document.forms[f].appendChild(new_input);
}
</script>
</body>
</html>
I am tracking the data sent with:
<?php
$title = $_REQUEST['title'];
$file = 'output.txt';
$current = file_get_contents($file);
file_put_contents($file, $title."\n");
?>
Additionally if request.send(formData); is changed to request.send("test"); then "test" will be sent in all cases, so it appears Safari is having an issue with the FormData object.
I have aso tested this using the fetch() API and the same thing happens.
I have a php file, content.php, that is currently being loaded in the browser:
<html>
<head>
<title>Content</title>
<script src="content.js"></script>
</head>
<body>
<?php
if ( isset($_POST["status"]) && ($_POST["status"] === 1) ) {
?>
Content for users with status 1
<?php
} else {
?>
Content for users with different status
<?php
}
?>
</body>
</html>
What I want to do, is set the
$_POST["status"]
variable from within
content.js
I have thought about using a hidden html form and clicking the submit button through javascript, but that doesn't really seem like an elegant solution.
I have also thought about using an XMLHttpRequest, the problem being that I haven't found a way to send the data to the currently viewed/loading page through an XMLHttpRequest.
I am using no extra libraries, only javascript and php.
Is there a more elegant solution to my problem the a hidden html form?
Seems you need to work with AJAX because you need to execute server side script in hidden manner and update the html.
interface.php has content.js and a div
content.js send ajax post request with status
content.php sends the content according to status
interface.php's div is updated.
Here are the content.js and interface.php
let status = 1;
loadDoc(status);
function loadDoc(status) {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = () => {
if (xhttp.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML =
xhttp.responseText;
}
};
xhttp.open("POST", "content.php", true);
xhttp.send("status=" + status);
}
<html>
<head>
<title>Content</title>
<script src="content.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
And here is your content.php
<?php
if ( isset($_POST["status"]) && ($_POST["status"] === 1) ) {
?>
Content for users with status 1
<?php
} else {
?>
Content for users with different status
<?php
}
?>
Bingo! You set the $_POST["status"] via content.js
POST variables can only be passed in a request header. This means that it has to be either a form submission, as you already know, or an AJAX request. There is no way to have a separate client-side resource supply new information to an existing request.
Hello I have encountered a problem while coding in Javascript and PHP (Ajax non jquery). I am trying to upload a file over Ajax, and handle it in PHP.
This is my code:
index.html
<html>
<head>
<title>PHP AJAX Upload</title>
<script type="text/javascript">
function upload() {
// 1. Create XHR instance - Start
var dat= "bla";
document.getElementById("div2").innerHTML = "working";
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
var rad = document.getElementById('fajl');
var filee = rad.files[0];
var formData = new FormData();
formData.append('rad',filee)
formData.append('var',dat)
xhr.open('POST', 'upload.php');
xhr.send(formData);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
document.getElementById("div2").innerHTML = xhr.responseText;
//alert(xhr.readyState);
//alert(xhr.status);
}
}
}
</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<label>Upload File:</label><br/>
<input name="rad" id="fajl" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" onclick="upload()" />
<div id="div2">
</div>
</form>
</body>
</html>
upload.php
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['rad']['tmp_name'])) {
$sourcePath = $_FILES['rad']['tmp_name'];
$targetPath = "images/".$_FILES['rad']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
echo ("uspjeh<br>");
}}
}
$podatak=$_POST['var'];
echo "$podatak"
?>
Problem is that I dont see PHP script response in my div2 element. Ajax behaves wierd and it puzzles me. I have put JavaScript alert command under xhr.readyState condition (now commented). When I do that then I see the output, but when I close alert dialog, the browser automaticly reloads page and makes the URL like i'm using GET method (i'm using POST) and then server output dissapears. (rad in ?rad=... is the name of my input element)
When I'm not using alert command then I don't see output at all, because page redirects really fast. What am I misiing?
It's because you are using a submit button and that's submitting the form. By default form methods are GET requests. Change to just a button instead:
<input type="button" value="Submit" class="btnSubmit" onclick="upload()" />
The default form action (submitting) is being carried out.
To stop this add return false to your click handler:
onclick="upload(); return false;"
I need to send only 1 variable to my .php file using AJAX (using method POST) and show it (with php). Here is my HTML code:
<script type = "text/javascript">
var XMLHttpRequestObject = false; //LO INICIALIZAMOS A FALSO PARA DESPUES COMPROBAR QUE ESTA CREADO CORRECTAMENTE
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); //PARA INTERNET EXPLORER
}
function irweb(idDiv) {
if (XMLHttpRequestObject) {
var objeto = document.getElementById(idDiv);
nom1="holaaaaaaa";
// var nom1 = document.getElementById('nombre').value;
//var com1 = document.getElementById('comentarios').value;
XMLHttpRequestObject.open("POST", "p2.php?");
XMLHttpRequestObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
objeto.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send("n="+nom1);
}
}
</script>
</head>
<body>
<form method="post" id="formulario">
<input type="submit" value="Enviar" onclick ="irweb('contenedor')" id="enviar"/>
</form>
<div id="contenedor" style="background-color:#99FF66;text-align:center;"></div>
</body>
Here is my PHP code:
<?php
$cabe = <<< 'EOD'
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<head>
</head>
<html>
<body>
<p>hola</p>
</body>
</html>
EOD;
$pasado1=$_POST["n"];
$pasado2=$_POST["c"];
echo "El parametro pasado es -->".$pasado1;
echo "El parametro pasado es -->".$pasado2;
?>
I called some alerts in the JS code, to chek if I get the values correctly, and it works, but when I call the php file, nothing happens
When you click on the submit button, you:
Run the JavaScript
Submit the form
You don't see a result from the JS because the form submits (reloading the page) before the readystate has reached 4.
Stop the form submitting if the JS runs:
onclick="irweb('contenedor'); return false;"
… and fix your server side script so it can handle the POST data if the JS fails for any reason and the form does submit.
Have you tried using jquery? If not, try it for easy coding and maintenance
http://api.jquery.com/jQuery.post/
The ajax post code is simply as below :
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Current Setup
I have an HTML form like so.
<form id="demo-form" action="post-handler.php" method="POST">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething">Update</button>
</form>
I may have many of these forms on a page.
My Question
How do I submit this form asynchronously and not get redirected or refresh the page? I know how to use XMLHttpRequest. The issue I have is retrieving the data from the HTML in javascript to then put into a post request string. Here is the method I'm currently using for my zXMLHttpRequest`'s.
function getHttpRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function demoRequest() {
var request = getHttpRequest();
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
console.log("Response Received");
}
}
request.open("POST","post-handler.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("action=dosomething");
}
So for example, say the javascript method demoRequest() was called when the form's submit button was clicked, how do I access the form's values from this method to then add it to the XMLHttpRequest?
EDIT
Trying to implement a solution from an answer below I have modified my form like so.
<form id="demo-form">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething" onClick="demoRequest()">Update</button>
</form>
However, on clicking the button, it's still trying to redirect me (to where I'm unsure) and my method isn't called?
Button Event Listener
document.getElementById('updateBtn').addEventListener('click', function (evt) {
evt.preventDefault();
// Do something
updateProperties();
return false;
});
The POST string format is the following:
name=value&name2=value2&name3=value3
So you have to grab all names, their values and put them into that format.
You can either iterate all input elements or get specific ones by calling document.getElementById().
Warning: You have to use encodeURIComponent() for all names and especially for the values so that possible & contained in the strings do not break the format.
Example:
var input = document.getElementById("my-input-id");
var inputData = encodeURIComponent(input.value);
request.send("action=dosomething&" + input.name + "=" + inputData);
Another far simpler option would be to use FormData objects. Such an object can hold name and value pairs.
Luckily, we can construct a FormData object from an existing form and we can send it it directly to XMLHttpRequest's method send():
var formData = new FormData( document.getElementById("my-form-id") );
xhr.send(formData);
The ComFreek's answer is correct but a complete example is missing.
Therefore I have wrote an extremely simplified working snippet:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
var xhr = new XMLHttpRequest();
xhr.onload = function(){ alert(xhr.responseText); }
xhr.open(oFormElement.method, oFormElement.getAttribute("action"));
xhr.send(new FormData(oFormElement));
return false;
}
</script>
</head>
<body>
<form method="POST"
action="post-handler.php"
onsubmit="return submitForm(this);" >
<input type="text" value="previousValue" name="name"/>
<input type="submit" value="Update"/>
</form>
</body>
</html>
This snippet is basic and cannot use GET. I have been inspired from the excellent Mozilla Documentation. Have a deeper read of this MDN documentation to do more. See also this answer using formAction.
By the way I have used the following code to submit form in ajax request.
$('form[id=demo-form]').submit(function (event) {
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// fire off the request to specific url
var request = $.ajax({
url : "URL TO POST FORM",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
});
// prevent default posting of form
event.preventDefault();
});
With pure Javascript, you just want something like:
var val = document.getElementById("inputFieldID").value;
You want to compose a data object that has key-value pairs, kind of like
name=John&lastName=Smith&age=3
Then send it with request.send("name=John&lastName=Smith&age=3");
I have had this problem too, I think.
I have a input element with a button. The onclick method of the button uses XMLHTTPRequest to POST a request to the server, all coded in the JavaScript.
When I wrapped the input and the button in a form the form's action property was used. The button was not type=submit which form my reading of HTML standard (https://html.spec.whatwg.org/#attributes-for-form-submission) it should be.
But I solved it by overriding the form.onsubmit method like so:
form.onsubmit = function(E){return false;}
I was using FireFox developer edition and chromium 38.0.2125.111 Ubuntu 14.04 (290379) (64-bit).
function postt(){
var http = new XMLHttpRequest();
var y = document.getElementById("user").value;
var z = document.getElementById("pass").value;
var postdata= "username=y&password=z"; //Probably need the escape method for values here, like you did
http.open("POST", "chat.php", true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", postdata.length);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(postdata);
}
how can I post the values of y and z here from the form