I am confused about my homework requirements: we need to put JS, HTML and PHP code in the same file xxx.php.
There is a form in the HTML, and once I submit the form, I need to send a request (XMLHTTPRequest) to myPHP.php with the form inputs (using POST to transfer the form data PHP). The PHP file will retrieve the form inputs, reformat it to the syntax of the API and send it to the Google API to get JSON object.
I am a beginner of PHP and JS, and I don't know how to combine them in the same file and do the homework based on the requirements. Like, how to send the JSON object obtained in PHP to Javascript.
Here is framework of my code (myPHP.php):
<html>
<head>
<script type="text/javascript">
// show the result
function show() {
var xmlhttpreq = new XMLHttpRequest();
var keyword = document.getElementById("keyword").value;
var post_data = "keyword=" + keyword;
xmlhttpreq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
createTable(jsonObj);
}
};
xmlhttpreq.open("POST", "myPHP.php", true);
xmlhttpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttpreq.send(post_data);
}
function createTable(object) {
var out = "xxx";
document.getElementById("display").innerHTML = out;
}
</script>
</head>
<body>
<div id="display"></div>
<form action="myPHP.php" name="myForm" method="POST">
<b>Keyword </b><input type="text" id="keyword" name="keyword">
<br>
<button type="submit" onclick="show()" name="search">Search</button>
</form>
<?php
if (isset($_POST["search"])) {
// extract the form data
$keyword = $_POST["keyword"];
// geocode the address
$location = urlencode($location);
// google map geocode api url
$url = "xxxxxxxx";
$res_json = file_get_contents($url);
echo $res_json;
}
?>
</body>
</html>
You can try something like this:
<?php
if (isset($_POST["search"])) {
// extract the form data
$keyword = $_POST["keyword"];
// geocode the address
$location = urlencode($location);
// google map geocode api url
$url = "xxxxxxxx";
echo file_get_contents($url);
} else {
echo '<html>
<head>
<script type="text/javascript">
// show the result
function show() {
var xmlhttpreq = new XMLHttpRequest();
var keyword = document.getElementById("keyword").value;
var post_data = "keyword=" + keyword;
xmlhttpreq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
createTable(jsonObj);
}
};
xmlhttpreq.open("POST", "myPHP.php", true);
xmlhttpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttpreq.send(post_data);
}
function createTable(object) {
var out = "xxx";
document.getElementById("display").innerHTML = out;
}
</script>
</head>
<body>
<div id="display">
<?php echo $result; ?>
</div>
<form action="myPHP.php" name="myForm" method="POST">
<b>Keyword </b><input type="text" id="keyword" name="keyword">
<br>
<button type="submit" onclick="show()" name="search">Search</button>
</form>
</body>
</html>';
}
?>
You first have to test in myPHP.php if there is some data send. If so, the form already has been display and the browser is sending the form data back. If not, it is the first time the php-page is loaded and you can display the html and javascript.
So:
<?php
//test if there is data from the form
if( isset( $_POST['some-form-variable'] ) ){
// YES
// process data an display something
}
else{
// NO DATA
// display form and javascript
}
Related
I have a page that displays the content of a C++ file into a textarea and I need to be able to save the contents of it using a script. (The C++ file does not have to be configured just saved.)
I'm using a PHP script to load the code from a file to display it on the textarea. How can I send back the contents to the script and save it to the same file or to a file with a new name?
PHP, HTML file:
<?php
$file = '/var/www/cgi-bin/cpp_get3.cpp';
$content = file_get_contents($file);
?>
<input type="text" id="filename" value="cpp_get3.cpp"><br>
<textarea id="cpp_content" rows="15">
<?php
echo($content);
?>
</textarea><br/>
<button id="save"onclick="savefile();">save</button>
Script:
function savefiles() {
var contentArea = document.getElementsById('cpp_content');
var cpp_content = contentArea.value;
var request = new XMLHttpRequest();
request.open('POST', '/php/save_contents.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
console.log("Success");
var resp = this.response;
} else {
alert ("Target server reached, but it returned an error" );
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send(cpp_content);
}
PHP file:
<?php
$filename = '/var/www/html/cgi-bin/cpp_get3.cpp';
$cpp_content = $_POST['cpp_content'];
if(file_exists($filename)){
file_put_contents($filename, $cpp_content);
}
?>
I expect for the C++ file of a text file at this point to get save with the content in the textarea.
You don't deserve me ;)
<?php
$fn = 'example.cpp';
file_exists($fn) or touch($fn);
if (!empty($_POST)) {
var_dump($_POST);
$_POST['filename'] === $fn or $fn = $_POST['filename'];
file_exists($fn) or touch($fn);
file_put_contents($fn, $_POST['cpp_content']);
}
$file = file_get_contents($fn);
?>
<html>
<head></head>
<body>
<form action="hi.php" method="post">
<h1>ig #WookieeTyler</h1>
<input type="text" name="filename" value="<?=$fn?>">
<br>
<textarea name="cpp_content" rows="15">
<?= htmlspecialchars($file); ?>
</textarea>
<br/>
<button id="save" type="submit">save</button>
</form>
</body>
</html>
Another option would be to send the contents to a separated PHP file through an XMLHttpRequest. This way you don't have to reload the page when saving. Something like this:
var request = new XMLHttpRequest();
request.open('POST', '/my/url/save_contents.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send('cpp_content=' + cpp_content);
So I have a main page which have buttons, each buttons contain names, when I click that button I want to pop up div which shows information of that person, I used ajax to retrieve info from php,
var strURL="searchSender.php?ID="+ID;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
outMsg=req.responseText;
var prevWin = document.getElementById("senderInfo");
prevWin.innerHTML = outMsg;
prevWin.style.top = 50+"px";
prevWin.style.right = 80+"px";
prevWin.style.visibility = "visible";
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
searchSender.php basically redeem info of that specific person from the database, that returns these codes (i didn't include here the code that retrieves data from database)
<label>Name: <?php echo $row['Name'];?> </label></br>
<label>Address: <?php echo $row['Address'];?></label></br>
<label>Contact: <?php echo $row['ContactNumber'];?></label></br>
<div id="divSenderMap">
<?php
$url = "mapSender.html";
$_SESSION['SenderID'] = $row['ID'];
include $url ?>
</div>
<input type="button" id="btnSendReply" value="SEND"/>
<input type="button" id="btnCloseDiv" value="X" onclick="closeDiv()"/>
mapSender.html is supposed to return a map where the person is, the code is working on any other file/page, but it does not do it here. It is returning php and html codes but not javascript codes. What could be wrong?
As #MichaelLonghurst told it seems your file is named mapSender.html. So the server does not call PHP before return the HTML.
You should rename mapSender.html into mapSender.php.
Good day, I'm trying to use Ajax in my web application. But I have a little problem with it. I try to control a form if some username has already been registered or not. But my JavaScript seem does not send $_POST value to PHP. And responses that user in not defined on the line where I have $_POST['user'].
Here what I have.
PHP:
<?php
$opt = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$dsn ='mysql:dbname=someone;host=127.0.0.1;charset=utf8';
$user='someone';
$pswd='aaa';
$dbh = new PDO($dsn, $user, $pswd, $opt);
$query="SELECT 1 FROM users WHERE username = :username";
$query_p=array(':username' => $_POST['user']);
try
{
$statment = $dbh->prepare($query);
$result = $statment->execute($query_p);
}catch(PDOException $e)
{
echo "Can't run query: " . $e->getMessage();
}
$row = $statment->fetch();
if($row){
return 0;
}else {
return 1;
}
?>
So it opens a connection to database and runs a query
JavaScript:
function checkUser(e){
var state1 = document.getElementById("alert_text");
var u = document.getElementById("user").value;
if(u != ""){
state1.innerHTML = 'processing...';
var request = new XMLHttpRequest();
request.open("POST", "validation.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var result=request.responseText;
alert(result);
if(result==1){
state1.innerHTML="OK";
}else{
state1.innerHTML="Alredy exists!";
}
}
};
request.send(u);
var slova = request.responseText;
}
}
document.getElementById("user").addEventListener("blur",checkUser,false );
So technically it is ajax.
HTML:
<form id="check" name="signUp" method="post">
<p class="alert_text"></p>
<label for="user">Username:</label><br />
<input id="user" name="user" type="text" ><br />
</form>
I don't really see what's the problem...
You're not passing the username into the PHP script. Your PHP is looking for a POST variable, $_POST['user'] – in your JavaScript you make a GET request, so the PHP script has nothing to look up.
Based on the edited question: You are not sending any key-value pairs to the server, just a single value.
You need to change:
var u = document.getElementById("user").value;
to:
var u = 'user=' + encodeURIComponent(document.getElementById("user").value);
And then later on the pair will be sent correctly:
request.send(u); // sends a single key-value pair
Note that I have just added the encodeURIComponent function to make sure the value gets encoded correctly.
I would like to call a php function after clicking a button.
I already found a way to do this (kind of).
This is my code:
info.html
<html>
<head>
</head>
<body>
<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main'">
</body>
</html>
info.php
<?php
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle ,1024,";");
}
fclose($file_handle);
return $line_of_text;
}
function main($csvFile){
//Set path to CSV File
$csv = readCSV($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';
}
?>
My button is able to call the main function, but I do not know how to pass on a variable with a button click, could anybody help me with this?
You could pass the argument as another URL parameter:
<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main&arguments[]=File.csv'">
Then the PHP would be:
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction'])) {
if (isset($_GET['arguments'])) {
$args = $_GET['arguments'];
} else {
$args = array();
}
call_user_func_array($_GET['runFunction'], args);
} else {
echo "Function not found or wrong input";
}
Putting [] after the parameter name in the URL tells PHP to collect all the parameters with this same name into an array.
However, this is extremely dangerous, since it allows someone to execute any PHP function. Someone could connect to a URL like info.php?runFunction=unlink&arguments[]=.htaccess.
You should check the function name against a list of allowed functions to call.
You have to make a AJAX call. You can pass any arguments in that via GET or POST method. AJAX is simplest way to do this.
Change
<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main'"
to
<input type=button value="test">
You should use Ajax to send data to the server
<script>
function sendData(){
var data1 = "Hello";
var data2 = "World";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert(xmlhttp.responseText);
}
xmlhttp.open("GET", "ajax.php?data1=" + data1 + "&data2=" + data2, true);
xmlhttp.send();
}
</script>
You call the sendData function, when the button is clicked:
<input type=button value="test" onClick="sendData()">
The server reads the GET-Parameter
if(isset($_GET['data1']) && isset($_GET["data2"])){
$data1 = $_GET["data1"];
$data2 = $_GET["data2"];
return $data1 . " " . $data2 . " was sent to the server";
}
My project is to take input from the user and write it to the end of a text file in JSON format using ajax and php. Problem is that the php only writes the time and date to the end of the file and nothing else. I took the example from a previous post and modified it here for my purposes. Here's the html
movie.html:
<html lang="en">
<head>
<meta charset="utf-8"/>
<script src="movie.js" type="text/javascript"></script>
</head>
<body>
<h1>
<center>
<input id="box" type="textbox"name="box" value="Enter Movie:"/>
<input id="add" type="button" value="Submit" onClick="addStuff();" /></center>
</h1>
<div id="status" ></div>
<h2>MOVIE NAME:</h2>
<ul id="list" name="list">
</ul>
<div id="status"></div>
</body>
</html>
Here's the movie.js file which sends the data via Ajax:
function addStuff(){
var movie_name_entered = document.getElementById("box").value;
var movieList = document.getElementById("list");
var hr= new XMLHttpRequest();
var url= "movie.php";
hr.open("POST",url,true);
hr.setRequestHeader("Context-type","application/x-www-form-urlencoded");
var param = "film=" + movie_name_entered;
hr.setRequestHeader("Content-length", param.length);
hr.setRequestHeader("Connection", "close");
hr.onreadystatechange= function(){
if(hr.readyState==4 && hr.status==200){
var return_data=hr.responseText;
console.log(hr.responseText);
document.getElementById("status").innerHTML=return_data;
}
}
hr.send(param);
document.getElementById("status").innerHTML = "processing...";
}
Here's the php (btw, I console.logged the data being sent to the php and it is correct):
<?php
if($_POST){
$data = $_POST["film"];
$file ='movie.txt';
$fp = fopen($file, "a");
$encoded = json_encode($data);
fwrite($fp, $encoded);
fclose($fp);
return $encoded;}
?>
As mentioned above, the code only writes the time and date to the text file and nothing more no matter what I do. I tested the data being sent and it's valid $_POST data. I'm not sure how else to proceed. Any helop would be appreciated. Thx!
try this code in movie.js
function addStuff() {
var movie_name_entered = document.getElementById("box").value;
var movieList = document.getElementById("list");
var hr = new XMLHttpRequest();
var url = "movie.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param = "film=" + movie_name_entered;
hr.setRequestHeader("Content-length", param.length);
hr.setRequestHeader("Connection", "close");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
console.log(hr.responseText);
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(param);
document.getElementById("status").innerHTML = "processing...";
}
Please change your php code to below
if ($_POST) {
$data = $_POST["film"];
$file = 'movie.txt';
$fp = fopen($file, "a+");
$encoded = json_encode($data);
fwrite($fp, $encoded);
fclose($fp);
exit();
}
you are getting a empty $_POST variable so your php code is never gets executed. you have a mistake in your code :
hr.setRequestHeader("Context-type","application/x-www-form-urlencoded");
it should be Content-type , replace x with c :D