Ajax doesn't send variables to PHP by POST - javascript

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

Related

When one div loads, the other div is deleted

Click here: henriquecosta.kdhost.eu.org, type the number 00008513 and choose a radio button and enter, then choose any 8-digit number and type. This part is working wonderfully after so much sacrifice for me, I'm not a programmer. The problem is that when another div is loaded, the previous one is deleted. I need all divs to remain on the page, in all it will be 40 divs. Yesterday I could not resolve with the localstorage, I think it is the solution, after that the script will be finished. Well, I'm happy with what I got so far. If anyone has any tips to give me, I'll be very grateful! Thank you.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<script>
var form = document.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault(); // <--- isto pára o envio da form
var url = this.action; // <--- o url que processa a form
var formData = new FormData(this); // <--- os dados da form
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.onload = function() {
if (ajax.status == 200) {
var dados = JSON.parse(ajax.responseText);
alert('Dados enviados:\n' + JSON.stringify(dados, null, 4));
} else {
alert('Algo falhou...');
}
};
ajax.send(formData);
});
</script>
<form action="index.php">
Cartao:<input size="7" name="cartao" value="" required="" pattern="[0-9]{8}" type="text">
<input value="01" name="armario" type="radio" />01
<input value="02" name="armario" type="radio" />02
<input value="03" name="armario" type="radio" />03
<button type="submit">Enviar</button>
</form>
<table width=100% border=1>
<tbody>
<tr align=center valign="middle">
<td width=33%><div id="01"></div></td>
<td width=33%><div id="02"></div></td>
<td width=33%><div id="03"></div></td>
</tr>
</tbody>
</table>
<?php
if (isset($_GET['cartao'])):
$radioValue = $_GET['armario'];
$radiovalor = '"'.$radioValue.'"';
$file = 'banco.txt';
$searchfor = $_GET['cartao'];
//header('Content-Type: text/plain');
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)):
json_encode($matches[0]);
$resultado = str_replace(array('"',' \r','[', ']'), '', htmlspecialchars(json_encode($matches[0]), ENT_NOQUOTES));
else:
$resultado = $_GET['cartao'];
endif;
else:
echo '';
endif;
// file_exists
if (isset($_GET['cartao'])) {
$path = './fotos/';
$recebe = $_GET['cartao'];
$img = $path.$recebe.".jpg";
if (file_exists($img)) {
$foto = '"<img width=80 height=80 src="'.$img.'">'; // existe
} else { $foto = ' <img width=80 height=80 src="./fotos/ausente.jpg">'; // não existe
}
}
?>
<script>
var x = '<?php echo $resultado, $foto; ?>';
var z = '<?php echo $radioValue; ?>';
document.getElementById(z).innerHTML += x;
</script>
</body>
</html>
There are several problems in your code which you are probably not aware of.
First of all, your whole page is reloaded everytime you click the "Enviar" button, because your javascript does not correctly prevent the default action.
To accomplish this, return false at the end of the function:
var form = document.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault(); // <--- isto pára o envio da form
var url = this.action; // <--- o url que processa a form
var formData = new FormData(this); // <--- os dados da form
var ajax = new XMLHttpRequest();
ajax.open("POST", url, true);
ajax.onload = function() {
if (ajax.status == 200) {
var dados = JSON.parse(ajax.responseText);
alert('Dados enviados:\n' + JSON.stringify(dados, null, 4));
} else {
alert('Algo falhou...');
}
};
ajax.send(formData);
return false;
});
By doing this, the whole page will not be reloaded.
Secondly, your server always returns a full html page, instead of differentiating, whether the url has been accessed by opening the page for the first time or if it received a request from your script.
If isset($_POST['cartao'] is true, than the request came from your javascript and you should return a JSON object containing the relevant data and build the html in your javascript and append it to your table.
I know that this all sounds a bit confusing if you are not a programmer but I hope I could point you in the right direction.
Once you return a JSON object from your server, I am happy to help you to render HTML from it in javascript.

Unable to receive something in PHP from XMLHttpRequest's "POST"

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.

Ajax acting as GET method even though is POST method

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;"

Ajax won't Display on web page

I am currently trying to use a Ajax in netbeans using JavaScript and PHP file. The following code I should click the button and the contents of the php fill should appear but it doesn't. When I use firebug in firefox the response shows the full php file has returned but will not display on webpage. Why???
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttp() {
var xmlHttp
try {
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
My PHP file is
<?php
echo "This is a php response to your request!!!!!!";
?>
Apart from the fact that HTML code is barely decent, why not use jQuery?
<button id="get" onClick="return false;">jQuery get</button>
<div id="result"></div>
<script type="text/javascript">
$("#get").click(function() {
$.get( "ajax.php", function( data ) {
$( "#result" ).html( data );
});
});
</script>
PHP is server side and is not made to be run on the client side. Your response should come from a URL and not the contents of a file. Ensuring that your response contains on HTML and not PHP should lead you to your solution.
Try replacing your PHP file with
<p>This is a php response to your request!!!!!!</p>
If this enables you to show your content, you have your problem and solution.

Reading a response in javascript from JSP

I am new in learning AJAX and stuck in the first program. Tried to debug but unable to do so.
Below is my code snippet
----------input-ajax.html-------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HTML PAGE</title>
<script type="text/javascript">
var request=null;
function createRequest(){
try{
request= new XMLHttpRequest();
)catch(e){
try{
request=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request=null;
}
}
}
if(request==null){
alert("Error Creating Request Object");
}
}
function getName(){
alert("getname called");
createRequest();
var url = "showName-ajax.jsp";
request.open("POST",url,true);
alert("before");
request.onreadystatechange = updatePage;
alert("after");
request.send(null);
}
function updatePage(){
//var newName= request.getResponseHeader("r1");
var newName= request.responseText;
var name1 = document.getElementById("name");
replaceText(name1,newName);
}
function replaceText(el, text) {
if (el != null) {
clearText(el);
var newNode = document.createTextNode(text);
el.appendChild(newNode);
}
}
function clearText(el) {
if (el != null) {
if (el.childNodes) {
for (var i = 0; i < el.childNodes.length; i++) {
var childNode = el.childNodes[i];
el.removeChild(childNode);
}
}
}
}
</script>
</head>
<body>
<h1>WELCOME <span id="name"> GUEST</span></h1>
<form method="POST">
<input type="text" name="t1">
<input type="button" value="Show Name" onclick="getName();"/>
</form>
</body>
</html>
----------showName-ajax.jsp------------
<%
String s1=request.getParameter("t1");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(s1); // Write response body.
%>
But When I run the program (click on the button) nothing happens. Even the alert message that getName function is called does not appear. PLEASE HELP!!!!
Typo:
)catch(e){
should be
}catch(e){
This would show up as an error in the console of your browser. Be sure to always check that first if things don't work like they should.
You have a ) instead of a } here:
try{
request= new XMLHttpRequest();
)catch(e){
So your function never gets defined.
change )catch(e){ to }catch(e){
but
why are you creating request object everytime on button click?
you just need to call "createRequest()" only once on page load event.

Categories