Getting undefined array key when passing data with XMLHttpRequest - javascript

I'm trying to pass a long formatted text string to a php process to save to a file. I am use the POST method as the string can be quite long. It seems to run thro the process and gives back the message 'File saved' but with the error message 'Undefined Array Key "data"' on line 2 of the php code. The file does not get saved and no data is being sent across from the XMLHttpRequest in the previous function.
My code is:- This gets 'str' from the previous function and is formatted correctly.
function getGame(str){
//Sends data to the php process "saveGame.php".
var data = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send(data);
}
it then goes the the 'saveGame.php' where the problem occurs on line 2.
<?php
$outputString = $_POST["data"];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
fwrite($fp, $outputString);
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
$message = "File saved!";
}
fclose($fp);
echo $message;
?>
I think my code of the process is okay but there is a problem with passing the "data" variable and I not sure what it is.
I tested the file saving process. I put a dummy string as a value of 'outputString' and it saved it. When I went back and used the current code the file was overwritten and was blank, indicating it had saved a blank string. So it seems no data is been passed to saveTeams.php although the saving of the file works.
I have got a reproducible example below. If you use it with the saveTeams.php file and a file to attempt to save the data to it should display the error I get in an alert drop down.
<!DOCTYPE html>
<head>
<title>Test program</title>
<script language="javascript">
function formatOutput() {
// lots of formatting goes on here
var formattedText = "This is a test"; //test data
getGame(formattedText);
}
function getGame(str){
//Sends data to the php process "save Game".
var data = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send(data);
}
</script>
</head>
<body>
<table width="1000" align="center" border="0">
<br />
<tr>
<td width="500"align="center" colspan="3" <button onclick="formatOutput()"/>Click on me</td>
</tr>
</table>
</body>
</html>
Hope this okay. I'm a bit new to this.

You are missing a post key
try changing this line to
var data = 'data='+str;

Related

XMLhttprequest.send() doesn't send variables to PHP

I have this code.
JAVASCRIPT
function removeAndReplace(id, sezione){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
}
}
xhttp.open("POST", "removeAndReplace.php", true);
xhttp.send("id=" + id + "&sezione=" + sezione);
}
PHP
print_r($_POST);
$id = $_POST['id'];
$sezione = $_POST['sezione'];
.
.
.
HTML
<input type="button" value="Elimina" class="btn_elimina" onClick="removeAndReplace(1, 'Shopping')">
I want to call a PHP function after the button click so I read that the better way is to use AJAX.
Firefox and Chrome return this error message:
Array
(
)
Notice: Undefined index: id in C:\pweb\tools\xampp\htdocs\Bazaar\php\removeAndReplace.php on line 6
Notice: Undefined index: sezione in C:\pweb\tools\xampp\htdocs\Bazaar\php\removeAndReplace.php on line 7
Line 6 is: $id = $_POST['id'];
Line 7 is: $sezione = $_POST['sezione'];
Where am I going wrong?
You are dumping your data into the request body without telling the server how it is formatted.
Since PHP doesn't know you have sent it data in an encoding it understands, it ignores the request body.
You need to add:
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
… before you send the request.
Aside
While your hard coded data is free of special characters, it is best practice to encode your data. This will save you headaches in the future:
xhttp.send("id=" + encodeURIComponent(id) + "&sezione=" + encodeURIComponent(sezione));
You can save yourself the trouble of manually encoding the data and having to set your own content-type by using the FormData API:
var data = new FormData();
data.append("id", id);
data.append("sezione", sezione);
xhttp.open("POST", "removeAndReplace.php", true);
xhttp.send(data);

Returning value to Javascript from PHP called from XMLHttpRequest

I am attempting to add an "Upload Image" feature to my AjaxChat window. The upload to the server works great, but now I need to be able to return the tmp_name/location of the file that was uploaded. In my Javascript I have the following (main) code (some setup code has been omitted because it is unnecessary -- The upload works as expected):
// Set up request
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'sites/all/modules/ajaxchat/upload.php', true);
// Set up handler for when request finishes
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = 'Upload';
} else {
alert('An error occurred!');
}
};
// Send data
xhr.send(formData);
My PHP code ("upload.php") is as follows:
<?php
$valid_file = true;
echo '<script type="text/javascript">alert("PHP Code Reached");</script>';
if($_FILES['photo']['name']) {
//if no errors...
if(!$_FILES['photo']['error']) {
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) { //can't be larger than 1 MB
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
exit("$message");
}
//if the file has passed the test
if($valid_file) {
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], '/var/www/html/images'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
exit("$message");
}
}
//if there is an error...
else {
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
exit("$message");
}
}
?>
I can tell my PHP code is being run because the image uploads to the server. However, I read that I could generate a Javascript "alert" popup from within the PHP using the following code:
echo '<script type="text/javascript">alert("PHP Code Reached");</script>';
But the above line does not seem to be doing anything. Is this expected since I'm using an XMLHttpRequest, rather than running the PHP directly?
Ultimately my goal is to pass the name of the uploaded file back to the Javascript that called the PHP so that I can create the image url, put it in img tags, and send it to the chat window using ajaxChat.insertText() and ajaxChat.sendMessage(). I'm not sure if this is possible the way I'm running my PHP, though. How would one go about doing this?
When you use XMLHttpRequest, the output of the server script is in the responseText of the object. So you can do:
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = xhr.responseText;
} else {
alert('An error occurred!');
}
};
If you want to send back multiple pieces of information, such as an informative message and the name of the file, you can use JSON to encode an associative array, which will become a Javascript object when you parse it.

How to load data from an XML file using php to show it in an html page with javascript

I'm doing an assigment for my programming class. I need to show a table with two columns (name and lastname) of a list of friends. This data is stored in a XML file like this:
<?xml version='1.0' standalone='yes'?>
<amigos>
<amigo>
<nombre>Alejandra</nombre>
<apellido>Ponce</apellido>
</amigo>
<amigo>
<nombre>Dalia</nombre>
<apellido>Gordon</apellido>
</amigo>
I retrieve this data with php, like this:
<table width="200" border="1">
<tr align="center">
<td>NOMBRE</td>
<td>APELLIDO</td>
</tr>
<?php
$amigos = simplexml_load_file('listaamigos.xml');
foreach ($amigos->amigo as $amigo) {
echo '<tr>';
echo '<td>',$amigo->nombre,'</td>';
echo '<td>',$amigo->apellido,'</td>';
echo '</tr>';
}
?>
I call this php file with a function written in javascript language. I'm using ajax for this homework. My javascript file is the one I'm showing below:
var xmlHttp;
function createXmlHttpRequestObject() {
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)
{
xmlHttp=false;
}
}
else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e)
{
xmlHttp=false;
}
}
if(!xmlHttp)
alert('Can't connect to the host');
else
return xmlHttp;
}
function cargarAmigos(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function cargar(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function procesarEventos()
{
if(xmlHttp.readyState == 4)
{
document.getElementById("listaAmigos").innerHTML= xmlHttp.responseText;
}
}
I use this javascript file in a html file. I call the function cargar () in the button's onclick event, like this:
<body>
<div id="listaAmigos" >
Lista amigos
</div>
<button onclick="cargarAmigos('procedimiento.php');">Lista Amigos Ajax</button>
</body>
The problem is that the code is not working. I mean that the names are not displaying at all in the table. Actually the table does not appear.
I'm pretty sure that the error is not in the code because it was working last week and I haven't changed the code since then. But today I loaded the html page just for "fun" and it wasn't showing my list of friends.
So I decided to open another project with uses the same algorithm and this one is not working too. I've checked that all the files are in the same folder. I've checked my xammp server and it's apache and mysql services are on. I have no idea what "thing" I could have done to cause this problem.
Any help will be really appreciated.
It looks like you should escape the ' character in this line:
alert('Can't connect to the host');
i.e. rewrite it like
alert("Can't connect to the host");
You can see that there's an error even just by looking at the formatting on Stack Overflow :)
Please refer to this question for the details on why it's working like that: When to use double or single quotes in JavaScript?

Trouble receiving Javascript variable when sent to PHP

Problem: Trouble receiving what is being sent to my PHP document.
Javascript:
$('#form_id').submit(function(event){
event.preventDefault();
event.stopPropagation();
var message;
var myRegExp = validation stuff
var urlToValidate = document.getElementById("url").value;
if (!myRegExp.test(urlToValidate)){
}else{
var code = (urlToValidate).slice(-22)
var request = new XMLHttpRequest();
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if (this.status ==200){
console.log (this.status);
}else{
console.log('Server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'php/submit.php', true);
request.setRequestHeader('Content-Type', 'text/plain');
request.send("code=" + code);
}
});
Then I'm using this code on my php/submit.php:
if (!empty($_POST['code'])) {
$code = $_POST['code'];
echo $code;
};
I feel like I'm not using the right tag names for PHP because I'm new to all of this. I'll note that I'm using form id but getting the value from an input.
Ramblings
I'm trying to send a user input that has been validated and sliced to mySQL database.
I achieved the string I wanted with javascript and passed it to a variable.
I'm trying to send it to a separate php file in another folder with a request.send(the_javaS_variable).
Now in the console I can see the variable holds the correct text value and I see it sending with state 4 and 200.
But it never shows up on the submit.php page.
try this and remove the console.log()
$('#form_id').submit(function(event){
var myRegExp = validation stuff
var urlToValidate = document.getElementById("url").value;
if (!myRegExp.test(urlToValidate)){
// failed
}else{
var code = 'code='+(urlToValidate).slice(-22);
$.post('php/submit.php', code, function() {
// success stuff
});
}
return false;
});

Ajax: bulk url list in textarea sending requests one after another and display answers repetitive

I want to input a bulk list of urls in a textarea (each line contains 1 url). After submitting the form, the ajax should get one url, doing php stuff with this url, sending the result back, take another url, do the same and repeat. While the hole thing is working there should be displayed a loading circle ("ajax-loader.gif") and the results should be displayed one after another, like:
[Submit] -> loading -> result 1st-url -> loading -> add result 2nd-url one line under result 1st-url -> loading -> add result 3rd-url one line under result 2nd-url -> ...
I'm doing this whole ajax/js stuff since yesterday - so i'm not very experienced in that way - the php is working with no errors. my main problem is the js/ajax request; how to recieve the result, doing stuff with it,.. This is what i've written so far:
js/ajax (w.o. jquery cause i dont like the notation):
function send (){
var url = document.getElementById('comment').value.split('\n'); //split input from textarea in array
document.getElementById("load").innerHTML='<img src="ajax-loader.gif" />';
for(var i=0;i<url.length;i++) {
http = new XMLHttpRequest();
http.open("POST", "check.php", true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http.send("name=" + url[i]);
http.onreadystatechange=function() {
if (http.readyState == 4) {
document.getElementById("result").innerHTML=http.responseText;
}
}
}
}
html:
<form method="post" action="" name="Formular">
<textarea cols="100" rows="10" id="comment"></textarea><br/>
<input type="button" value="Absenden" onClick="send()">
</form>
<div id="load"></div>
<div id="result"></div>
php:
<?php
$url = $_POST['name']; //get url
..do funky stuff..
echo $result; //result is a simple string if an element on that url exists
?>
What you need to do is make your ajax function recursive, eg on completion, it calls its self, rather than using a loop.
Here is a full example, contained in a single php file, called ajax-example.php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
sleep(1);
echo $_POST['name'];
die();
}
?>
<html>
<head></head>
<body>
<div id="load">doin nothin</div>
<textarea name="n" id="comment" cols="30" rows="10"></textarea>
<br/>
<button onclick="send()">send</button>
<div id="result"></div>
<script type="application/javascript">
function send (){
var url = document.getElementById('comment').value.split('\n'); //split input from textarea in array
var current = 0;
var total = url.length;
document.getElementById("load").innerHTML='loading';//'<img src="ajax-loader.gif" />';
//call ajax for 1st time
ajax();
function ajax(){
//if there are urls left to process
if(current < total){
var http = new XMLHttpRequest();
http.open("POST", "/ajax-example.php", true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http.send("name=" + url[current]);
//increment current marker
current++;
http.onreadystatechange=function() {
if (http.readyState == 4) {
var res = document.getElementById("result");
res.innerHTML=res.innerHTML + http.responseText +"</br>";
//recursive call
ajax();
}
}
}else{
//we are done, remove the loading img
document.getElementById("load").innerHTML='finished';
}
}
}
</script>
</body>
</html>
Just to add, dont discount jQuery just because you dont like the syntax, it can make your life a lot easier for non trivial dom manipulation

Categories