Get value from database after clicking on image - php

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.

Related

use jQuery to get text from current div

I have a small search engine querying the database for a list of names. The engine returns a maximum of 5 names. There is a button next to each each person's name. When the button is clicked, my jQuery code is supposed to add only that person's name to a comma separated list. Currently, it is adding every name that the engine pulls up. Im assuming I need to utilize the this command somehow. I feels as if my div isn't properly being selected.
The Question: how do you access the text of a paragraph that exists in the same class as the button?
The paragraph and button are enclosed by a class. The paragraph has a class. The button has a class.
//jQuery function to add the name to my list of names
$(document).ready(function(){
var addList = $('.addList');
$(".addCustomer").on( "click", function() {
customerToAdd = $('.addIndividual > .searched_name').text(); //here is where the problem lies. it comma separates every name
addList.val($('.addList').val() + customerToAdd + ', ');
search.val('');
});
});
And here is my html enclosed in php. This holds the fields that are used by the jQuery above.
while($state = mysqli_fetch_assoc($states)) {
$customerid = $state['id'];
$customername = $state['name'];
echo "
<div class='addIndividual' >
<p style='float:left;' class='searched_name'>".$customername."
</p>
<button type='button' value=".$customername." class='btn btn-default addCustomer'>Assign List to a Class</button>
</div>
<hr>";
}
You need to change
$('.addIndividual > .searched_name').text();
to
$(this).val();
OR if not the same as in the customer paragraph (it does seem that it is now):
$(this).closest(".addIndividual").find('.searched_name').text();
or if the paragraph stays next to the button for sure:
$(this).prev().text();
It looks like you already have the customer's name in the value attribute of the button. You can just grab it with: $(this).val().
You should also change your button to use class="addCustomer" instead of id="addCustomer". ID's are for unique elements, while a class is for multiple elements. In your case, you have a button for each customer.
Instead of $(".addCustomer").on( ... create a function like this:
function addCustomer(index){
$('.addIndividual .searched_name_'+index).text();
// continue the script ...
}
Your while loop will now look like this:
<p style='float:left;'class='searched_name_".$customerid."'>".$customername."</p>

php how to handle hyperlink like a POST instead of GET?

I will have a query that return a set of results, and these results will be in hyperlink form as shown below:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
Now user get to click on this hyperlink and get routed to abc.php?cif=$cif..
My question is, is it possible to only show abc.php to user, just like a POST method, and $cif remains available at abc.php?
As #Flosculus said above, the "best" solution to simulate a post request is doing something like proposed here: JavaScript post request like a form submit
However, despite it's surely a reliable solution, I'm wondering you just don't use sessions instead, something like:
From the page where you set the cif variable:
session_start();
$_SESSION['cif'] = $row['cif'];
In abc.php:
session_start();
if (isset($_SESSION['cif'])) {
// Do what you need
}
EDIT::
Another (possible) solution is setting an hidden input and silently submit a form when you click on an anchor, like this:
From your example, instead of:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
You do this:
When you print all the entries, please add this first (from PHP):
<?php
echo <<<HEADER
<form action="abc.php" method="post" id="submitAble">
<input type="hidden" name="cif" id="cif" value="{$row['cif']}">
<table>
HEADER;
// Get data from your query.. Here is an example:
while ($row = mysli_fetch_assoc($query)) {
echo <<<ENTRY
<tr>
<td>{$row['cif']}</td>
</tr>
ENTRY;
}
echo "</table> <!-- \table collapse --></form> <!-- \form collapse -->";
?>
Then, if you're using jQuery (thing that I'm recommending), simply add an event listener in javascript, like this:
$('.cifSetter').on('click', function(e) {
e.preventDefault();
$('#cif').val($(this).data('cif'));
$('#submitAble').submit();
});
If you don't have jQuery, use this instead:
var cifSetter = document.getElementsByClassName('cifSetter');
for (var i = 0; i < cifSetter.length; i++) {
cifSetter[i].addEventListener('click', function(e) {
e.preventDefault();
var cif = document.getElementById('cif');
cif.value = this.dataset.cif;
document.getElementById('submitAble').submit();
});
}
In both ways, whenever an anchor gets clicked, it will prevent its standard behavior (redirecting) and will instead set the value of an hidden field to the value of the CURRENT "cif" and submit the form with the desired value.
To retrieve the desired value from abc.php, just do this:
$cif = $_POST['cif'];
However, keep in mind that the hidden field is editable by the client (most persons won't be able to edit it, though), therefore you should also sanitize your data when you retrieve it.
Sessions could do it but I'd recommend to just use $_POST. I dont get why you wouldn't want to use POST.

Ajax GET passing the incorrect data

i have this HTML / PHP code:
$notes.='<div class="note '.$color.'" ';
if($row["xyz"] == '') {
$notes.='style="left:45%; top:10%; z-index:0;"><h3 align="center">New Note</h3>';
} else {
$notes.='style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">';
}
$notes.=htmlspecialchars($row['text']).'
<a class="closeMessage">X</a><div class="addedby">'.htmlspecialchars($row['addedby']).'</div>
<span class="data">'.$row['sequence'].'</span>
</div>';
there are multiple containing different data from the database
i would like to use ajax to send data to a PHP page using GET, i currently have this:
$('.closeMessage').live('click',function(){
//alert("close");
alert($('span.data').html());
$.get('/includes/sticky_notes/closeMessage.php',{
sequence : $('span.data').html()
});
alert("close");
});
but its passing the incorrect sequence each time. its passing the sequence number of a different row
As your HTML code for the notes have several elements with the class 'data', when you call for $('span.data').html() you will always get the inner html of the first span with the data class.
You can traverse the dom tree and use something like the siblings function.
$(document).ready( function(){
$('.closeMessage').on('click',function(){
//alert("close");
this_data = $(this).siblings('.data').html();
alert(this_data);
$.get('/includes/sticky_notes/closeMessage.php',{
sequence : this_data
});
alert("close");
});
});
In this example we store the data in a variable this_data = $(this).siblings('.data').html(), so we refer to the element that was clicked - $(this) and then go down in the tree until the next element with the class data.
One last thing - consider to use $('.closeMessage').on instead of live as it has been deprecated - http://api.jquery.com/live/

PHP echo overwrites previous echo

I have an HTML file that, when you click a button, Ajax loads a PHP file and the PHP file then echoes some text back to the HTML file.
The problem is that if I click the button a second time (or third, or fourth, etc), the next echoes overwrite the previous echo.
For example, if I click the button the first time, it would echo text here. If I click it a second time, it overwrites the previous echo and, again, would show text here instead of showing it on a new line.
Here's the HTML/Ajax:
<html>
<body>
<div id="show-more-results"></div>
<center><a class="btn show-more">Show more comments</a></center>
<script type="text/javascript">
var videoid = <?php echo $video_id; ?>;
$(document).ready(function() {
$(".show-more").click(function() {
num_comments += 10;
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: {video_id: videoid, num: num_comments},
success: function(data) {
$("#show-more-results").html(data);
}
});
});
});
</script>
</body>
</html>
PHP:
<?php
$videoid = $_POST['video_id'];
$num_comments = $_POST['num'];
echo $videoid;
?>
How can I make it so that the next echoes from the PHP file don't overwrite the previous echoes?
Instead of using the .html() function, which will overwrite the contents of the element every time, use .append() to add to it instead:
$("#show-more-results").append(data);
It's not PHP's echo that is overwriting your value, but your use of jQuerys html() function. It sets the HTML data for the element #show-more-results to a new value. (effectively overwriting the previous value)
To get the desired result, just concatenate the previous value with the new value:
$("#show-more-results").html(
$("#show-more-results").html() + '<br />' + data
);
Or even shorter:
$("#show-more-results").append('<br />' + data);
Something like
$( "#show-more-results" ).append( "<p>" + data + "</p>" );
Wrapping the data in <p> tags will keep it neat, but you may want some other container.
Every request is a separate script exectuion, it is like new page load.
You don't say, that HTML from previous page overwrites HTML from current page, do you?
If you want to preserve "history", you need to either accumulate reponses in your javascript code, or put in some persistent storage (Memcache, DB, etc) and return whole data.
You should append the result instead of replacing it.
//This
$("#show-more-results").html(data);
should be
$("#show-more-results").append(data);
In the success function, use document.createElement and createTextNode and appendChild to keep adding elements to the document.

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

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.

Categories