How to display only one specified div in jquery - php

I am trying to display one specified div when I am clicking on button with class .showFormButton, but unfortunetly every div with class .showForm appears. How to make only one .showForm div appear using jQuery?
JQUERY:
$(document).ready(function() {
$(".showFormButton").click(function(e){
e.preventDefault();
$(".showForm").css('display', 'block');
$(".showForm").css('position', 'absolute');
});
});
HTML
print "<input type='submit' class='showFormButton' VALUE='Ulubiony' onclick='ShowDiv()'>";
print "<div style='display: none; margin-left: -170px; margin-top: -60px; background-image: linear-gradient(rgb(15, 159, 220),rgb(14, 108, 148));' class='showForm'>";
print "<div >";
print "<p><b>Dodaj do ulubionych pracownika</b></br> [".$row['imie1']. " ".$row['nazwisko1']."]</p>";
print "<p>Osobista notatka</p>";
print "<FORM ACTION='view_tm.php' METHOD='POST' ENCRYPT='multipart/form-data' name='ulubiony_pracownik_dodaj'>";
print "<textarea name='id_pracownik_op_notatka' rows='10' cols='45'>". $row['notatka'] ."</textarea>";
print "<input type='hidden' name='id_pracownik_op' value='" . $row['id_pracownik'] . "'>";
print "<INPUT TYPE='submit' id='showFormButton' NAME='ulubiony_pracownik' VALUE='Dodaj do ulubionych'>";
print "</form>";
print "</div>";

You have to use this object to target your selection over the clicked element,
$(document).ready(function() {
$(".showFormButton").click(function(e){
e.preventDefault();
var elm = $(".showForm", this)
elm.css({'display' : 'block', 'position' : 'absolute' });
});
});
Instead of using .css() for setting the properties, you could use .addClass(). Because it would be easy in maintaining, like removing the added properties in future.
$(document).ready(function() {
$(".showFormButton").click(function(e){
e.preventDefault();
var elm = $(".showForm", this)
elm.addClass("clicked");
});
});
CSS:
.clicked { display:block; position:absolute; }
Edit:
Since the target element is the next sibling the the current element, you have to use .next(selector) at this context.
$(document).ready(function() {
$(".showFormButton").click(function(e){
e.preventDefault();
var elm = $(this).next(".showForm")
elm.css({'display' : 'block', 'position' : 'absolute' });
});
});

jQuery has the .show() function to make hidden stuff visible. Take a look at this code snippet:
$(document).ready(function () {
$(document).on('click', '.action-btn', function () {
$('.hidden-div').show();
});
));
<div style="display: none;" class="hidden-div">
Hidden text
</div>
<button class="action-btn">Show hidden div</button>

You can distinguish the div by using an attribute
$(document).ready(function() {
$(".showFormButton").click(function(e){
e.preventDefault();
$(".showForm[showme='1']").css('display', 'block');
$(".showForm[showme='1']").css('position', 'absolute');
});
});
HTML
print "<input type='submit' class='showFormButton' VALUE='Ulubiony' onclick='ShowDiv()'>";
print "<div showme='1' style='display: none; margin-left: -170px; margin-top: -60px; background-image: linear-gradient(rgb(15, 159, 220),rgb(14, 108, 148));' class='showForm'>";
print "<div >";
print "<p><b>Dodaj do ulubionych pracownika</b></br> [".$row['imie1']. " ".$row['nazwisko1']."]</p>";
print "<p>Osobista notatka</p>";
print "<FORM ACTION='view_tm.php' METHOD='POST' ENCRYPT='multipart/form-data' name='ulubiony_pracownik_dodaj'>";
print "<textarea name='id_pracownik_op_notatka' rows='10' cols='45'>". $row['notatka'] ."</textarea>";
print "<input type='hidden' name='id_pracownik_op' value='" . $row['id_pracownik'] . "'>";
print "<INPUT TYPE='submit' id='showFormButton' NAME='ulubiony_pracownik' VALUE='Dodaj do ulubionych'>";
print "</form>";
print "</div>";

Related

Only 1 data submitted into database (food ordering system)

I am new on implementing Ajax on PHP so I need a big help! anyways my problem is I have a 5 column names on my table_menu
table_menu:
menu_id
menu_foodname
menu_price
menu_quantity
menu_image
and inside those column names it has 6 datas.
And I will gonna fetch those datas on my webpage(users.php)
<?php
// users.php
// fetching data
include 'config/initialize.php';
$sql = "SELECT * FROM table_menu";
$res = mysqli_query($con, $sql);
if($res)
{
echo "<table><tr>";
while($row = mysqli_fetch_array($res))
{
echo "<td>";
echo "<div class='horizontalAlign'>";
echo "<form class='form-item' method='post'>";
echo "<img class='img-circle' src='menuImage/".$row['menu_image']."' style='height: 150px; width: 200px;'>";
echo "<input type='hidden' name='menuimage' class='menuimage' value='".$row['menu_image']."'>";
echo "<input type='text' name='menufoodname' class='menufoodname' value='".$row['menu_foodname']."' style='border:none; margin-top: 10px; margin-left: 30px; font-size: 20px;' readonly>";
echo "<div style='font-size: 20px; margin-left: 40px;'>Price:</div> <input type='text' class='menuprice' name='menuprice' value='".$row['menu_price']."' style='border:none; margin-left: 100px; margin-top: -28px; position: absolute; font-size: 20px;' readonly>";
echo "<div style='font-size: 20px;'>Quantity:</div> <input type='number' class='menuquantity' name='menuquantity' style='margin-top: -26px; position: absolute; margin-left: 90px; text-align: center;' value='".$row['menu_quantity']."' min='0' max='100'>";
echo "<br>";
echo "<input type='button' value='Submit order' class='btnaddorder btn btn-lg btn-info' class='btn btn-info'>";
echo "</form>";
echo "</div>";
echo "</td>";
$i++;
if($i == 3)
{
echo "</tr><tr>";
}
} // end of while
echo "</tr></table>";
} // end of variable $i
?> <!-- // end of fetching data -->
and I want the page to be not refresh while the user orders... so I add this ajax script on the bottom of users.php
<script type="text/javascript">
$(document).ready(function() {
$(".btnaddorder").click(function() {
var menuimage = $(".menuimage").val();
var menufoodname = $(".menufoodname").val();
var menuprice = $(".menuprice").val();
var menuquantity = $(".menuquantity").val();
// Returns successful data submission message when the entered information is stored in database.
$.post("addorders.php", {
menuimage1: menuimage,
menufoodname1: menufoodname,
menuprice1: menuprice,
menuquantity1: menuquantity,
}, function(data) {
});
});
});
</script>
Now the problem is when I am clicking the first button on the fetched datas the first one only got inserted and if I am add the second item even the third until fifth item it only display one data on the database which is the first data, why?
heres my addorders.php
<?php
include 'config/initialize.php';
include 'credentials/credentialsForUsers.php';
$menuimage = $_POST['menuimage1'];
$menufoodname = $_POST['menufoodname1'];
$menuprice = $_POST['menuprice1'];
$menuquantity = $_POST['menuquantity1'];
$sql = "INSERT INTO table_orders VALUES('','$username','$email','$menuimage','$menufoodname','$menuprice','$menuquantity')";
$result = mysqli_query($con, $sql);
?>
thank you & sorry for my bad english. hope you understand my problem
To clarify which fields you want to submit you can do the following:
$(".btnaddorder").click(function() {
// here you find closest form tag to the pressed button
var form = $(this).closest('form');
// replace all you values with simple .serialize() function
// this function will use all non-disable fields from the form
$.post("addorders.php", form.serialize(), function(data) { });
});
On the serverside your $_POST will have the same keys as fields on your form.

Passing a variable in $_POST parameters not working in PHP?

I am displaying images from a database, each image has a comment box that contains a form and a submit button; the submit button has the name of the image that is displayed. Ex. if the image name is flowers.jpg, the name for the submit button is set to flowers.jpg. (I did string replace though, so in my code it would be set to flowersjpg) The names are added to the submit button with no problem at all. Because I have several images, I wanted to pass $row['image'] (image name) into $_POST[ ] parameters for an isset() function but it is not working. - All the code is in one document
$result = mysqli_query($conn, "SELECT * FROM uploads ORDER BY timestamp DESC");
while($row = mysqli_fetch_array($result))
{
// Prints all the photos with a caption
echo "<div class='wrapper' name=".$row['image'].">";
echo "<div class='caption'>";
echo "<h3>".$row['title']."</h3>";
echo "<p class='description'>".$row['description']."</p>";
echo "</div>";
echo "<img src='images/uploads/".$row['image']."'/>";
// name for submit button, the $row['image'] contains the entire image name so certain characters have to be removed
**$name = str_replace(array(".", "-", ":", "'", "/", " "), "", $row['image']);**
// comment box - just a form with a submit
echo "<div class='commentBox'>
<form action='test.php' method='POST'>
<textarea placeholder='Say something nice!' name='comment'></textarea>
// CREATES NAME FOR BUTTON. FOR EACH IMAGE, THE BUTTON HAS THE IMG NAME
**<button type='submit' name='".$name."' value='submit'> post </button>**
</form>
</div>";
echo "</div>";
}
if(isset($_POST["'".$name."'"]))
{
echo '<script type="text/javascript"> alert("isset"); </script>';
}
When I put the name as a plain string in the $_POST parameters, it works fine but when I put the variable in, it does not work. The $name variable is a string.
This works but I'm sure any string used will work as long as the button name and string in $_POST are the same.
echo "<button type='submit' name='flowerspng' value='submit'> post </button>";
if(isset($_POST[flowerspng]))
{
echo '<script type="text/javascript"> alert("isset"); </script>';
}
This code on the other hand, does not. I know variables can be passed inside $_POST parameters, so I don't understand what's wrong with my code. Is my syntax incorrect? Clearly the variable is not being set otherwise the alert box would pop up.
echo "<button type='submit' name='".$name."' value='submit'> post </button>";
if(isset($_POST["'".$name."'"]))
{
echo '<script type="text/javascript"> alert("isset"); </script>';
}
I have tried this too but I don't think it worked because there are no quotes around $name.
echo "<button type='submit' name=$name value='submit'> post </button>"
if(isset($_POST[$name]))
{
echo '<script type="text/javascript"> alert("isset"); </script>';
}
This code works:
echo "<button type='submit' name='$name' value='submit'> post </button>"
if(isset($_POST[$name]))
{
echo '<script type="text/javascript"> alert("isset"); </script>';
}
I moved the if statement for the isset() function into the end of the while loop, it works for all images now.
while($row = mysqli_fetch_array($result))
{
echo "<div class='wrapper' name=".$row['image'].">";
echo "<div class='caption'>";
echo "<h3>".$row['title']."</h3>";
echo "<p class='description'>".$row['description']."</p>";
echo "</div>";
echo "<img src='images/uploads/".$row['image']."'/>";
$name = str_replace(array(".", "-", ":", "'", "/", " "), "", $row['image']);
echo "<div class='commentBox'>
<form action='test.php' style='text-align: right; background-color: rgb(34,34,34); width: 100%; height: 120%; margin: 0;' method='POST'>
<textarea style='height: 90%; width: 79%; resize: none; border-radius: 3px; margin: 0; margin-top: 5px;' placeholder='Say something nice!' name='comment'></textarea>
<button type='submit' name='$name' value='submit' style='height: 100%; width: 20%; float: right;'> post </button>
</form>
<div class='seeMore'> see more </div>
</div>";
echo "</br><div class='comments' style='display: none;'> comment display </div>";
echo "</div>";
**
// testing the if statement for each image - works perfectly now
if(isset($_POST[$name]))
{
echo '<script type="text/javascript"> alert("'.$name.'"); </script>';
mysqli_query($conn, "UPDATE uploads SET title='test' WHERE image='".$row['image']."'");
header("Refresh:0");
}
**
}

The JQuery function is not working [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 9 years ago.
Hi I click on one of the links given in the save column. Once it is clicked the code between the script tags should be run and give an alert ('BBBBBBBBBBBBBBBBBBBB'). But I can't figure out why it doesn't give the expected result. Please someone help me to correct this
<html>
<title></title>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script></head>
<script>
$(".QuestionEdit").click(function(){
alert('BBBBBBBBBBBBBBBBBBBB');
var B=$(this).attr('id');
var Data=B.replace("QuestionEdit","");
alert(Data);
return false;
});
</script>
</head>
<body>
<?php
echo "<form>";
echo "<div id='QuestionDetails' style=' position:relative; top=50px;'>";
$Query="SELECT * FROM Questions WHERE Form_ID='0'";
echo "<table border='1' id='DisplayFormDetailss'>
<tr style='background-color:#D0A9F5;' height='40px;'>
<th width='100px;'>Question_ID</th>
<th width='420px;'>Question Name</th>
<th width='100px;'>Inactivate</th>
<th width='70px;'>Edit</th>
</tr>";
$i=0;
while($i<5){
echo "<tr height='25px;'>";
echo "<td><input name='QuestionID[]' id='QuestionID ".$i."' align=center value='8'></input></td>";
echo "<td><input name='QuestionName[]' style='width:420px;' id='QuestionName".$i."' align=left value='7'></input></td>";
echo "<td name='QuestionInactive[]' id='QuestionInactive".$i."' align=center><input type='checkbox'></input></td>";
echo "<td class='QuestionEdit' id='QuestionEdit".$i."' align=center><a href='' align=left>Edit</a></td>";
echo "</tr>";
$i++;
}
echo "</table>";
echo "</div>";
echo "<div id='Sub' style='position:relative; top:50px;'>";
echo "<input type='submit' value='Save The Table'></input>";
echo "</div>";
echo "</form>";
?>
</body>
</html>
The div.QuestionEdit is not loaded when the script executes. Wrap the script in $(document).ready() to execute when the DOM is available.
$(document).ready(function(){
$(".QuestionEdit").click(function(){
alert('BBBBBBBBBBBBBBBBBBBB');
var B=$(this).attr('id');
var Data=B.replace("QuestionEdit","");
alert(Data);
return false;
});
});
Solution:
$(document).ready(function() {
$(".QuestionEdit").click(function(){
alert('BBBBBBBBBBBBBBBBBBBB');
var B=$(this).attr('id');
var Data=B.replace("QuestionEdit","");
alert(Data);
return false;
});
});
Your script is running before the document has loaded.
Use the document ready callback to run any jQuery code that needs to access the DOM so it runs when the DOM is loaded.
$( document ).ready(function() {
// Handler for .ready() called.
});

How to add new dynamic content to my JS code?

I have been developing a simple page, and there is the problem - my page contains a table with 2 columns; if user moves his cursor to the second column it transforms in editable field and user can edit it and do some actions. Also the page contains links for pagination; if user clicks by link, for example, "2", then table change its content dynamically using Ajax/Jquery. So, my code works good for initial screen, but if I change a page then I can't edit any field in the second column, i.e. code for editing doesn't work now. So, please, tell me, how can I fix it? JS code:
<script type="text/javascript" charset="utf-8">
function hide_info_block(block_id) {
$('#info_block').hide();
}
$(function()
{
var old_value='No translate';
var item_id='';
var item;
$('.field').hover(
function()
{
old_value=$(this).text();
item_id=$(this).attr('id');
item=$(this).parent('td');
new_value=(old_value=='Not translated') ? '' : old_value;
$(this).empty();
var field="<div id='save_button' class='btn btn-primary' style='float: right' href='#'>Save</div><form>"+
"<div style='overflow: hidden; padding-right: .5em;'>"+
"<input id='new_value' type='textarea' name='term' style='width: 100%;' value='"+new_value+"'/></div></form>";
$(this).html(field);
},
function()
{
$(this).empty();
$(this).html(old_value);
});
$('#save_button').live('click', function() {
if ($.trim($('#new_value').val()).length==0)
{
alert ('The string is empty');
return;
}
var loader="<td><img id='small_loader' style='position:absolute' src='/small_loader.gif' /></td>";
item.after(loader);
var old_val=old_value;
var new_val=$.trim($('#new_value').val());
$.post("http://"+document.location.host+"/index.php/welcome/update_record", { old_value: old_val,
value: new_val, id: item_id} ,
function(data) {
var message="Message";
var json = jQuery.parseJSON(data);
var item_id=json.id.replace(/([!"#$%&'()*+,./:;<=>?#\[\\\]^`{|}~])/g, "\\$1");
if (json.result=='LOGIN') {
message="You need to enter before making any actions";
$('#'+item_id).html(json.old_value);
}
else {
if (json.result=='OK') {
$('#'+item_id).css('color', '#000000');
message="Your correction has been added successfully";
$("#"+item_id).html(json.language_value);
}
else {
message="Your correction has been updated successfully";
$('#'+item_id).html(json.language_value);
}
}
$('#small_loader').remove();
alert(message);
});
});
$('.page_button').live('click',function() {
$('#ajaxBusy').show();
$('.selected_page_button').attr('class','page_button');
$(this).attr('class','selected_page_button');
$.post("http://"+document.location.host+"/index.php/welcome/update_records_set/"+this.id,
function(data)
{
if (data != "")
{
$(".records_content:last").empty();
$(".records_content").html(data);
}
$('#ajaxBusy').hide();
});
});
});
</script>
Table code:
<div class="records_content">
<table>
<tbody>
<?php
$i=0;
foreach ($records as $record) {
//echo "<tr class = 'output' style='border-bottom: 1px dotted silver;'>";
echo "<tr class = 'output' style='border-bottom: 1px dotted silver;'>";
echo "<td width='400'>" . strip_tags($record['translate']['language_value']) . "</td>";
if ($record['translate']['coalesce(loc.language_value)'])
{
echo "<td width='200' height='30'><div class='field' id='".$record['translate']['label_value']."/".$record['language_id']."'>".
strip_tags($record['translate']['coalesce(loc.language_value)'])."</div>";
if (count($record['alternatives']))
{
echo "<br/><b>Alternatives:</b>";
echo "<ul>";
foreach ($record['alternatives'] as $alternative)
{
echo "<li>".strip_tags($alternative['coalesce(loc.language_value)'])."</li>";
}
echo "</ul>";
}
}
else
{
echo "<td width='200'>"."<div class='field' style='font-style: italic; color: #FF0000' id='".$record['translate']['label_value']."/".$record['language_id']."'>Not translated</div>";
if (count($record['alternatives']))
{
echo "<br/><b>Alternatives:</b>";
echo "<ul>";
foreach ($record['alternatives'] as $alternative)
{
echo "<li>".strip_tags($alternative['coalesce(loc.language_value)'])."</li>";
}
echo "</ul>";
}
}
echo "</td>";
$i++;
}
?>
</tbody>
</table>
</div>
UPDATE 2:
$('body').on({
mouseenter: function(event)
{
old_value=$(this).text();
item_id=$(this).attr('id');
item=$(this).parent('td');
new_value=(old_value=='Not translated') ? '' : old_value;
$(this).empty();
var field="<div id='save_button' class='btn btn-primary' style='float: right' href='#'>Save</div><form>"+
"<div style='overflow: hidden; padding-right: .5em;'>"+
"<input id='new_value' type='textarea' name='term' style='width: 100%;' value='"+new_value+"'/></div></form>";
$(this).html(field);
},
mouseleave: function(event)
{
$(this).empty();
$(this).html(old_value);
}}, '.field');
You're adding a hover handler to your .field only once. When you change your .field by loading it through AJAX, it becomes a different element without any event handlers.
attach the hover event handler after loading the new .field.
OR
use delegated event handlers.
$('body').on({
mouseenter: function() {
//code when mouse enters .field
},
mouseleave: function() {
//code when mouse leaves .field
}
}, '.field');
Try running it in Google Chrome and press F12 so you have the JavaScript debugger available. Use the [Console] tab so see whether any errors are occurring. Its surprising what you can learn from this and what JavaScript is doing behind the scenes!

How can we create custom style for Jquery-ui dialog window in PHP?

I am having a PHP page which the result table contain a link that opens a popup box. Earlier I used JavaScript. But I want to hide the address bar, so this cant be done in JavaScript(hope so). So I tried using jQuery-ui for this.
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css">
<style type="text/css">
#data-specs {
border-collapse: collapse;
}
#data-specs th,
#data-specs td {
padding: 0px;
border: 0px;
}
.loading {
position: absolute;
top: 50%;
left: 50%;
margin-top: -8px;
margin-left: -8px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var $loading = $('<img src="loading.gif" alt="loading" class="loading">');
$('#data-specs a').each(function() {
var $dialog = $('<div></div>')
.append($loading.clone());
var $link = $(this).one('click', function() {
$dialog
.load($link.attr('href'))
.dialog({
title: 'Dialog Title',
width: 500,
height: 300
});
$link.click(function() {
$dialog.dialog('open');
return false;
});
return false;
});
});
});
</script>
</head>
My table part code is like this:
print "<table width='875' id='data-specs' align='center'>";
while($row = mysql_fetch_array($result))
{
print "<tr height='18'>";
print "<td width=200 align=left style='padding-left:10px'>" . $row['Country'] . "</td>";
print "<td width=70 align=center>" . $row['MidEstimate'] . "</td>";
print "<td width=70 align=center>" . $row['LowEstimate'] . "</td>";
print "<td width=70 align=center>" . $row['HighEstimate'] . "</td>";
print "<td width=118 align=center>" . $row['Source'] . "</td>";
print "<td width=110 align=center>" . $row['StudyLocation'] . "</td>";
print "<td width=89 align=center>" . $row['Relevance'] . "</td>";
print "<td width=89 align=center>" . $row['Quality'] . "</td>";
print "<td width=61><a style='color:#E46D0A;' href='popupboxD.php?SId=$vv'>".$row['Info']."</a></td>";
print "</tr>";
}
}
if(empty($result)){
print "<table width='875' align='center'>";
print "<tr height='1'><td colspan='9'><font color='#000080'><b>Does not have information on this particular selection.</b></font></td></tr>";
print "</table>";
Now the problem is its all works well. But when I click the link, the jQuery dialog box opens and the style(css) for my parent window is also changing? I want the style to be applied only for dialog window also I want to change the look and feel of dialog window? How can I do this? please help me in this.
Update
I am using this code in drupal 6, but when I click the link the pop-up is not opening as a modal dialog window. IT opens completely in the parent window? How can I in-corporate jQuery UI in drupal 6 with same code? Please help me.
To make your own jQuery ui styling (a theme), make your changes on jquery ui themeroller. After that you can download it (before you should deselect all components), if it's a zip decompress it, save the files on your server and replace the href attribute of you following line:
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css">
But this will change all jQuery ui elements of this page.
=== UPDATE ===
To make the dialog modal you have to add the modal option.
.dialog({
...
modal: true
})
Also see my updated jsfiddle.
In general, PHP has nothing to do with JQuery, Javascript, HTML controls and all that stuff.
PHP is merely a text processor. It is your job to determine, what text to output. PHP won't do it for you.
Once you done with text - then you can print it out with PHP. It is not a big deal too - there are simple formatting rules for the PHP strings.
However, to output large amounts of texts. you can just escape from PHP:
<?
//some PHP
?>
<table width='875' align='center'>
<tr height='1'>
<td colspan='9'>
<font color='#000080'>
<b>Does not have information on this particular selection.</b>
</font>
</td>
</tr>
</table>
<?
//PHP again
?>

Categories