I have seen questions and answers regarding this issue. For example How to return a HTML file as the response to a POST request? but am having problems implementing the solutions. Here is a sample of some php code in a directory called websiteIssue that does not work, and I am not sure why.
index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
$page = "";
}
include 'case.php';
?>
case.php
<?php
$testLog = 'testLog.txt';
$fileHandle = fopen('testLog.txt', 'a');
fwrite($fileHandle, '$page = '.$page."\n";
switch($page)
{
case "screen2":
include 'screen2.php';
fwrite($fileHandle, 'including screen2.php'."\n");
break;
default:
include 'screen1.php';
fwrite($fileHandle, 'including screen1.php'."\n");
break;
}
fclose($fileHandle);
?>
screen1.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen1.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen2</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen2.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen2.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen1"})> Screen 2 => Screen1</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
On initial load it works as I expected, the html in screen1.php is shown in the browser, but when the button on the page is pressed the html remains the same, rather than changing to that in screen2.php
The output to testText.log is something like:
$page =
including screen1.php
$page = screen2
including screen2.php
As is might be obvious, I am a newbie to this, and hopefully there is some basic thing I have not done. The browser I am running it on is Firefox. Any help would be much appreciated.
Small note:I retyped the code by hand for this post, and have not run it (the machine running the webserver is not connected to the internet), hopefully there are no syntax errors, but I may have made a typo somewhere.
By including the php file you are responding to the javascript, but you arent actually using that response for anything. If redirecting to that page is what you want, you need to use location.assign on the response. To do that:
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
// Redirects user to response when received.
xmlRequest.onreadystatechange=function{
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
location.assign(xmlRequest.responseText);
}
};
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
Based on the answer given by Felipe Souza I made the following modifications to allow the page to be dynamically modified rather than being a redirect. Thought I would share as it is another solution which some might be interested in.
index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
include 'case.php';
}
else
{
include 'base.php';
}
?>
case.php
<?php
switch($page)
{
case "screen2":
include('screen2.php');
break;
case "screen1":
include('screen1.php');
break;
default:
include('screen1.php');
break;
}
?>
base.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>base.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<div id="container" style="width:100%; height:100%">
<?php
if(!isset($_POST['page']))
{
$page = "";
include 'case.php';
}
?>
</div>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData = new FormData();
xmlRequest.onreadystatechange=function()
{
if(xmlRequest.readyState==4 && xmlRequest.status==200)
{
document.getElementById("container").innerHTML = xmlRequest.responseText;
}
}
for(name in data)
{
formData.append(name, data[name]);
console.log(name + ":" + data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen1.php
<button type"button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen 2</button>
screen2.php
<button type"button" onClick=dataSubmit({page:"screen1"})>Screen 2 => Screen 1</button>
There seem some potential advantages in that the amount of data sent for the new screens is smaller, and (not sure if it is useful) the structure of the website is more disguised. Anyway, it is based on the answer given by Felipe Souza and supplements it (shows a dynamic approach rather than a changing pages one). Just thought I would mention it, if that was what some were looking for.
Related
I had similar code run before but now i've lost it. No matter what I do, it will never run the php code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function kosarica() {
var vrednost = "Itworks!";
var httpr=new XMLHttpRequest();
httpr.open("POST","izpis3.php",true);
httpr.setRequestHeader("Content-type","aplication/x-www-form-urlencode");
httpr.onreadystatechange=function(){
if(httpr.readyState==4 && httpr.status ==200){
document.getElementById("responce").innerHTML=httpr.responseText;
}
httpr.send("vrednost"+vrednost);
}
}
</script>
</head>
<body>
<p id="responce">a</p>
<button onclick="kosarica()">Click me</button>
</body>
</html>
PHP Code:
<?php
echo $_POST['vrednost'];
?>
I know that I can make code for this example all in javascript but I want to run more php code where it access my database.
It does not fail, but it does never happen. You need to move the send() outside the handler.
The content type is wrong.
You need to use an equal sign to make it a variable for PHP.
Please do not use var keyword. Use const for a constant or let for a variable.
function kosarica() {
const vrednost = "Itworks!";
const httpr = new XMLHttpRequest();
httpr.open("POST", "izpis3.php", true);
httpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpr.onreadystatechange = function () {
if (httpr.readyState === 4 && httpr.status === 200) {
document.getElementById("responce").innerHTML = httpr.responseText;
}
}
httpr.send("vrednost=" + vrednost);
}
I'm looking how to submit submit an input field made with JavaScript.
I want to submit the value of the input fields made with JavaScript with the POST method to a file called "home.php". But I didn't find any possible way to do that, I hope someone helps me. I've included the full source code. I'll be really thankful for any help.
Thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="IE=edge" http-equiv="X-UA-Compatible" />
<base target="_parent">
<script>
if (window.parent !== window) {
try {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__;
} catch (error) {
// The above line can throw if we do not have access to the parent frame -- i.e. cross origin
}
}
</script>
<title>Storybook</title>
</head>
<body>
<div id="root"></div>
<div id="error-display"></div>
<script type="text/javascript" src="http://yourjavascript.com/2560291117/preview-0c18dfe69fe4ef4a04bd-bundle.js"></script></body>
</html>
Instead of messing up with POST or GET requests you can just use the built-in document.querySelector('#YourIdHere)
The # sign is important as it means that it's an id.
Also, you can add a submit button and fetch the website using the:
fetch('urlHere', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data)
)
Is that good?
With input fields it looks something like that:
<html>
<body>
<input id='input' type="text" value="">
<button onclick="submit()">Submit!</button>
<p id="title">Your text here!</p>
<script>
function submit() {
const query = document.querySelector('#input').value;
const title = document.getElementById('title');
console.log(query);
console.log(title.innerHTML = query);
}
</script>
</body>
</html>
And using requests:
<html>
<body>
<button onclick="submit()">Submit!</button>
<script>
function submit() {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.response);
};
};
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users');
xhr.send();
};
</script>
</body>
</html>
I'm trying to implement the function of checking if the email is exists by using ajax, but my code works on my mac with MAMP while they don't work on my windows PC with XAMPP. Here is the register.php file:
<!doctype html>
<html lang="en" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script type="text/javascript">
/**
* Created by PC2 on 15/12/2016.
*/
/** Create xmlHttpRequest Object */
function getXmlHttpObject() {
var xmlHttpRequest;
if(window.ActiveXObject){ //if the user's web browser is IE core
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}else{
xmlHttpRequest = new XMLHttpRequest();
}
return xmlHttpRequest;
}
var myXmlHttpRequest = "";
/** Check if the email address is exist or not */
function checkEmail() {
myXmlHttpRequest = getXmlHttpObject();
if(myXmlHttpRequest){
var url = "/Ajax-Check-Username-Clean-Code/Ajax/registerProcess.php";
var data = "email="+$('email').value;
myXmlHttpRequest.open("POST",url,true);
myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
myXmlHttpRequest.onreadystatechange = process; //process is a function
myXmlHttpRequest.send(data);
}else{
window.alert("Create Ajax Engine Fail!");
}
}
/** function to change the visibility of the div */
function process() {
if(myXmlHttpRequest.readyState == 4){
var mes = myXmlHttpRequest.responseText;
var mes_obj = eval("(" + mes + ")");
var mes_status = mes_obj.status;
}else{
window.alert("Error");
}
if(mes_status == "ok"){
$('message').textContent = "ok";
}else if(mes_status == "error"){
$('message').textContent = "Error";
}
}
function $(id) {
return document.getElementById(id);
}
</script>
<title>Check Username</title>
</head>
<body>
<section>
<form class="register-form">
<div class="register">
<h2>Email:</h2><input type="text" id="email" name="email-input" onkeyup="checkEmail();"><div class="text" id = "message"></div>
<h2>Password</h2><input type="password" class="password-input"><br/><br/>
<button class="submit">Sign Up</button>
</div>
</form>
</section>
</body>
</html>
And Here is the PHP file:
<?php
$email = $_POST['email'];
$mes = "";
if ($email == "songtao"){
$mes = '{"status":"error"}';
} else {
$mes = '{"status":"ok"}';
}
echo $mes;
?>
These code works well on my Mac, when I tried to run the code on windows, there is an error said "undefined index" in the php file ( $email = $_POST['email'] ), anyone has any ideas why this happened?
The following code should add 100 to an existing number in a mysql table if the button gets clicked. If I click the button nothing happens, but if I reload the page the function adds 100 to the number. What is wrong with my code?
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
<?php
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
?>
});
</script>
</html>
You cant call PHP code from a jQuery function like that. All the php runs when the page loads and thats it. You can however use jQuery and Ajax to send a message to a php script that processes that message then returns a response. The script can even be in the same actual file like you have (or in a different file altogether) something like this would do:
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
if(isset($_POST['updateTest']){
$val = $_POST['test'];
$id + $_POST['userId'];
// validate inputs and such....
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
// send success or error response...
echo json_encode(['success'=>true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
var count = 100;
var userId = 1;
var dataObject= {updateTest: true, test: 100, userId: 1};
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataObject,
success: function(response) {
if(response.success){
alert('test worked');
}
else{
alert('there was an error')
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</html>
As mentioned by the previous poster PHP is server side and Javascript client side so what is actually happening is the following.
When the page is returned back to the user your piece of javascript just looks like the below..
Your MySQL statement here has executed already it can not interact with client side code in this way
<script>
$("#button").click(function(){
// nothing here.. But your MYSQL statement has executed anyway
});
</script>
I want to make a JS Ajax request but it doesn't work.
I wrote this code:
var i=0;
function send()
{
var request = new XMLHttpRequest();
request.open("GET", 'support.html', true);
request.send(null);
request.onreadystatechange = interpretRequest;
i++;
document.getElementById("debug").innerHTML=document.getElementById("debug").innerHTML+i;
}
function interpretRequest() {
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+"answer received";
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+request.status;
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+request.readyState;
switch (request.readyState) {
// if readyState == 4 and status == 200
case 4:
document.getElementById("Antwort").innerHTML=document.getElementById("Antwort").innerHTML+" answer received and state 4";
if (request.status != 200) {
alert("Error"+request.status);
} else {
var content = request.responseText;
// write content
document.getElementById("content").innerHTML = content;
}
break;
default:
break;
}
}
The function send is called by an intervall every s.I see that this works because
the nummers appears in the debug div. The function interpretRequest is called too. The string "answer received" appears but there is no print out which contains the request.status. In addition case 4 is never entered and the content div stays empty.
The HTML File is:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
<script type="text/javascript" src="code.js"></script>
</head>
<body>
<div id="debug">Debug:</div>
<br /><hr />
<div id="content">HTML:</div>
<br /><hr />
<div id="answer">answer:</div>
</body>
</html>
The support.html is in the same folder and it contains:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>It works It works It works It works It workIt works</h3>
</body>
</html>
request isn't a global, so you can't access it from the interpretRequest function.
Use this instead.