I'm trying to implement the following architecture using example of finding even/odd number. I'm using client as HTML file and web server as PHP.
[ "FindEO.html" ] - The HTML file is shown below:
<!DOCTYPE html>
<html>
<body>
<h3>Check Even/ODD Number</h3>
<form method="get" action="http://192.168.0.103:81/DUNNO/eo.php">
Enter number: <input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>
[ "EO.php" ] - The PHP file is as follows:
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$name = $_GET['fname'];
$num = (int)$name;
if (($num%2)==0) {
echo "$name is Even";
} else {
echo "$name is Odd!";
}
}
?>
When the HTML file is executed, it ask for input as:
After clicking on the submit button.
The PHP page is displayed rather than showing content of the PHP page inside the HTML file.
[ Currently showing (PHP file): ]
[ It should show PHP content in HTML File ]
So, the request is sent from HTML file to PHP server, and instead of getting response from PHP file to HTML file, it is showing directly the PHP file itself.
1) Is this possible to display the expected output. (PHP processed output in HTML file)?
2) Suppose I stored the current PHP code in function as:
<?php
function findeo($num){
if (($num%2)==0) {
echo "$name is Even";
} else {
echo "$name is Odd!";
}
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$name = $_GET['fname'];
$num = (int)$name;
findeo($num);
}
?>
then how to pass parameter (10 or any number to $num variable) and call the findeo() function of the PHP page inside the HTML file?
Someone please help me to implement the client - server architecture or tell me if there as any other way where this architecture can work using HTML as client & PHP as server.
use javascript to send the form to the php file and retrieve the answer.
here is how i would have done it:
function getAnswer(e) {
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://192.168.0.103:81/DUNNO/eo.php', true);
xhr.responseType = 'text';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
document.getElementById('answer').textContent = xhr.response;
}
}
};
xhr.onerror = function() {
document.getElementById('answer').textContent = "Error...";
}
xhr.send(null);
}
<!DOCTYPE html>
<html>
<body>
<h3>Check Even/ODD Number</h3>
<form method="get" onsubmit="getAnswer(event)">
Enter number: <input type="text" name="fname">
<input type="submit">
</form>
<div id="answer"></div>
</body>
</html>
using preventDefault() will stop the page from trying to submit the form, and allow the javascript to perform the request by itself.
also, i added a div to your HTML that will hold the respone given by your PHP file.
PHP cannot modify the content of the page after it has been served to the browser. However this would be trivial with a JavaScript Library such as jQuery. or by using AJAX to call the php script to update an element. There are examples on StackOverFlow like: Change DIV content using ajax, php and jQuery
Related
I have a html form in which I want to save all the entries of all the fields into a file using php.
If I am able to save entries successfully then I want to give popup message saying {bytes} bytes written to file.
If I am not able to write successfully then I want to give popup message saying There was an error writing this file.
And if the user doesn't have write access then it should give popup message - Write access revoked.
I call save.php file from the form action to save all the entries in a file and add do some sort of validations.
Below is my index.php file which has form in it -
<?php
declare(strict_types = 1);
session_start();
require_once 'helpers.php';
if (! check_auth()) {
redirect('login.php');
return;
}
?>
<!doctype html>
<html lang="en">
<head>
<title>Home</title>
</head>
<body>
<div>
<h1>Website Title</h1>
Logout
</div>
<div>
<p>Welcome back, <?= $_SESSION['user_id'] ?>!</p>
</div>
<form action="save.php" method="POST">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" name="submit" value="Save Data">
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</body>
</html>
And below is my save.php file -
<?php
declare(strict_types = 1);
session_start();
require_once 'helpers.php';
if (!check_auth())
{
redirect('login.php');
return;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (!isWriteAccess())
{
echo json_encode(['success' => false, 'message' => 'Write access revoked', ]);
return;
}
// Your code here...
if (isset($_POST['field1']) && isset($_POST['field2']))
{
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
$ret = file_put_contents('mydata.txt', $data, LOCK_EX);
if ($ret === false)
{
die('There was an error writing this file');
}
else
{
echo "$ret bytes written to file";
}
}
else
{
die('no post data to process');
}
}
Problem Statement
As of now whenever I click save button on my form which is in index.php, it just prints everything on my browser as the response and also redirects to save.php but I don't want that. I want to show all messages on popup window but it should stay on same index.php file.
If I am able to write successfully to the file, then I should see some bytes written to the file as a popup but it should stay on index.php file only.
If there is a write access issue then it should show Write access revoked as a popup but it should stay on index.php file only.
How can I make sure that whenever I click save button on my form which is in index.php it should stay on the same page but still do all sorts of validations and save entries in a file?
You already have jquery connected, so use $.ajax() to submit the form like this example or this. In the 'success:' handler the data variable will contain responce from your save.php:
success: function(data) {
$('#result').html(data);
}
therefore you can pop up a window with this results. Something like that in your index.php:
<script>
$(function() {
//This submits a form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
var method = form.attr('method');
$.ajax({
type: method, // "POST"
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
alert(data); // show response from the php script.
}
});
});
</script>
PS: You can easily get answer to your question by yourself, such questions was answered here a lot. All trick is to add site:stackoverflow.com to your request in Google.
I am trying to make a ReactJS application which needs to communicate to PHP.
I could to use nodeJS but I chose PHP because I learned it some years ago and don't want to forget it.
So, what should happen in my app:
When user submits submit button(which is also rendered in render() ),instead of redirecting to php file, app will send ajax request to the external php file. PHP file should get input's value.
but php shows such warnings in console when I remove if(isset()) from the file.
Notice: Undefined index: search in C:\xampp\htdocs\ReactStudy\travelReduxApp\public\server\itemList.php on line 13
These are my codes
index.js
import ajaxRequest from './ajax';
console.log(store);
setTimeout(function(){
document.getElementById('AppName').classList.add('visible');
},300);
class App extends React.Component{
submitForm = (e)=>{
e.preventDefault();
//console.log(this.refs.search.value);
const value= this.refs.search.value;
ajaxRequest(e,value);
}
render(){
return(
<div>
<section id="Search">
<form id="Search" data-object="form" method="GET" onSubmit={this.submitForm}>
<input ref={'search'} placeholder="search country, attraction names" type="text" name="search"/>
<button type="submit">SEARCH</button>
</form>
</section>
<ItemList/>
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('App')
)
ajax.js
export default function ajaxRequest(e,value){
let xhr = new XMLHttpRequest();
switch(e.type){
case 'submit':
xhr.open('get','//localhost:80/ReactStudy/travelReduxApp/public/server/search.php?'+value,true);
xhr.onreadystatechange = function(data){
switch(xhr.status){
case 200:
const text = xhr.responseText;
console.log(text);
}
}
}
xhr.send();
}
search.php
<?php
header('Access-Control-Allow-Origin:* ');
/*shows warning without isset*/
/*$form = $_GET["search"];
echo $form;*/
/*with isset shows not found*/
if(isset($_GET["search"])){
$form = $_GET["search"];
echo $form;
}else{
echo "not found";
}
?>
could please someone find or teach me why my php can't find input tag with name attribute's value search?
the input tag is already rendered into the document when php is called. What am I missing?
I am using webpack and bundle.js is included on the bottom of the tag.
edited my code. I am using GET in my code and I don't know why I wrote POST here. So, forget it. I am using $_GET in my php code. Pardon me.
The only thing your Ajax is sending is this.refs.search.value - not the name "search" / not url encoded / not multi-part encoded. Indeed, you seem to have invented your own encoding system.
Try:
xhr.open('get','//localhost:80/ReactStudy/travelReduxApp/public/server/search.php?search=' + value,true);
in Ajax.js
<?php
header('Access-Control-Allow-Origin:* ');
/*shows warning without isset*/
/*$form = $_GET["search"];
echo $form;*/
/*with isset shows not found*/
if(isset($_POST["search"])){
$form = $_GET["search"];
echo $form;
}else{
echo "not found";`ghd`
}
?>
Help me please. Where is my mistake ? I have many XML files on the IIS server. After click button link to XML come in JS file. JS send link to PHP file. PHP must show save dialog to save this link. See code:
JS:
function showAl(url)
{
alert(url);
var ajax = getRequest();
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
...
}
}
ajax.open("POST", "/do_query.php", true);
var data = 'info='+url;
ajax.send(data);
}
PHP:
<?php
if (isset($_POST['info']))
{
$info = $_POST['info'];
header('Content-Type: application/xml;');
header('Content-Disposition: attachment; filename=file.xml;');
readfile(str_replace(" ", "%20", $info), false);
}
?>
Thank's in advance !
Three simple ways to download a file:
Good old form
<form id="the-form" action="/do_query.php" method="post">
<input type="hidden" name="info" value="test">
<input type="Submit" value="Download with regular form">
</form>
Submit good old form with JavaScript
<script type="text/javascript">
function download(){
document.getElementById("the-form").submit();
}
</script>
<input type="Submit" value="Download with JavaScript" onclick="download()">
Switch to GET (requires changes to do_query.php):
Download with link
The problem with AJAX is that it runs on current (HTML) page. It can manipulate the page HTML or redirect to another location but it cannot send a custom HTTP response.
You cannot prompt a user to save a file when you are using AJAX, you will need to direct the browser window to the URL of the file to download. This also means you will need to use the GET method instead of the POST method to transfer the file.
Try this:
JS:
function showAl(url)
{
window.location.href = '/do_query.php?info=' + url;
}
PHP:
if (isset($_GET['info']))
{
$info = $_GET['info'];
// ...
This should prompt the user to download the file.
I am calling a very simple PHP page with some equally simple AJAX, but the call always returns nothing, even though the PHP is fine. That is, you can go to the URL of the PHP page and see that it echoes "Hello World" but when it is called with JS, it returns nothing.
Below is the HTML Page with the Javascript:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......<br />
Enter your email: <input id="email" type="text" />
<input type="button" onclick="setXMLHttpRequest()" value="Go!" />
<script type='text/javascript'/>
var http;
function setXMLHttpRequest()
{
if(window.XMLHttpRequest)
http = new XMLHttpRequest();
else if(window.ActiveXObject)
http = new ActiveXObject("Microsoft.XMLHTTP");
url = "http://www.convolutedconstruct.com /Ajax/checkemail.php?email=" +
document.getElementById('email').value;
http.onreadystatechange = display;
http.open("GET", url, true);
http.send(null);
}
function display()
{
if (http.readyState == 4)
{
infostr = http.responseText;
alert("From the PHP: " + infostr);
}
}
</script></body></html>
Here is the content of the PHP page
Click here for the live PHP page
<?php
$email = $_GET['email'];
echo "Hello World!";
?>
Why does this return nothing to the JS, even though the PHP page echoes the text correctly?
As has been suggested above, AJAX request will only work usually when both the caller and called are on same domain, You have to ensure that your html code, which contains the javascript, resides on same domain http://www.convolutedconstruct.com.
If that is not the case you can use CORS to allow your ajax to receive input from your php page by sending this header in your php output
<?php
header("Access-Control-Allow-Origin: *");
//rest of your code
?>
See: http://enable-cors.org/
i dont like using the XMLHTTP request. instead i use jQuery's method $.ajax({}); method. it always works for me!
$.ajax({
type: "POST", // or 'GET'
url: "your-url.php", // url that you are passing the data to
data: {
dataName: 'data to pass' // string, variable, object, array, etc
},
success: function(output) { // output is what the url is 'echoing' back to the jQuery
// do something when the ajax method is complete.
}
});
dont forget to import the jQuery source code - http://code.jquery.com/jquery-1.7.2.min.js
these are the most common of the components that are used in ajax.
I'll be glad to help you out some more if you would like it.
If you want to know more just check the documentation on it: http://api.jquery.com/jQuery.ajax/
Is it possible to trigger a PHP function by just clicking a link? Or should I stick with the form submit method? If clicking the link will work, where should the link refer to?
Here is a sample code:
<?php
session_start();
function listMe($username){
$username = mysql_real_escape_string($username);
$query = mysql_query("INSERT INTO List (Usernames) VALUES ('$username')") or die(mysql_error());
}
?>
<html>
<head>
<title>SAMPLE</title>
</head>
<body>
Add my username to the list
<?php
listMe($_SESSION['Username']);
?>
</body>
</html>
Maybe someone can point me in the right direction. Thanks!
You can do this by means of loading the entire page over again by the use of form submission, or by loading specific page contents directly into the page without needing to go from page to page. The second method is called "AJAX" (Asynchoronous Javascript and XML). Here are two examples, one of each specified.
Form submission approach
form.php
<?php
function get_users(){
}
if(isset($_GET['get_users']))
{
get_users();
}
?>
...
<form method="get">
<input type="hidden" name="get_users">
<input type="submit">
</form>
AJAX approach
ajax_file.php
<?php
function call_me(){
// your php code
}
call_me();
?>
form.html
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
// do something if the page loaded successfully
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
click to call function
</body>
</html>
HTML
list me
PHP
<?php
if (isset($_GET['list_me'])) listMe();
(EDIT although this works, it's a bad idea as it is. One should never read from $_GET without sanitising it first)
You can pass it as a query parameter of the link.
http://example.com/?command=listMe&username=tom
However that way everybody will be able to run the function by loading that URL
List me
and in the PHP
<?php
if( isset($_GET['list_me']) && isset($_SESSION['Username'] ) ){
listMe( $_SESSION['Username'] );
}
?>
To trigger a function on link click with php the only way I know would be to append a param in the url of the link and then listen for that
Add my username to the list
Then check for link
if (isset($_GET['function'])){
runFunction();
}
This is because php is a server side technology if you want to fire something without refreshing the page you would need to look at something like javascript
I found this code in a plugin, they have user a foreach look to trigger the action:
$actions = unset($meta[$key]);
foreach ( $actions as $action => $value ) {
echo '<li>' . '<i class="fa fa-times"></i></li>';
}