Replacing div html() by echoing PHP - how to? - php

I have a multiple product elements that get their class and ID from PHP:
$product1["codename"] = "product-1";
$product1["short"] = "Great Product 1";
$product2["codename"] = "product-2";
$product2["short"] = "Great Product 2";
<div class="leftMenuProductButton" id="'. $product1["codename"].'" >'. $product1["short"].'</div>
<div class="leftMenuProductButton" id="'. $product2["codename"].'" >'. $product2["short"].'</div>
These display as:
<div class="leftMenuProductButton" id="product-1" > Great Product 1</div>
<div class="leftMenuProductButton" id="product-2" > Great Product 2</div>
In the page, I have an element that I want to replace the HTML:
<div id="productPopupTop">
//Replace this content
</div>
Using jquery, I have tried the following:
$( '.leftMenuProductButton' ).hover (
function () {
var swapNAME = $(this).attr("id"); //gets the ID, #product-1, #product-2 etc. This works.
$("#productPopupTop").html(' <? echo $' + swapNAME + '["short"] ?>'); //This is supposed to get something like <? echo $product-1["short"] ?> This doesn't appear to work.
},
function () {
//this is just here for later
});
If I try to do an alert('<? echo $' + swapNAME + '["short"] ?>'); it will literally display something like <? echo $product-1["short"] ?>
Please note that both the Javascript and the PHP are externally linked in a PHP file (index.php <<< (js.js, products.php)
QUESTION: How do I replace the HTML() of #productPopupTop with the ["short"] of a product? If I should use Ajax, how would I code this?

try this:
$( '.leftMenuProductButton' ).hover (
function () {
$("#productPopupTop").html($(this).html());
},
function () {
//this is just here for later
});

As knittl mentioned, php is a pre-processor on the server, and can't do anything once the page has been sent to the client.
The options I can think of are
Store the product information in javascript on the client (i.e. a javascript array that is populated with php)
Use ajax to query the server with a codename and receive the corresponding data (i.e. server.com/getshort.php?codename=product-2, which would respond with Great Product 2).
If the text within the tag is always the same, #Kasia's answer will work, and is simpler.

Related

expand/collapse div (toggle) when clicking on header

I have the following jQuery code to toggle the view of more information in a div.
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#"+bidValue+'_status')
expandArea.slideToggle(500);
});
The code works to toggle the view of displaying more information when the submission header is clicked. The div IDs of $moreInfo are dynamically created.
$moreInfo = $bidValue.''."_status";
echo "<div class='expandCollapse' id='$bidValue'>Submission</div>";
echo "<div id='$moreInfo'>$displayComments</div>";
However I want to open only one view/div at a time. If a div is open when a submission is clicked it should be closed before the other one is opened.
I've tried several things but it closes or hides all divs. Searching the web only show a solution using anchor tags.
Any thoughts...?
Thanks.
To achieve this you can put a common class on the second div element to allow you to hide them all before showing the next, like this:
echo '<div id="$moreInfo" class="expand-area">$displayComments</div>';
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#" + bidValue + '_status').slideToggle(500)
$('.expand-area').not(expandArea).hide();
});
Also note that you can make your code much more simple and generic by usnig DOM traversal to select the elements, instead of building selector strings based on related id attributes, like this:
$(".expandCollapse").click(function () {
var expandArea = $(this).next('.expand-area').slideToggle(500);
$('.expand-area').not(expandArea).hide();
});
The code above assumes that the elements are siblings, but you can easily amend the next() to traverse however is required.
Assuming the header and content divs are siblings you may use:
$(.expandCollapse + div)
// All <div>s that are immediately after an .expandCollapse
$(".expandCollapse").click(function () {
var bidValue = this.id,
expandArea = $("#"+bidValue+'_status')
expandArea.slideToggle(500);
$('.expandCollapse + div').not(expandArea).hide();
});
$('[id$="_status"]').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='expandCollapse' id='bidValue1'>Submission1</div>
<div id='bidValue1_status'>displayComments</div>
<div class='expandCollapse' id='bidValue2'>Submission2</div>
<div id='bidValue2_status'>displayComments</div>
<div class='expandCollapse' id='bidValue3'>Submission3</div>
<div id='bidValue3_status'>displayComments</div>

My mess that I'm trying to do with PHP, MySQL, jQuery and css

Let's see if I can explain what I'm trying to do here..
I've got a MySQL Database with some info stored in it. I am using PHP to query the database, pull my selected entries out, put each one into a separate <div> (with Bootstrap framework). I have accomplished this part.
Below is a snippet of what I'm doing...
$query = "SELECT `quote`,`id` FROM `db`";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
echo ' <div class="panel panel-info">
<div class="panel-body text-muted" id="'.$row['id'].'">
'.$row['quote'].'
</div>
</div>';
}
Then I am wanting to use jQuery to add a css class on "click" to an individual <div> and be able to then use PHP to store the text of the "selected" <div> to a variable, for later use.
This is the part I am struggling with, I can not figure out how to separate each individual <div> specifically and have jQuery add the class to it, because the "id" of div differs with every result from the db query.
To add a class to a div when it is clicked -
jQuery
$('div').click(function() {
$(this).addClass('foo');
var divText = $(this).text(); // store to JavaScript variable
});
Now that you have the JavaScript variable stored you can send it to a PHP function via AJAX.
What I would do is add a class to the <div>s, and use that to attach the event.
<div class="panel-body text-muted click-panel" id="'.$row['id'].'">
Then in your JavaScript, do something like:
$(function(){
$('div.click-panel').click(function(){
var div_id = this.id,
div_text = $(this).text();
if(/* some condition eg. div_id === 5 */){
$(this).addClass('clicked');
}
});
});

Get value from database after clicking on image

I have a query that gets the latest 10 rows in a table and loops 10 times to echo HTML that includes some of the information taken from the table, to something similar like below (pseudo code):
query = <GET 10 LATEST ROWS FROM TABLE>
$name = <ONE VALUE FROM TABLE>;
$name2 = <ANOTHER VALUE FROM TABLE>;
echo '<div class="style1">' . $name . '</div> <img src="image.png" /> <div class="style2">' . $name2 . '</div>';
What I'm having trouble with is that, if a user clicks the image, I need to run some Ajax to show another piece of HTML based on the variable $name.
The problem is that, since I'm echoing 10 rows from the table, how can I get the value of that one variable when the image is clicked?
Please help!
give each div an id based on the value of $name. and you use $name for your ajax call to get to next step.
Wrap the grouping you need.
PHP:
<div class="style-container">
<div class="style1"><?=$name;?></div>
<img src="image.png">
<div class="style2"><?$=name2;?></div>
</div>
Then you can use JS to loop through by container and get the name, no matter what the values inside may be, with or without quotes and other special characters.
JS:
$('.style-container').each( function( i, el ) {
var $el = $(el),
name = $el.find( '.style1' ).text();
$el.find( 'img' ).on( 'click', function() {
$.ajax({
url : 'whatever.php',
data : { name : name }
});
});
});
Note I would only do this if using the markup is your only option. You may want to echo out a json_encode of data inside a JS tag. Then you can iterate and use a templating engine like mustache to print out the markup. Then you could use AJAX to open a URL based on the data rather than the markup.

Get current HTML element in PHP

I may have misunderstood the purpose of PHP here. But I want to do the following:
I have a PHP function, and I call it from HTML, e.g.
<BODY>
<DIV id='A'>
<?php emit("hello1"); ?>
</DIV>
<DIV id='B'>
<?php emit("hello2"); ?>
</DIV>
</BODY>
And I want to know, within the function, which DIV it was called from.
e.g.
<?php function emit($txt){
echo "$txt";
echo "from DIV id $DIVID"
}
?>
And I want it, obviously, to print
hello1 from DIV id A
hello2 from DIV id B
Is there any way of finding the "current" DIV's ID?
Yes, you have misunderstood the purpose of PHP.
PHP is a server side programming language, it does not run on the HTML page, but before the HTML gets loaded on to the browser.
The task that you are trying to do can be done from JavaScript if interested. I will give an example of jQuery:
var emit = function(el, txt) {
var id = el.attr('id');
el.html(txt+" from DIV id "+id);
}
Now call using
emit($("#a"), "hello1");
Same can be done from JS in the following way
var emit = function(el, txt) {
el = document.getElementById("el");
id = el.getAttribute('id');
el.innerHTML(txt+" from DIV id "+id);
};
Use like:
emit("a", "hello1");

Bind event of a specific element to a specific target

i am using while loop to output data in
<p><?php echo $title;?></p></font></a><button id=show>show()</button> <button id=hide>hide()</button>
my show hide function is
$("#show").click(function () {
$("p").show('fast');
});
$("#hide").click(function () {
$("p").hide('fast');
});
$("#reset").click(function(){
location.reload();
});
now when i am clicking show hide only the first show hide loop is working and it shows/hides all the data not just the one i clicked
Change the code to use this, like so:
$(this).prev('p').show('fast');
You will need to do this in each JQuery .click section.
Edit:
Another good point which has been mentioned, you are using an ID for your element which won't allow this to work on more than one. Your new markup should look like:
<p><?php echo $title;?></p></font></a><button class="show">show()</button>
and the JQuery:
$(".show").click(function () {
$(this).prev('p').show('fast');
});
Welcome to SO. Nice to see that you have formated your first question nicely.
Few things you might want to change.
As you are going through a loop, make sure you use a counter inside the loop and add the counter to the id. This will make the id a unique identifier. Also wrap them inside a div.
$counter = 0;
forloop {
$counter++;
<div>
<p><?php echo $title;?></p></font></a><button id="show<?php echo $counter; ?>">show()</button>
</div>
}
So now your id will be unique.
Now you can write your jquery in the below way.
$("button").click(function () {
$(this).attr('id'); //not required but incase you need the id of the button which was clicked.
$(this).parent().find("p").show('fast');
});
$("button").click(function () {
$(this).parent().find("p").hide('fast');
});
Two things: 1. I think you can only have one element with one id, such as #show. If you want to reference more buttons, you should use a class, such as this: show() (as I understand the buttons are output in a loop, there will be more of them).
Second: inside your javascript code, you do $("p")... - this references all elements on the page. I think you should use $(this) and start from there, check out this article, it explains a lot: http://remysharp.com/2007/04/12/jquerys-this-demystified/
There are many ways to go at this. Here's one:
First, add the loop number to the IDs (let's say it's $i)
<p id="TITLE_<?php echo $i; ?>" style="display:none;"><?php echo $title;?></p>
<input type="button" class="show" data-number="<?php echo $i; ?>"/>
<input type="button" class="hide" data-number="<?php echo $i; ?>" />
Your functions will then be:
$(".show").click(function () {
$("TITLE_" + $(this).data('number')).show('fast');
});
$(".hide").click(function () {
$("TITLE_" + $(this).data('number')).hide('fast');
});
Of course there are ways to do it via JQUERY without the use of the $i.
Edit: To have the tags hidden on page load, either use the style=display:none as I have added in the tag above, or you can use JQuery as follows:
$(document).ready( function() {
$("p[id^=TITLE_]").hide();
// this will retrieve all <p> tags with ID that starts
// with TITLE_ and hide them
});

Categories