I have some php conditional logic...basically I want to use jQuery to show or hide certain div's when I submit a form:
<?php
if (isset($_POST['submit']) {
/*
If the user submits the form and
use jQuery to hide an existing div tag
<script type="text/javascript">
$('#mydiv').hide();
</script>
*/
}
?>
Is there a sort-of non-messy way to go about mixing php and jQuery like this? I just want my jQuery to be in one block and my php to be in a separate block (i.e. not interspersed)
You can catch the "onClick" event with ajax and then do what you want with your div like :
in your HTML page :
<button type="button" onclick= "yourFunction()">Click Me!</button
and then in a separate javascript file:
yourfunction() {
$("div").hide();
}
EDIT : You don't need PHP if you only want to hide a div when the form is submitted
Well if you are simply trying to hide something after the form has been processed successfully then putting your JavaScript code inside that if block is as good place as any other. You would just need to take care that the DOM tree is actually ready before you try to hide an element.
if (isset($_POST['submit']) {
echo <<<JS
<script type="text/javascript">
$(document).ready(function(){
$('#mydiv').hide();
});
</script>
JS;
}
However if that DIV you are trying to hide contains important information which isn't supposed to be seen in case form processing fails you should "hide" your container on the server side.
$status = false; // Status of the form processing
if (isset($_POST['submit']) {
// If processing succeeds you set $status to true
}
<?php if($status){ ?>
<div id="myDiv">
// Your super secret ingredient formula!
</div>
<?php } ?>
Related
So if i have a small layout stored in example.blade.php, How do i use it in jquery ?
I want to include certain elements such as textboxes when a particular radio button is checked otherwise not.
Example:
$("document").ready(function(){
if ($("#role").prop( "checked")) {
$("#content").html(#include('layouts.nav'));
}
else
{
$("#content").html('');
}
});
The above code does not work so please provide some solution.
You can not do that. #include() is Blade and will be interpreted by PHP while JS runs in the browser. The Blade directives are already interpreted by PHP when the code hits the browser
You can create a hidden div in your view and then use jquery to get it's html content, here is an example:
<div class="layouts-nav" style="display:none;">
#include('layouts.nav')
</div>
<script>
$("document").ready(function(){
if ($("#role").prop( "checked")) {
var layoutNav = $('#layouts-nav').html();
$("#content").html(layoutNav);
}
else
{
$("#content").html('');
}
});
<script>
I am very new to PHP and I am trying to get a piece of PHP code to run inside of my HTML file.
I have a drop down menu. If users select one item, it should display additional fields. So, I want them to only display if they select that item from the drop down menu. I am trying to select it based on the value for that drop down item. I have not declared any PHP values in a PHP script. This is all in HTML.
I know that with jquery you have to pull in the jquery library before running the script. Do I need to do this with PHP also?
Here is the code that I am trying to run:
Thank you in advance!
html file
<?php
if ($dropmenuValue == specificDropDownOption) {
?>
<div>
-conditional content-
</div>
<?php
}
?>
One of the main things about PHP and other server-side languages is that once they render the page, they shut down, and that's it. There's nothing they can do after.
You need to resort to a client-side here, probably the simplest way being adding the values of PHP variables to the appropriate JavaScript variables and then taking it from there. You would also need to render all possible contents and only show what you need.
So, in your case, you could make a CSS class to denote hidden content and then use JavaScript to hide/show different parts of the markup. Please note that all the hidden code (rendered by PHP, but hidden by CSS) is still visible in the page source, so if you have anything sensitive in there you should definitely do it by either making AJAX calls to load partial content, or regular page redirection/navigation.
EDIT
Here is a super-simple example I made for you, to see how you can show/hide content:
HTML (parts can be rendered by PHP, of course)
<div id="content1" class="content">Hey</div>
<div id="content2" class="content hidden">There</div>
<div id="content3" class="content hidden">World</div>
<hr />
<button onclick="show(1)">Show 1</button>
<button onclick="show(2)">Show 2</button>
<button onclick="show(3)">Show 3</button>
JS
function show(id) {
// select all the content divs
var allDivs = document.getElementsByClassName('content');
// iterate over them and add a hidden class to each
for (var i = 0; i < allDivs.length; i++){
allDivs[i].classList.add('hidden');
}
// finally, remove the hidden class from the one we referenced
document.getElementById('content' + id).classList.remove('hidden');
}
See it in action here: http://jsfiddle.net/f0onk7bk/
You can try something out with this... While using HTML inside of the PHP
#item { display: block;}
#itme.active { display:none }
Something like this would work when the page was loaded/reloaded...
<?php
if(isset($_POST['dropdown_name_here']) && $_POST['dropdown_name_here'] == "specificParameter")
{
echo("<div id='condition_one_div'> ... </div>");
}
else
{
echo("<div id='condition_two_div'> ... </div>");
}
?>
... but JavaScript is what you would want to use for dynamic content I would think.
var div = document.getElementById('div_name_here');
var dropdown = document.getElementById('dropdown_name_here');
if(dropdown.value == "specificParameter")
{
//add/show content for div here
}
else
{
//hide content for div here
}
is this what you are looking for?
<select id='dropdown_name' onchange='if(this.value == "parameter"){ document.getElementById("div_name").style.display = "block"; }else{ document.getElementById("div_name").style.display = "none"; }' >
</select>
So I have several divs that i assigned a class to. Each div has a header. The contents underneath each header are dynamically generated via php. Certain times of the year these divs contain no information but the header still displays. I want to hide the divs that do not have any paragraphs inside of them I cannot quite get them to work and I have a feeling it has to do with the paragraphs being generated by php.
EXAMPLE:
<div class="technology_connected article_headers">
<h3>TECHNOLOGY CONNECTED</h3>
<?php echo $tools->article_formatter($articles, 'Technology Connected'); ?>
</div>
Here is my Jquery code.
$(document).ready(function() {
$(".article_headers").each(function() {
if ($(this).find("p").length > 0) {
$('.article_headers').show();
}
});
});
Try this:
$(document).ready(function() {
$(".article_headers").each(function() {
if ($(this).find("p").length > 0) {
$(this).show();
}else{
$(this).hide();
}
});
});
DEMO
As noted by #JasonP above, this really should be done server side. However, since you do want it done server side, you can simplify the process greatly. Generate the data server side as you're doing. Make sure all <div> tags are visible. Then in your JavaScript use the following selector:
// Shorthand for $(document).ready(function() { ... });
$(function () {
$('.article-headers:not(:has(p))').hide();
});
The selector above targets all elements with the class .article-headers that do not contain a <p> tag and hides them.
JSFiddle demoing the above as a toggle button to show or hide the no paragraph sections.
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>
Hopefully someone will know how to do this...
I would like the show/hide to work dependent on the the image/icon clicked.
For example if Request Icon is clicked, the colorbox popup will be displaying the Request and Offered divs.
Whereas if the Accepted Icon is clicked, the colorbox popup will display Accepted and Offered Divs but hides the Request div.
Here's a few in the PHP:
<div <?php if($_GET['status']=="Requested"){ echo "class=iconActive";}else {echo "class=iconInactive";}?>>
<a href="/index.php/agent-appointment-request-list/?status=Requested">
<img src="components/com_agent/images/requestedIcon_s1.png" id="requestedIcon" alt="" /></a>
<div class="iconTitle">Requested</div>
</div>
Here's the jquery for show/hide that I have:
$(".slidingDivReq").show();
$("#show_hideReq").show();
$('#show_hideReq').click(function(){
$(".slidingDivReq").slideToggle();
});
Update: Here's the section for the content that'll be show/hidden. :
<div class="AppointmentTitleFirst">
<img src="components/com_agent/images/req_appt_title_s1.png" class="ApptIcon"></img>
<h1>Requested Appointment # <?php echo $this->appointment->id;?> Status:<?php echo $this->appointment->status_name;?></h1>
<img src="components/com_agent/images/dropdown_arrow_s1.png" class="ApptDropDownArrow1" id="show_hideReq"></img>
</div>
<div class="clearFloat"></div>
<div id="requestedAppointmentContent" class="slidingDivReq">
Content here....
</div>
Pretty much, I'm not sure how to use the GET['status'] and use it with the show/hide. So if the GET['status'] == Requested, then the show_hideReq will be .show(), but my other divs in the colorbox will use .hide(); (unless it's a page that needs a few other divs to .show())
Hopefully someone will know.
I'm not sure how to use the GET['status'] and use it with the
show/hide
You can use a hidden element as a variable, sothat you can test your GET['status'] in jquery. Add this element in your php page:
<input type="hidden" id="StatusId" value="<?php echo GET['status']; ?>"/>
Then you can do this:
$('#div').click(function(){
var statusId = $("#StatusId").val();
If( statusId === 0){
//Do something
}else{
// Do something elese
}
});
You should send the status value in the url that redirect to this php page, for example from js file it would look like:
var url = "http://localhost/yourcurrentphpfile.php?Status=" + somevalue;
window.location.href = url;
or the clicked <a> tag in your php page that redirect to this page should has the href property looks like http://localhost/yourcurrentphpfile.php?Status=somevalue.
yourcurrentphpfile.php is the php page that containst the hidden input.
You'd better use $(element).css("dissplay","none"); to hide an element and $(element).css("dissplay","inherit"); to show it.
Also in your PHP you better use if (isset($_GET['status']) && !empty($_GET['status'])) to ensure you have a value. Also, you need to edit your ECHO instructions to:
echo 'class = "iconActive"';
and
echo 'class = "iconInactive"';
Following your code's logic,
$(function(){ //on page load
$("div.classActive").load(function(){
//Do whatever you want when the div is active such as show/hide elements
})
$("div.classInactive").load(function(){
//Do whatever you want when the div is inactive such as show/hide elements
})
})
Only of the 2 will be executed since when a page renders only one of them will exist.