php / Javascript / Ajax loading content does not work - javascript

I'm trying to load content from a php file which name is "include.php" to a in another php file which name is "index.php". But the loading does not work. The code is as below:
The file: index.php
<header>
<script type="text/javascript">
function load(){
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechage = function (){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById(adiv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'include.php', true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="submit" value="Submit" onclick="load();">
<div id="adiv"></div>
</body>
The File: include.php
<?php
echo 'Hello!';
?>
Thanks.

If what you are doing is the way you describe then this is simpler:
<header>
<?php include("include.php") ?>
</head>
<body>
<input type="submit" value="Submit" onclick="load();">
<div id="adiv"></div>
</body>
If you want to get result from include.php into JavaScript then you'll probably be better using ajax.
By the way, if you are planning a "universal header" for all your PHP files, you don't need to echo it just write it as normal HTML with any necessary PHP tags

Should it not be document.getElementById("adiv").innerHTML = xmlhttp.responseText;? Notice the quotes.

....xmlhttp.onreadystatechage = function (){
if(xmlhttp.readyState == 4 && xmlhttp.st...
Check the spelling onReadyStateChange.

Related

XHR based ajax unable to upload files

I've a pretty simple javascript function which tries to send formdata along with an attached file to a php script. Below is my html and javascript code:
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery AJAX Submit Form</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<form id="form" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<input type="file" name="file" id="file">
<input type="button" onclick="upload()" value="Upload">
</form><span id="msg"></span>
<div id="result"></div>
<script type="text/javascript">
function upload(){
var formData = new FormData();
formData.append("file", document.getElementById("file").files[0]);
var xhttp = new XMLHttpRequest();
document.getElementById("msg").innerHTML = document.getElementById('file').files[0];
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
document.getElementById("msg").innerHTML = this.responseText;
}
};
xhttp.open("POST", "https://localhost/2.php");
xhttp.setRequestHeader("Content-type", "multipart/form-data");
xhttp.send(formData);
}
</script>
</body>
</html>
And below is my php script "2.php":
<?php
error_reporting(E_ALL);
$myfile = fopen("newfile.txt", "w");
fwrite($myfile, $_POST['name'].$_FILES['file']['name']);
fclose($myfile);
echo 'file written';
move_uploaded_file($_FILES['file']['tmp_name'],$_FILES['file']['name']);
echo "success";
?>
The above php script doesn't has any problem because it is able to retrieve the input text as $_POST['name'] and save it in the text file created. Also the script is successfully able to retrieve the file submitted and save it, only when I submit the html form normally without any javascript.
I want to submit both the input field data and selected file via XHR api only and not through fetch api.

Sending data from JavaScript to PHP via XMLHttpRequest

Good day.
I'm trying to send a simple piece of data from one php file (manage.php) to another (view.php).
I cannot send the data via a form, I want to send it via a JS script. Here's my attempt:
var read = function(id) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("id=" + id);
}
In view.php, using $_POST["id"] causes an error stating that the index "id" is undefined.
What's the correct way to send the data? Thank you.
Your input is not complete. So I did the full example below that you can follow. I made a function, named readid(id), doing the same thing as you want. Then I call that function from html, when needed.
<!doctype html>
<html lang="fr">
<head>
<meta charset="iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" charset="iso-8859-1">
function readid(id){
"use strict";
console.log("id=", id)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/cgi-bin/view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 || this.status === 200){
console.log(this.responseText); // echo from php
}
};
xmlhttp.send("id=" + id);
}
</script>
</head>
<body>
<p>This is a test</p>
<input type="button" name="Submit" value="Submit" id="formsubmit" onClick="readid(id)">
</body>
</html>
view.php
<?php
$logFile = "view.log";
$id = $_POST['id'];
file_put_contents($logFile, $id);
echo $id;
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
$.ajax({
type: 'POST',
data: id,
url: 'PATH_TO_VIEW.PHP',
success: function(data) {
//do something
},
error: function(data){
console.log('Something went wrong.');
}
});
});
</script>
</body>
</html>
Now the data in ajax can be collected numerous e.g. serialized and new FormData(form) to quickly name two.

Getting data from Google docs into Javascript

I try to get data from google spreadsheets and everything is allright when I'm testing html page locally. But when I load my html file and javascript file into server nothing works.
Here is the code of html file "page.htm":
<html>
<head>
<title>
</title>
<script type="text/javascript" src="teams.js" >
</script>
</head>
<body
onload= "Data();">
<table>
<form name="Team">
<tr>
<td>
<input size="19" name="tName" readonly >
</td>
</tr>
</form>
</table>
</body>
</html>
And js file "teams.js":
function Data() {
var url="https://docs.google.com/spreadsheets/d/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/pub?&gid=0&range=A1&output=csv";
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status==200){
document.Team.tName.value = xmlhttp.responseText;
}
};
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
Google doc
Tried this on my own server - got a following CORS error on the browser's console:
This means that you cannot directly access the url with your browser, because the Google's server is not sending back a required header field that would allow this.
A way around this is to use an alternative API, that can provide us with JSONP format output for the Google Spreadsheet:
So consider this JavaScript:
function Data(response) {
document.Team.tName.value = response.feed.entry[0].gs$cell.$t;
}
And the following HTML:
<html>
<head>
<title>
</title>
<script type="text/javascript" src="teams.js" >
</script>
</head>
<body>
<table>
<form name="Team">
<tr>
<td>
<input size="19" name="tName" readonly >
</td>
</tr>
</form>
</table>
<script src="https://spreadsheets.google.com/feeds/cells/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/1/public/values?alt=json-in-script&callback=Data&range=A1"></script>
</body>
</html>
And it should work perfectly.
This works as, rather than your won code, the Google's own server calls the Data function with the proper data - a method called JSONP that allows cross-domain data requests. Requesting data from another domain is blocked by default in the browsers. The only exception is the file:// protocol, which allows some requests to any domains, as there is no origin domain to match the rules. This explains why your code worked on the local, but not after it had been uploaded to the server.
When I run the code it works, fills the input with the csv file value. When I try to run the link on How do you Import data from a Google Spreadsheet to Javascript? got cross origin block from my browser.
If you can't run the script below you should try allowing CORS on your browser or perhaps try with ajax.load to get the file.
<html>
<head>
<title>
</title>
<script type="text/javascript">
function Data() {
var url = "https://docs.google.com/spreadsheets/d/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/pub?&gid=0&range=A1&output=csv";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.Team.tName.value = xmlhttp.responseText;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
</script>
</head>
<body onload="Data();">
<table>
<form name="Team">
<tr>
<td>
<input size="19" name="tName" readonly>
</td>
</tr>
</form>
</table>
</body>
You should see it something like:

Problems with nginx server

I have the following code in php:
<html>
<head>
<script stype="text/javascript">
function ventanachat(){
var xmlHttp;
if (window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var fetch_unix_timestamp ="";
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById("ventanachat").innerHTML=xmlHttp.responseText;
setTimeout('ventanachat()',10);
}
}
xmlHttp.open("GET","db.php"+"?t="+timestamp,true);
xmlHttp.send(null);
}
window.onload = function startrefresh(){
setTimeout('ventanachat()',1000);
}
</script>
</head>
<body>
<form action="insert.php" method="GET">
<input type="text" name="mensaje" id="enviachat" >
<input type="submit">
</form>
<div id="ventanachat" style="width:200px;height:200px;border:1px solid black;overflow:hidden;">
<script type="text/javascript">
ventanachat();
</script>
</div>
</body>
</html>
It is a very basic chat page that updates every 1 second. (the insert.php and db.php files are just consultations and are good)
It works perfect in Apache but Nginx does not work me. Why?.
(I speak Spanish, sorry if misspelled. use a translator). Thanks

AJAX won't transfer variable to PHP

I am trying to transfer input from Javascript to PHP with AJAX but the input will not transfer.
Here is my JS code:
<!DOCTYPE html>
<html>
<head>
<style>
div{border:solid;}
div{background-color:blue;}
</style>
</head>
<body>
<div id="comments"> </div>
<br>
<span> Comment: </span> <input id="comment"> <button onclick="getInput()"> Submit Comment </button>
<script>
function getInput(){
var input = document.getElementById("comment").value;
addComment(input);
}
function addComment(input){
var request = new XMLHttpRequest();
request.open("GET","chatroom.php?i="+input,false);
request.send();
}
</script>
</body>
</html>
Here is my PHP Code:
<?php
$input = $_REQUEST["i"];
file_get_contents("chatext.txt",$input);
?>
The PHP code is executed, but the variable is not transferred.
did you mean file_put_contents("chatext.txt", $input)?
php.net/manual/en/function.file-put-contents.php

Categories

Resources