my websites search results are immune to jquery - php

I have a website where I can search for things in the database, let it be boats for now.
I use this form
<form method="post" action="">
<input type="text" class="form-control" id="searchField" name="searchField" autocomplete="off"/>
</form>
<div id="searchResults"></div>
And this jquery to display serch results
//Autocomplete search field
$("#searchField").keyup(function(){
var input = $("#searchField").val();
$("#searchResults").html("");
input = $.trim(input);
if(input){
$.post( "source/pages/processing/search_boats.php", {inputString:""+input+""}, function( data ) {
$( "#searchResults" ).html( data );
});
}
});
the search_boats.php look like this:
<?php
$input = $_POST['inputString'];
$sql = mysqli_query($dbcon, "SELECT boat_name FROM boats WHERE boat_name LIKE '%".$input."%' ORDER BY boat_name LIMIT 5 ");
echo "<ul id='searchUL'>";
while($row = $sql -> fetch_array()){
?>
<div class="row">
<div class="col-md-4">
<? echo $row['boat_name']?>
</div>
</div>
<?
For now this working perfectly - just like I want it. However, when these search results appear on the website I can not add any click events on them. Ive tried making buttons, anchors. I suspect jquery is not ready for this added piece of search results that Im displaing the user. For example, I'm able to hide a div called myDiv on click on any anchor tags
like so..
$("a").click(function(){
$("#myDiv").toggle();
});
but when I click anchors on the search results, the myDiv isn't being hidden.
What could be the problem ?

Try This
$('body').on('click','a',function(){
$("#myDiv").toggle();
});

Related

How do I get the value of textarea that is created in while loop

I have the problem, that I can't access the value my textareas which are created in a while loop of php. I guess that they are not registered in the DOM. Same is for the button that is attached to it.
So I do know, that I have to access the button via jquery with the special event listener because of this dynamically creation. I get all the IDs that I need, but I am not able to get the value of the textarea, even that I can get its correct ID, as it somehow seems to be just empty.
As I can't post a php fiddle in here, here is an example of how it works.
include"connection.php";
$stuff="here is the query";
for ($n = 1; $n <= 13; $n++) {
$xy=$con->query($stuff);
while($row=mysqli_fetch_assoc($xy))
{
$value = $row['value'];
echo"<div id='$n' class='antworten'>$value<br>
<div id='notizcontainer$n' class='antwortcontainer'>Notizen:</div>
<div class='antwortcontainer' id='notizerstellen$n'>Notiz erstellen:<br>
<textarea id='notizfeld' class='textarea'></textarea><br>
<button id='absenden' class='notizabsenden'>Notiz absenden</button></div>
</div>";
}
}
jQuery:
$(document).on('click', '.notizabsenden', function(){ //do this bc its not registered and .click() is not working, also I need the click event on the button class to know on which button the event is going on
var parentid = $(this).parent().attr('id'); //get parentid of button
var notizid = $('#'+parentid).find('textarea').attr('id'); //find id of textarea of parent
var notiz = $('#'+notizid).val(); //this should give me the text of the textarea... but it returns empty/blank
console.log(notizcontainer); //this turns out correct
console.log(parentid); //this turns out correct
console.log(notiz); //this returns empty/blank as if the textarea has nothing in it... which it does
The issue is because the HTML in your PHP loop is re-using the same id for multiple elements when they have to be unique. To fix that problem, remove the id attributes from all repeated content.
To address the issue of accessing the textarea content, you need to use DOM traversal to find the textarea related to the button which was clicked. To do that you can use a combination of closest() and find(), like this:
$(document).on('click', '.notizabsenden', function(e) {
const $btn = $(e.currentTarget);
const notiz = $btn.closest('.notizerstellen').find('.notizfeld').val();
console.log(notiz);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<!-- generated by your PHP loop... -->
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Lorem ipsum</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Dolor sit</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Amet consectetur</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>

Comment and subcomment form: problems when showing and hiding it inside while loop (php) and based on a jquery script logic

The problem is with my two forms (for comments and subcomments by the users). I've implemented a jquery code so that this such form can show or hide when clicking on the "reply" button. Well, man, so far so good. But I noticed after a few tests that this works out on the comments but not on the subcomments.
On the subcomments it works but only on the subcomments I posted and when I'm logged in my own system. On the rest of the subcomments, it does not work, and when I click on the secondary comment or subcomment "reply" button, it doesn't show or hide anything and the other buttons like "delete" and "edit" look unactive and don't work at all. Well, this is my first problem. Now, my second problem is with the span "view replies".
When I click on it, it hides all "ul"(unordered lists) with class ".replies" at once (in which there are the subcomments to the main comment) and not one by one (hide-and-show switching) like I'd like. Besides, when I click on it again, it simply doesn't reshow. This is the jQuery code:
$(document).ready(function(){
$(document).on('click' , '.reply' , function(){
var closestDiv = $(this).closest('div'); // also you can use $(this).parent()
//closestDiv.fadeOut();
$('.replyto').not(closestDiv.next('.replyto')).hide();
//$('.reply').closest('div').not(closestDiv).show()
closestDiv.next('.replyto').slideToggle(100);
});
});
This one above is to toggle the "reply" form of comments. It's working on the first level (comments), but not for the subcomments.
$(document).ready(function(){
$(document).on('click' , '.clicktoviewreplies' , function(){
var closestUl = $(this).closest('ul'); // also you can use $(this).parent()
//closestUl.fadeOut();
$('.replies').not(closestUl.next('.replies')).hide();
//$('.clicktoviewreplies').closest('ul').not(closestUl).show()
closestUl.next('.replies').slideToggle(100);
});
});
This one above is to toggle the subcomments or replies. It's something like "show replies" and "hide replies". And this is the whole php code. It's based on four tables: registered_users, videos (although it's not here), comments and subcomments, as you can see.
<?php
while($commentslist = $showcomments->fetch()){
$iduser = $commentslist['idUser'];
$idcomment = $commentslist['id'];
$showuser = $pdo->prepare("SELECT * FROM registered_users WHERE id = ?");
$showuser->execute(array($iduser));
while($row6 = $showuser->fetch()){
<li>
<div>
<b><?php echo $row6['username']; ?></b><br>
<?php echo $commentslist['comments']; ?>
<!--additional comment buttons or controllers-->
<?php
if($iduser == $row['id']){ ?> <button>Edit</button><?php }else{ ?> <button>Report</button><?php } ?> <button class="reply">Reply</button><?php if($iduser == $row['id']){ ?> <a onClick="return confirm('You sure you wanna delete that comment there')" href=""><button>Delete</button></a><?php }
?>
</div>
<div class="replyto">
<!--THIS IS TO SUBMIT THE CHILD COMMENTS(SUBCOMMENTS)-->
<form enctype="multipart/form-data" method="post" action="<?php echo "postsubcomment.php?id=$idcomment"; ?>">
<textarea name="subcomment" cols="50" rows="4"></textarea>
<input type="submit" name="reply" value="Submit">
</form>
</div>
<span class="clicktoviewreplies"><b>View replies</b></span> <!--ATTENTION!HERE IT IS WHERE MY PROBLEM IS. I CLICK ON IT AND IT HIDES ALL "UL"(Unordered Lists) WITH CLASS ".REPLIES" AND NOT ONE BY ONE (SWITCHING) LIKE I'D LIKE. AND WHEN I CLICK ON IT AGAIN, IT DOESN'T RESHOW.-->
<!--SECOND LEVEL UNORDERED LIST-->
<ul class="replies">
<!--Subcomments go/show here. This happens everytime the user replies to a main comment-->
<?php
$showsubcomments = $pdo->prepare("SELECT * FROM subcomments WHERE idComment = ?");
$showsubcomments->execute(array($idcomment));
while($subcommentslist = $showsubcomments->fetch()){
$subcommenter = $subcommentslist['idComment'];
$selectcomment = $pdo->prepare("SELECT * FROM comments WHERE id = ?");
$selectcomment->execute(array($subcommenter));
$row7 = $selectcomment->fetch();
//This is to get the parent comment user
$selectuser = $pdo->prepare("SELECT * FROM registered_users WHERE id = ?");
$selectuser->execute(array($row7['idUser']));
$row8 = $selectuser->fetch();
$subcommentslist['idUser']; //The user that made the subcomment
$selectuser2 = $pdo->prepare("SELECT * FROM registered_users WHERE id = ?");
$selectuser2->execute(array($subcommentslist['idUser']));
$row9 = $selectuser2->fetch();
?>
<!--SECOND LEVEL LIST ITEM: This is to show the subcomments-->
<li>
<div>
<?php echo "<b>".$row9['username']; ?>
<?php echo "<br>".$subcommentslist['subcomments']."<br>"; ?>
<!--additional subcomment buttons or controllers-->
<?php
if($row9['id'] == $row['id']){ ?> <button>Edit</button><?php }else{ ?> <button>Report</button><?php } ?> <button class="reply">Reply</button><?php if($row9['id'] == $row['id']){ ?> <a onClick="return confirm('You sure you wanna delete that comment there')" href=""><button>Delete</button></a><?php }
?>
</div>
<div class="replyto" style="margin-left:5%; position:relative;">
<!--THIS IS TO REPLY TO BOTH THE MAIN COMMENT AND SUBCOMMENTS BELOW IT-->
<form enctype="multipart/form-data" method="post" action="<?php echo "postsubcomment.php?id=$idcomment"; ?>">
<textarea name="subcomment" cols="50" rows="4"></textarea>
<input type="submit" name="reply" value="Submit">
</form>
</div>
</li>
<?php
}//THIRD (SUBCOMMENTS) WHILE CLOSED
?>
</ul> <!--SECOND UNORDERED LIST CLOSED -->
</li>
<?php
} //SECOND WHILE CLOSED
} //FIRST WHILE CLOSED
?>
Well, the first instance (comments) "reply button "behaviour works. Why not the second instance one (reply for subcomments)? I wonder if the problem is the second or third while loop or maybe it has something to do with the "ul" and "li" arrangements.
Well, the boss here will solve these problems for you, man.
For the second problem (span:"view replies"), change your code to this:
$(document).ready(function(){
$(".clicktoviewreplies").click(function(){
//$(this).closest('ul').next('.replies').hide();
//$('.replies').
$('.replies').not($(this).next('.replies')).css("display", "none");
$(this).next('.replies').slideToggle(100);
});
});
And also change the text to "show/hide replies".
As for the first problem (reply buttons and comment and "subcomment" forms), delete the "style" tag and all css, except the attribute "display: none". Remember that the jQuery or even a Javascript code might have a malfunction since you're using something beyond the class itself needed to identify the element in the code. I don't know how to explain why this happens.
So instead of using:
<div class="replyto" style="margin-left:5%; position:relative;">
Use:
<div class="replyto">
And in CSS, use only:
.replyto
{
display: none;
}
And a tip: for a matter of having a well structured and "understable" way of code implementation, you could avoid "style" tags and use only CSS organized in a separated stylesheet document. I hope to have helped you, dude.

Multiple, dynamic dropdown list based on user selection

I have read through all the "dynamic multiple dropdown lists" questions here on stackoverflow but could not find what I am looking for.
It's a form for states and cities. User select a state, through ajax I request the cities for that specific state ID.
But, I need to have the two selects already created and displayed (maybe the city select grayed out). An example here PenskeAutomotive.
What I managed to do so far is to have only the state select and upon the execution of ajax, from the XMLHttp.ResponseText to create the city select. An example here Dorpdown list example - at bottom of page.
I need to have both selects displayed and then only update the city select with the new values of the XMLHttp.ResponseText.
Can anybody point me to some direction?
UPDATE:
Right after posting I found a question that I have not read before. Went into it and I may have found my direction. I am just trying that right now. It's jQuery/Ajax. Question
Not sure where you're having trouble, but to (hopefully) point you in the right direction:
You could have both of your <select> elements created on the page, with the City dropdown having the HTML disabled attribute, which will gray it out.
The disabled dropdown will have no options, aside from maybe one that says something like "select state."
You'll add an onchange event listener to your State dropdown which will perform the AJAX call, and I would recommend you get your response back in JSON format.
Then you can clear out the options of the next dropdown and create and append the new options from your server, then enable the dropdown.
If you want to provide what you've done so far, I'm sure we can help debug it.
I use this code in my site, maybe is usefull for you:
in head:
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(){
$("#select1").change(function(event){
var id = $("#select1").find(':selected').val();
$("#select2").load('../scripts/depto.php?id='+id);
});
});
</script>
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function(){
$("#select2").change(function(event){
var id = $("#select2").find(':selected').val();
$("#select3").load('../scripts/municipios.php?id='+id);
});
});
</script>
and in select:
<div class='control-group'>
<label class='control-label' for='typeahead'>PaĆ­s </label>
<div class="controls">
<select name="IDPAIS" id="select1" required>
<?
$sql = $conn->prepare("SELECT * FROM lista_paises");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion].'</option>';
}
?>
</select>
</div>
</div>
<div class='control-group'>
<label class='control-label' for='typeahead'>Departamento </label>
<div class="controls">
<select name="departamento" id="select2" required></select>
</div>
</div>
<div class='control-group'>
<label class='control-label' for='typeahead'>Municipio / Ciudad</label>
<div class='controls'>
<select name="ciudad" id="select3" required></select>
</div>
</div>
in the lista_paises.php
<?
include('../include/config.php');
$query = $conn->prepare("SELECT * FROM PAISES);
$respuesta="[";
foreach ($aMunicipios as $muni) {
$respuesta .="{id:".$muni["id_municipio"].",nombre_municipio:'".$muni["municipio_nombre"]."'},";
}
$respuesta = substr($respuesta,0,strlen($respuesta)-1);
$respuesta.="]";
echo $respuesta;
}
?>
in depto.php
<?
include('../include/config.php');
$sql = $conn->prepare("SELECT * FROM lista_estados WHERE relacion = ".$_GET['id']);
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion1].'</option>';
}
?>
in municipios.php(ciudad/city)
<?
include('../include/config.php');
$sql = $conn->prepare("SELECT * FROM MUNICIPIOS WHERE relacion1 = ".$_GET['id']);
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo
'<option value="'.$row[id].'">'.$row[opcion2].'</option>';
}
?>
maybe works for you

Drop down list solution?

I am a newby so appologise for asking a basic question.
I have a php page - a 'create new project' page
There are some simple data such as name, deadline etc...
but depending on the type of the project I have 4 different ends (different pages?) in this FORM and I can't find the solution for it.
Here is my code:
<h1>New Project</h1>
<form name="newpr">
New project name:<input type="text" placeholder="new project name..."><br />
New project end date:<input type="text" placeholder="date..."><br />
New project type:
<select name="menu" onChange="location=document.newpr.menu.options[document.newpr.menu.selectedIndex].value;" >
<?php
$listdata = mysql_query("SELECT * FROM lists WHERE tag='prtype' ORDER BY listing ASC");
while($listresult = mysql_fetch_array($listdata))
{
if ($listresult["listing"]!="...") $link=$listresult["value"].".php";
else $link="";
echo "<option value='".$link."'>".$listresult["listing"]."</option> ";
}
?>
</select>
</form>
As you see the select list comes from Mysql and I would like a div under a form to be able to open page1.php or page2.php etc as user selects...
Thanks in advance
Andras
it might be ajax question...
I'd solve this the following way
<!-- using jQuery -->
<h1>New Project</h1>
<form method="" action="post">
New project name:<input type="text" placeholder="new project name..."><br/>
New project end date:<input type="text" placeholder="date..."><br/>
New project type:
<select name="menu">
<?php
$listdata = mysql_query("SELECT * FROM lists WHERE tag='prtype' ORDER BY listing ASC");
while($listresult = mysql_fetch_array($listdata))
{
$link = '';
if($listresult['listing'] != '...') {
$links = $listresult['value'] . ".php";
echo "<option value='$link'>${listresult['listing']}</option>";
}
}
?>
</select>
<div id="page">
<!-- container for loaded page -->
</div>
<script type="text/javascript">
$("select[name=menu]").change(function() {
var url = $("option:selected", this).val();
// Load a page to the container
$("#page").load(url);
});
</script>
</form>
Using jQuery I added on change handler on select box and if it's changed it loads via ajax a page to the div container.
And let me give you and advice - try to avoid mixing code and html. It leads to difficulties in further development and maintenance.
You want to make a HTTP request to your php page Checkout http://mootools.net/docs/core/Request/Request.HTML
http://mootools.net/docs/more/Request/Request.JSONP
Listen for the callback on your request then inject the returned data as an element into the DOM. Mootools is my weapon of choice but Jquery etc. all have this same functionality. call php page under Javascript function This question is very similar to yours.

PHP Pass variable to popup form within same page

Following on from a previous question, (previous question here), the problem I'm having seems to involve trying to pass/post a value through a form when the form action is '#'. I've tried session data but it always returns the last item from the database. Everthing else returns nothing.
Any help/ideas/advice greatly received, S. (Code below)
This is the code that displays the list of items, each containing an 'email' link/button to one instance of a popup window/form that is located at the bottom of the page.
<?php
$query = mysql_query("select * from istable where categoryID = '1'");
while ($result = mysql_fetch_array($query)) {
echo '<h4>'.$result['title'].'</h4>
<p>'.substr($result['descrip'],0,408).'... <strong>Read more</strong></p>
<form action="#" method="post" rel="#sheet" class="see">
<input type="hidden" name="propTitle" value="'.$propResult['title'].'">
<input type="submit" name="submit" value="Email">
</form>
';
}
?>
This is the code for the popup window/form at the bottom of the same page that is called through jquery.
<div id="sheet" class="rounded">
<!--{{{ pane1 -->
<div class="pane" id="pane1">
<h4>Email Details to a Friend</h4>
<p>You have selected to forward the details of <?php echo $_POST['propTitle']; ?> to a friend.</p>
<p>Please fill out the following form</p>
<form class="rounded" id="email-form" method="post" action="<?php echo $pageLink; ?>">
<!-- form goes in here -->
</form>
</div>
<!--}}}-->
</div>
<script type="text/javascript">
$(".see").overlay({mask: '#999', fixed: false}).bind("onBeforeClose", function(e) {
$(".error").hide();
});
</script>
Why are you using PHP for this? If the popup is called through the same page, use JavaScript to get the DOM element value and if you need to process data use AJAX.

Categories