Pass variables from Javascript to PHP - Popup/Modal Window - javascript

<html>
<head>
<script type="text/javascript">
function showdivv(el, idclicked) {
var iddd = idclicked;
var display = document.getElementById(el).style.display;
if(display == "none")
document.getElementById(el).style.display = 'block';
else
document.getElementById(el).style.display = 'none';
}
</script>
<?php $showw = "<script>document.write(iddd)</script>"; ?>
</head>
<body>
<div id="myDiv" style="display: none;">ID Selected: <?php echo $showw; ?></div>
<?php $variable = 4; ?>
<button type="button" onclick="showdivv('myDiv', '<?php echo $variable; ?>')">Show / Hide</button>
</body>
I'm trying to make a way when a person presses the button pass the variable, in this case ID, to JavaScript and then show the hidden div in PHP. It does not work, can someone help me? THX

If you're okay with the page reloading, you can simply do
window.location.href('php_script_that_needs_your_input.php?id=input_id_from_js');
If not, I absolutely recommend using JQuery as it makes Ajax queries a breeze.
Inside the <head> tags:
<script src='http://code.jquery.com/jquery-2.2.0.min.js'></script>
Upload the script to your own server for production purposes, obviously.
in the <body>, where you want the results from the PHP script to appear (skip this if you don't want output from PHP):
<div id="phpResult"><!--content to be set by ajax--></div>
and put this JS directly below this <div>:
function ajax_on_button_press(resultDiv, id) {
var phpUrl = "php_script.php?id="+id+"&other_variable=cheese&more_info=rats";
$(resultDiv).load(phpUrl);
}
I have used example values here, but you can easily use variables from JavaScript like this:
var other_variable=$('#otherVariableInput').val(); //gets input from a textbox with the html id otherVariableInput
var phpUrl = "php_script.php?id="+id+"&other_variable="+other_variable+"&more_info=rats";
To start the process, you need a button that runs this script. Change your button markup to
<button type="button" onclick="ajax_on_button_press('#phpResult', '<?php echo $variable; ?>')">Show / Hide</button>
If I have understood you correctly, that should solve your problem.

Related

How To use PHP variable in jQuery (in Wordpress plugin)

This is wordpress plugin code The following code works, but no text comes into the modal window. Error is this enter image description here
<?php
$phpvariabletext = get_post_meta( $post_id, '_billing_satis_sozlesme', true );
// $phpvariabletext large text along with html codes
?>
<a class="classa" id="view" onclick="openmodal()"> Show Contract </a>
<script type="text/javascript">
var content = '<?php echo $phpvariabletext; ?>';
var newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(content);
}
</script>
You can use PHP variable in JQuery/Javascript easily check below steps
1) Stored PHP variable value in HTML input tag as type hidden
<input type="hidden" value="<?php echo $phpvariabletext;?>" id="phpvariable">
2) After assign variable value in HTML input tag. You can get value in JQuery/Javascript.
<script type="text/javascript">
var content = $('#phpvariable').val();
var newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(content);
}
</script>
Creating extra DOM elements solely to transport a value is needless extra markup.
I always pass php data to javascript as json_encode() output (without manually quoting) because it will automatically double-quote your string and escape any of the double-quotes in the actual data.
<a class="classa" id="view" onclick="openmodal()"> Show Contract </a>
<script type="text/javascript">
let newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(<?= json_encode(get_post_meta($post_id, '_billing_satis_sozlesme', true)); ?>);
}
</script>
The above technique outputs the php value using php "short tags".
P.s. you could also consider removing the inline js function call and use an event listener in your js to keep all of the behaviors/events in one place.

Why I lost the filename value when I click the submit button

I have made a form to pass xml files on a server. Although when it correctly sends the file to the server, it seems that the pages reloads and the value of the file name is lost and my javascript code returns nothing.
However if I remove the line
<input type="submit" />
from the code below it keeps the filename in the variable x but it doesn't send the file to the server.
I want to send the file on the server and keep its name into a variable in order to use in any other javascript functions.
<?php
$uploads_dir='/web/stud/external/scomvs2/epicurus';
if(isset($_FILES['xml_file1'])){
$errors= array();
$file_name = $_FILES['xml_file1']['name'];
$file_size =$_FILES['xml_file1']['size'];
$file_tmp =$_FILES['xml_file1']['tmp_name'];
$file_type=$_FILES['xml_file1']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['xml_file1']['name'])));
$expensions= array("xml","XML");
if(in_array($file_ext,$expensions)== false){
$errors[]="extension not allowed, please choose an xml file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"$uploads_dir/$file_name");
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" id="uploading" name="xml_file1"/>
<input type="submit" />
</form>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("uploading").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
You can add in our Javascript part the following:
<script>
function myFunction() {
var x = <?=json_encode($file_name)?>;
document.getElementById("demo").textContent = x;
}
</script>
Now when in Javascript you call that function, the demo element will show the file name. Note that it is better to use textContent instead of innerHTML, although with filenames you don't risk to have special characters that HTML would interpret (<>&).
Now you should also make sure that $file_name is always defined. So at the top of your PHP code, add:
$file_name = '';
Instead of injecting the file name in your Javascript code, you could also let it be injected directly in the demo tag, like this:
<p id="demo"><?=htmlspecialchars($file_name)?></p>
Then you don't need Javascript to fill it in, if that is all you wanted to do.

<script> tags not working following jQuery post

I am having a problem with jQuery where by it is not loading inside a requested div.
Setup:
On index.php I have 4 Morris charts on 4 tabs all working fine.
On each tab there is a list. Each item in the list is a link
Upon clicking the link the div within the tab reloads with new data
via post:
$(document).ready(function () {
$('.click5').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company5-'+companyId+' .clickthrough5').val(),
ref_date_from5: $('#company5-'+companyId+' .ref_date_from5').val(),
ref_date_to5: $('#company5-'+companyId+' .ref_date_to5').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
The new div contains a back button to take you back to a replica of the 1st graph but on a different page (donut1.php), for my personal ease:
$(document).ready(function () {
$('.backref2').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut1.php', {
clickthrough6: $('#company6-'+companyId+' .clickthrough6').val(),
ref_date_from6: $('#company6-'+companyId+' .ref_date_from6').val(),
ref_date_to6: $('#company6-'+companyId+' .ref_date_to6').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
All this code works fine up until landing on donut1.php.
At this point I proceeded to pull out chunks of my hair for several hours looking through Inspect Element in Chrome to identify the issue.
1 bald person later I realised the jQuery was not loading although it is correctly requested in a script tag.
I confirmed this by placing the following on both donut1.php and donut5.php:
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
donut5.php displays the output fine while donut1.php does not.
I then tried to load an external source and a different version using the Google snippets found here but this still did not work.
Some points to note:
I currently have jquery loading in my header and footer as part of trying to work this out.
As the 2 pages donut1.php and donut5.php do not include header or footer I have manually included them both in there. Same exact way in both files. donut5.php works donut1.php does not.
Order is index.php > donut5.php > donut1.php and then you continue to cycle between donut5 and donut 1 - or you would if the post on click was working in donut1.php.
Any help would be greatly appreciated!
EDIT: donut1.php:
<?php
include("../../../includes/config.php");
$selected = $_POST['clickthrough6'];
$date_from = $_POST['ref_date_from6'];
$date_to = $_POST['ref_date_to6'];
?>
<script src="../../../js/jquery-1.11.0.js"></script>
<script>
$(document).ready(function () {
$('.click7').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company7-'+companyId+' .clickthrough7').val(),
ref_date_from5: $('#company7-'+companyId+' .ref_date_from7').val(),
ref_date_to5: $('#company7-'+companyId+' .ref_date_to7').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
</script>
<div id="tabs2">
<div id="tabs-1" class="donut5">
<h4>Top 5 Referrers - Quotes <br /><small>Total number of Quotes between <?php echo date("d/m/Y", $date_from); ?> to <?php echo date("d/m/Y", $date_to); ?></small></h4>
<div class="statgrid">
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
<?php $quotes_q="SELECT
c.case_id,
co.name AS company_name,
co.company_id AS company_id,
COUNT(c.case_id) 'quote_count'
FROM
(`case` c,
`panel_company` pc,
`panel` p)
LEFT JOIN company co ON (co.company_id = pc.company_id)
WHERE pc.panel_id = " .$RegisteredUser['panel_id']. " AND
p.company_id = pc.company_id AND
c.panel_id = p.panel_id AND
c.insert_date > ".$date_from. " AND
c.insert_date < ".$date_to. "
GROUP BY p.panel_id
ORDER BY quote_count DESC, co.company_id
LIMIT 5";
$result=$mysqli->query($quotes_q); ?>
<div class="col-2-6">
<div id="morris-donut-chart6"></div>
</div>
</div>
<div class="statgrid">
<?php while ($row=$result->fetch_array()) { ?>
<div class="col-4-6">
<div id="company7-<?php echo $row['company_id'];?>">
<input type="hidden" class="ref_date_from7" value="<?php echo $date_from; ?>" />
<input type="hidden" class="ref_date_to7" value="<?php echo $date_to; ?>" />
<input type="hidden" class="clickthrough7" value="<?php echo $row['company_id'] ?>" />
<a><div id="<?php echo $row['company_id'];?>" class="click7 col-5-6"><?php echo $row['company_name']; ?></div></a>
<div class="col-1-6"><?php echo $row['quote_count']; ?></div>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<?php
$quotes_q = "SELECT
c.case_id,
co.name AS company_name,
COUNT(c.case_id) 'quote_count'
FROM
(`case` c,
`panel_company` pc,
`panel` p)
LEFT JOIN company co ON (co.company_id = pc.company_id)
WHERE pc.panel_id = ".$RegisteredUser['panel_id']." AND
p.company_id = pc.company_id AND
c.panel_id = p.panel_id AND
c.insert_date > ".$date_from." AND
c.insert_date < ".$date_to."
GROUP BY p.panel_id
ORDER BY quote_count DESC, co.company_id
LIMIT 5";
$result = $mysqli->query($quotes_q);
?>
<script>
var donut_data6 = [
<?php while ($row = $result->fetch_array()) { ?>
{
label: '<?php echo substr($row['company_name'],0,15); ?>',
value: '<?php echo $row['quote_count']; ?>'
},
<?php } ?>
];
var donut6 = {
element: 'morris-donut-chart6',
data: donut_data6,
resize: false
}
donut6 = Morris.Donut(donut6)
</script>
EDIT2:
Not too sure if this makes a different but in Network tab I have 2 listings for jquery the initial one loaded from the header which loads 304 Not Modified and the 2nd one which loads on calling donut5.php which loads as 200 OK. Seems that after this I cannot request jquery again perhaps?
EDIT3: in donut1.php I have removed everything except for the jquery script request and the Hello World inside the div I am trying to retrieve. Network tab still shows that jquery is not loading. The strange thing is I have this exact setup, minus the charts, working on the same page (different div classes of course), and this does load jquery fine.
EDIT4: Substituted jQuery for JS as a test and not even basic stand alone JS will work, added in:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Nothing :( - Looping in JS world
EDIT5: Suppose <script> is a HTML tag so looping in them too.
EDIT6: When adding console.logo(data) to the function in list item 4 above I get back the following (obviously I have excluded a lot for testing:
<script src="../../../js/jquery-1.11.0.js"></script>
<script src="../../../js/jquery-ui.js"></script>
<!--
<script>
$(document).ready(function () {
$('.click7').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company7-'+companyId+' .clickthrough7').val(),
ref_date_from5: $('#company7-'+companyId+' .ref_date_from7').val(),
ref_date_to5: $('#company7-'+companyId+' .ref_date_to7').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
</script>
-->
<div id="tabs2">
<div id="tabs-1" class="donut5">
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
</div>
</div>
EDIT7:
Placing code here to confirm if I have correctly inplemented KevinB's suggestion.
var
contentSelector = '.donut5',
$content = $(contentSelector),
contentNode = $content.get(0);
var documentHtml = function (html) {
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi, '</div>');
// Return
return $.trim(result);
};
$(document).ready(function () {
$('.click5').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company5-' + companyId + ' .clickthrough5').val(),
ref_date_from5: $('#company5-' + companyId + ' .ref_date_from5').val(),
ref_date_to5: $('#company5-' + companyId + ' .ref_date_to5').val()
},
function (data) {
var
$data = $(documentHtml(data)),
$dataBody = $data.find('.donut5'),
$dataContent = $dataBody.find(contentSelector),
$menuChildren, contentHtml, $scripts;
// Fetch the scripts
$scripts = $dataContent.find('.document-script');
if ($scripts.length) {
$scripts.detach();
}
// Fetch the content
contentHtml = $dataContent.html() || $data.html();
$scripts.each(function () {
var $script = $(this),
scriptText = $script.text(),
scriptNode = document.createElement('script');
if ($script.attr('src')) {
if (!$script[0].async) {
scriptNode.async = false;
}
scriptNode.src = $script.attr('src');
}
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
console.log(data);
});
});
});
EDIT8:
After trying the code above in EDIT7 the .donut5 in no longer being pulled from donut5.php to index.php which was originally working. I can see that jquery doesn't duplicate anymore on Network tab when clicking the link for donut5.php (even though the call to it is still there). Currently either I assume I have not mapped a div correctly above as I did remove part of the class find code for :first as I felt it was not required or somehow I have managed to make things worse!
When you pass an htmlstring to .html, one of two things happen. It either gets inserted using .innerHTML, or it gets inserted using .empty().append(htmlString). Which one is chosen is based on the complexity of the htmlstring passed in.
If it's relatively simple, .innerHTML will be used and scripts will execute in the way you expected.
However, if it is more complex, the elements are first parsed and appended to a docFragment before being appended to the document. This middle step is what causes your problem because the javascript will be executed before the elements are part of document.
The only way to fix this issue is to forcibly delay the execution of the javascript by either coding the javascript in such a way that it's execution is in a callback that later gets called, or by removing the javascript from the htmlstring before appending it and then executing it after.
Below is an example of the former:
(function divTestLooper () {
if (!$("#divTest1").length) {
// the element didn't exist, lets wait a little longer...
return setTimeout(divTestLooper, 10);
}
$("#divTest1").text("Hello, world!");
})();
Here is an example of the latter:
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L60-L70
and
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L123-L135
and
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L158-L167
Of course, the best solution is likely to avoid this problem entirely by not including javascript in your partials.

Hide div content permanently

I want when the user click on submit button the content disappear (random text 3) until the user logs off. The JS works fine but, if I refresh the page, the content appears. Can anyone help me achieve this or can anyone convert my code to PHP so that I can use a session variable to achieve this?
<style type="text/css">
div.something{
/*random code;/*
}
</style>
<script type="text/javascript">
function hideSomething(){
document.getElementsByClassName("something")[2].style.display = "none";
}
</script>
<div class="something">random text 1</div>
<div class="something">random text 2</div>
<div class="something">random text 3</div><br />
<input type="submit" value="Disappear" onclick="hideSomething()" />
well the professional way is to record it on cookie or store in database with user information like IP or you can use rough way to just forward it to another page where that div not appear thou some dont allow cookies to store let me know which one you like and i will fill my answer with it sample
Use a cookie and store the status of the div there.
You can easily read and write a cookie using javascript.
A nice tutorial can be found here: http://www.w3schools.com/js/js_cookies.asp.
For example, in the hideSomething() function do the following:
document.cookie="display_div=true";
Then, when the page is loaded, call a javascript function that shows or hide the div based on the value of the cookie:
if(cookie_value == "true")
//Hide your div
else
//Show your div.
end
So first we create a form with a hidden text box, once user click on button Close Attendance the value of hidden textbox is submited and a session variable is created:
if(isset($_POST['hidden'])){
$_SESSION['closed'] = TRUE;
}
Then we check is session is set, if yes display attendance close, if not display content.
<?php if(isset($_SESSION['closed'])){
echo "attendance closed.";
}
else {
echo "<form name='test' action='attendance.php' method='post'>
<input type='hidden' name='hidden'/>
<button> Close Attendance </button>
</form>";
}
?>
try the following code, it should give you a very clear glimpse on how to do it.
<!DOCTYPE html>
<html>
<head>
<title>ZUUS: Ironman</title>
</head>
<script type="text/javascript">
function hideSomething()
{
document.cookie="hide_div=true";
myFunction();
}
function myFunction()
{
var cookie_value = getCookie("hide_div");
alert(cookie_value);
if(cookie_value == "true")
document.getElementById("test_div").style.display = "none";
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
</script>
<body onload="myFunction();">
<div id="test_div" style="background-color: blue;" onclick="hideSomething();">
this is a test
</div>
</body>
</html>

Solution for changing' img id' with 'document.getElementById' when selecting from auto generated list

Solution for changing image id when selecting from auto generated list
This code:
<?php foreach(glob('pano/*.png') as $filename):?>
<li><?php $path_parts = pathinfo ($filename); echo $path_parts['filename'], "\n";?> </li>
<?php endforeach; unset( $filename);?>
Generates a screen with a button for each of the files. The function chgpano:
function chgpano()
{
ima = document.getElementById("tonto");
init();
}
Changes the img Id assigned to variable "ima". The contents of "tonto" need to reflect the image selected.
The following cannot work, but does show the intent:
function chgpano()
{
img id="tonto" src= ('pano/'+ variable with text from button selected)
ima = document.getElementById("tonto");
init();
}
I saw a similar question but it was rejected as being unclear
Try this:
// PHP can look like
$liA = '';
foreach(glob('pano/*.png') as $f){
$path_parts = pathinfo($f);
$liA .= "<li><a href='javascript:chgpano($f)'>{$path_parts['filename']}></a></li>";
}
echo $liA;
// JavaScript can look like + some goodies
var doc = document; // get in the habit of declaring variables
function E(e){
return doc.getElementById(e);
}
var tonto = E('tonto');
function chgpano(f){
tonto.src = f;
}
I would use external JavaScript, putting the <script> tag at the bottom of the body. Alternatively, you would put the <script> tag in the <head> and run onload.
as mentioned in the comment the purpose of id in html is for one single element..
so i would use class or the new data-TAG.
to reuse the php script also for other scripts/sites i would scan the folder and convert everything to json.(simple array containing all the paths of the png's)
here is a example using javascript 1.7 (modern html5 browsers)
to handle multiple elements with one handler.
scanForPNGs.php
echo json_decode(glob('pano/*.png'));
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
img{width:100px;}
img.IMA{opacity:0.3;}
</style>
<script>
var box;
function ajax(a,b,c){c=new XMLHttpRequest;c.open('GET',a);c.onload=b;c.send()};
function display(){
box.innerHTML='<img src="'+JSON.parse(this.response).join('"><img src="')+'">';
}
function whatever(e){
e.target.classList.toggle('IMA');// activate & deactivate
//or
//e.target.dataset['IMA']=e.target.dataset['IMA']=='ON'?'OFF':'ON';
}
window.onload=function(){
box=document.getElementsByTagName('div')[0];
box.addEventListener('click',whatever,false);
ajax('scanForPNGs.php',display);
}
</script>
</head>
<body>
<div></div>
</body>
</html>
inside the whatever function you can add whatever proprieties or functions to the element that you click.
in my case i just change the opacity.
the trigger is the image itself.
i did not test this code...to be sure test it with chrome.
example
http://jsfiddle.net/8jeDS/1/
Thanks Guys & Gals. This fixed it:
<?php
foreach(glob('pano/*.png') as $filename):$path_parts = pathinfo ($filename); $id_front = $path_parts['filename'];?>
<li> <a onclick = "javascript:chgpano('<?php echo $id_front ?>')"><?php echo $id_front, "\n";?></a><img id= <?php echo $id_front ?> src= <?php echo$filename ?> style="display:none"></li>
<?php endforeach; unset( $filename);?>
As you can see I put the same variable being used to assign the image id into the function parameter.
Now the variable ima contains the img id
function chgpano(blah)
{
ima = document.getElementById(blah);
init();
}
I had to move the variable difinition out side the div otherwise the function parameter was getting filled before the variable was defined.

Categories

Resources