javascript generating php doens't works - javascript

Hello I have an option list in html that is created dynamically by php. I want to take the value of the option list withought subbmiting everything and then call another php function to fill another option list. To be more specific I want the user to first pick a University from a database and then to pick a department of that Universe. I 've created dynamicaly the option list for the Uni's by fetching all Uni's from the database and then find the value by javascript. So in the javascript function I want to write php code in order to fetch all the departments from the university. Eveything works fine until I try to call the php function from the javascript.
signup.php
<form>
<table>
.
.
.
<tr>
<td> Ίδρυμα:</td>
<td><select id="selection" name="selection" onchange="selectDep()" >
<?php include './selectUni.php'; ?>
</select> </td>
<td><span id="orgError" style="display: none;"></span> <td>
</tr>
<tr>
<td> Τμήμα:</td>
<td id="dep" name="dep" ></td>
<td><span id="depError" style="display: none;"></span><td>
</tr>
.
.
</table>
</form>
generateDep.js
function selectDep(){
if(document.getElementById('selection').value === "---")
return;
var value=document.getElementById('selection').value;
alert(value);
document.getElementById('dep').innerHTML=" <?php include './selectDep.php'; selectDep("+value+"); ?> ";
return true;
}
the value at the alert is correct
selectDep.php
<?php
//just trying to make this work for now
function selectDep($value){
echo $value;
}
?>
I cannot understand what I am doing wrong. Everything look fine to me. Can you help me?

First You have to understand that the javascript code executes in web browser but the php code executes in web server.
You can use AJAX to fix your problem.

PHP is a server-side scripting language. It is executed on the server, which means the page has to submit values to the server as a trigger. Javascript and HTML are client-side, which means it's all done in the browser without communicating with the server.
To see this in action, right-click on a PHP page in the browser and select to view source. All you will see is the HTML, you will not be able to view any of the PHP code that generates the page. When PHP executes on the server, the result is client-side code (javascript, HTML and maybe CSS) which is sent to the browser.
The browser wouldn't know what to do with PHP code. If you set the inner HTML of an element to some PHP code in client-side script, it won't get executed and all you will achieve is having the browser render the PHP script exactly as you entered it.
In short, the javascript has to submit the selected value back to the server, before the server-side PHP can work out which departments to send back to the browser.

Related

using ajax to pass string from php to javascript

So I have a piece of javascript code in an html document that responds to a button click. I want a new url to open, and if I specify the link in javascript as I've done below, everything works fine.
<input type="submit" id="submitbtn" value="Purchase Module"/>
<script type="text/javascript">
document.getElementById("submitbtn").addEventListener("click",handle_click);
function handle_click() {
var link;
link="http://www.google.com";
window.location.href=link;
}
</script>
Problem is I want to hide the real link on the server side as it includes a username:password. The php script below calls a function (not shown) that generates the link (a string). This also works fine.
<?php
$link=get_page_link();
?>
I want to pass the link string to the javascript and have tried various iterations of
link=<?php echo $link ;?> to no avail. As I understand it you can't pass strings this way and you need to use ajax. That's where I'm stuck. Seems like I need a $_POST on the php side and a $_GET on the java side, but not sure on the specifics. Any help would be appreciated. Thanks.

Accessing Js variable in php on the same page just with a difference of div tag in URL

I have a page say abc.php which displays a list of image names in a table.
When u click on any image name, the page loads an overlay at abc.php#openModal. This new page displays a list of related sensor values which are dependent upon the image name.
How do i get the image name when u click on the link to open the overlay ??
Sample Code:
<html>
<body>
<table>
<tr><td>Image name</td></tr>
<tr><td><a href='#openModal'>Image1</a></td></tr>
</table>
<div id="openModal">
<table>
<tr><td>Sensor value</td></tr>
<?php
$sql="SELECT sensor_value FROM table WHERE imageid='$id'";
$result=mysqli_query($conn,$sql);
if($result){
$row=$result->fetch_assoc();
echo "<tr><td>".$row['sensor_value']."</td></tr>";
}
?>
</table>
You cannot access JS variables from PHP code just because PHP is executed on server and JS - on client. In other words, PHP code ends execution earlier than JS code starts.
In you case you should on click call your JS function, which makes async query to server and displays call result in your modal window.

PHP code runs automatically in Javascript when not needed [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
Inside a PHP/HTML page i'm trying to start a session in php and then set a value to a session variable, and i'm trying that inside a Javascript function, and in this function there is a if statement, but the php code inside the if statement runs automatically when i go to the page immediately, when i want the code to run only when the user accept the terms...
Here is my code :
HTML :
<label>
<input type="checkbox" name="terms" id="terms-checkbox">
<font color="#090909" size="+1">I agree to the Terms and Conditions.</font>
</label>
Javascript :
if(document.getElementById("terms-checkbox").checked){
<?php session_start(); $_SESSION["ITA"] = "Yes"; ?>
window.open('DL.php?App=STOPit');
}
So when i open the php page that contains that previous Javascript code, the $_SESSION["ITA"] variable will be equals to "Yes" even that the condition is not met yet.
Hope someone can help me with that.
That's not how PHP and Javascript work.
PHP runs on the server before anything else. JS runs on the client side.
Without further information:
I suppose your JS code is not a file, but a inline script on the same HTML/PHP page. When your user requests the HTML page, PHP parses it, including the tags inside your JS code.
If you want PHP to do something based on a user action on the browser (document.getElementById) you have to take other routes. Maybe using Ajax, for example -- so your PHP code can do something.
For your better understanding php runs on the server side and javascript runs on the client side.
What you are trying to do is possible if you submit the data using a form or you have to make an ajax call using javascript.
Below is one way of doing something similar.
<?php
session_start();
if(isset($_POST['terms'])) {
$_SESSION["ITA"] = "Yes";
header('Location: DL.php?App=STOPit');
}
?>
<form action="<?php $_SERVER["PHP_SELF"] ?>" method="post">
<label>
<input type="checkbox" name="terms" id="terms-checkbox">
<font color="#090909" size="+1">I agree to the Terms and Conditions.</font>
<input type="submit" value="Submit">
</label>
</form>
Always start your PHP session_start() on the top of your PHP script file.
<?php
session_start();
?>
Here you can continue with your HTML/CSS/JavaScript codes
but the above is mandatory in order to start a session within
your PHP project.
Otherwise you'll be sending header information after the output buffering happend, and you'll end up with an error like this:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
When you have properly initialized a session handler as I described, you can use or do:
$_SESSION['item-name'] = 'value'; // to set a value of a specific session item
echo $_SESSION['item-name']; // retrieve it's value and output it
unset($_SESSION['item-name']); // to delete it from the $_SESSION container

How do I put javascript value into a php variable without changing the page?

I've got this research.php file that should show the content of a database table, taking the informations for the query from a javascript form.
I made in javascript the form and disabled the enter key, so that only by hitting the button you can submit the value. The value of the components in the form should be used to make the query. Can I pass the value to a php variable in the same file?
<!DOCTYPE html>
<html>
<head>
<!--
Implemented by Argese Alessandro and Rosso Kevin
The slider is taken from "https://dhtmlx.com/docs/products/dhtmlxSlider/samples/index.html"
Download slider: "https://dhtmlx.com/docs/products/dhtmlxSlider/"
-->
<title>Ricerca diplomati</title>
(...) <!--slider things-->
<style>
(...)
</style>
<script>
var mySlider;
function doOnLoad(){ //slider load
(...)
};
function doOnUnload(){ //slider unload
(...)
};
window.addEventListener('keydown', function (event) {
// if the keyCode is 16 ( shift key was pressed )
if (event.keyCode == 13) {
// prevent default behaviour
event.preventDefault();
return false;
}
});
function interact(form){
(...) //here the value is put in js variables, for a test
});
</script>
</head>
<body onload="doOnLoad();" onunload="doOnUnload();">
<form id="filters" name="filters" action="#" enctype="text/plain">
<table cellspacing="0" cellpadding="0" border="0" class="filters_table">
<tr>
<td>Specializzazione:</td>
<td>
<select name="specialization" class="table">
<option selected value="0">Tutte le specializzazioni</option>
<option>Chimica</option>
<option>Elettrotecnica</option>
<option>Informatica</option>
<option>Meccanica</option>
</select>
</td>
<td></td>
<td></td>
<td>Valutazione finale:</td>
<td><div id="sliderObj"></div></td>
<td><span id="sliderLink"></span><span class="minussign">-</span><span id="sliderLink2"></span></td>
<td></td>
<td></td>
<td>Città:</td>
<td><input type="text" name="city" size="35" maxlength="40" value=""></td>
<td></td>
<td><input type="button" onclick="interact(filters)" value="search" style="background: url(res/magnifying-glass-16x.png); background-repeat: no-repeat; background-position:center; background-color: #0c84e4;width:24px; height:24px;"></td>
</tr>
</table>
</form>
<?php
function viewTable(){
echo "Here the table will be shown";
}
?>
</body>
</html>
In this code the button click just call the interact function, that show an alert window with the value of the variables.
I tried to use ajax but, as far as I understood, it would open a new file.
I've also seen a solved answer in which someone suggested to use the cookies, but that solution really disgusted me.
The most helpful thing I found is here:
How do i store select value into a php variable,
but the POST method refresh the page and the slider crushes.
If you want to pass a variable from JS to PHP you are going to want to use AJAX, it allows you to send and receive info from server running the PHP script.
Your Javascript:
var infobeingsent = "test";
$.ajax({
type: "POST",
url: 'YOURPHPFILE.php',
data: { testVAR : infobeingsent },
success: function(data)
{
alert("data has been sent");
var recievedvar = data;
}
});
Your php file:
if(isset($_POST['testVAR']))
{
$recievedvar = $_POST['testVAR'];
echo "Hey, ive recieved your request";
}
Using AJAX means that your browser never has to come into direct contact with the php file and there's no interruption from the end-users perspective
I think you are a bit confused about the whole work flow between php (server side) and js (client side). OR may be I got your question wrong. But here is a hint on how you can approach this.
You have a server side running php - Great.
You have an html page with js - Awesome.
In the html page, you have a form that you want to run a query based on the user submission:
AJAX is the way. You can do it with pure javascript or a plugin like jquery. On the php side, you can even keep a small, seperate script just to handle this request, run the query and generate the result. Use "onSubmit" for the form to invoke ajax.

Submitting embedded pdf in html form

I've searched in vain for days, but haven't found a solution for my problem yet.
Ideally, I would like to embed a fillable pdf form into an intranet html form for submission to the server for processing (ability to parse the field/values would be gravy, but not required). The files are all in the same domain so no cross-domain issues. I know I could add submission functionality to the pdf form itself, but 1) scripting is beyond the ability of the pdf document administrator and I don't want to take that on, 2) there are hundreds of pdf documents, 3) I need additional scripted fields/values submitted with the form, 4) I want the pdf document to be contained within the login session. So far, the server log shows all the field/values, except the PDFInput parameter which is passed, but the value is empty.
Here's what I have so far:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(uploadForm).on("submit", function(event) {
var iframe = document.getElementById('PDFObj');
var iframeDocument = [iframe.contentDocument || iframe.contentWindow.document];
var pluginData = iframeDocument;
$(this).append('<input type="file" name="PDFInput" id="PDFInput" value="' + pluginData + '" style="visibility:hidden"/>');
return true;
});
});
</script>
and
<form enctype="multipart/form-data" method="post" name='uploadForm' id='uploadForm'>
<input type='hidden' name='rm' id='rm' value='uploadFile'>
<table align='center'>
<tr>
<td align='left'>
<strong>Notes:</strong>
<br>
<textarea cols='80' rows='2' name='notes' id='notes'></textarea>
<br>
<br>
</td>
</tr>
<tr>
<td colspan=2 align='center'>
<input type='submit'>
</td>
</tr>
<tr>
<td colspan=2>
<br>
<input type='hidden' name='formid' id='formid' value='6F45B3AF-91F3-108C-D3D9-701F541B49DC'>
<iframe type='application/pdf' src="url.pl?formid=6F45B3AF-91F3-108C-D3D9-701F541B49DC.pdf" height='800' width='1000' name='PDFObj' id='PDFObj'>
</td>
</tr>
</table>
</form>
I've tried embedding it using iframe and object along with setting input type="object", but I can't get any combination to work.
Is this even possible? Is there a better approach?
As far as I know, you're not going to be able to capture the PDF data directly from HTML like that. Your best bet is going to be to add submit functionality to the PDFs, then process the resulting FDF data with a server-side script.
You will need either add Submit a Form buttons to your PDFs, or modify the existing buttons. Make sure the form action in the PDF has #FDF after the URI (eg https://example.com/process.php#FDF).
Parsing the data server side is simple. I'm not sure what server side language you are using, but here is a PHP snippet
<?php // process.php, report the data we received
echo '<h2>GET Data</h2>';
foreach( $_GET as $key => $value ) {
echo '<p>Key: '.$key.', Value: '.$value.'</p>';
}
echo '<h2>POST Data</h2>';
foreach( $_POST as $key => $value ) {
echo '<p>Key: '.$key.', Value: '.$value.'</p>';
}
Note that a PDF only interacts with a web server properly when viewed inside of a web browser.
I do not know of a reliable way to programmatically add submit buttons to PDFs, nor do I know of a reliable conversion method. You're between a rock and a hard place here IMHO.
More info:
http://www.w3.org/TR/WCAG20-TECHS/PDF15.html
http://etutorials.org/Linux+systems/pdf+hacks/Chapter+6.+Dynamic+PDF/Hack+74+Collect+Data+with+Online+PDF+Forms/

Categories