Table Row attr() Issue - php

I'm stuck on a piece of code that calls a jQuery modul populated with a table row id. I'm about 90% sure that the error is within my jQuery code. Once I click on the button (class="view"), I get an undefined value instead of the row ID.
Thanks for any help!
Relevant section of leads_queue_a.php:
<section class="main">
<h1>Lead Queue - Assigned Leads</h1>
<div id="lead_wrapper_a"></div>
</section>
fill_leads_a.php:
$cond = array();
$params = array();
if ($_POST['id'] == '') {
return;
}
if (isset($_POST['id']) && $_POST['id'] != '') {
$userID = $_POST['id'];
}
if (!empty($userID)) {
$cond[] = '`users`.`id` = ?';
$params[] = "$userID";
}
$query = "SELECT `leads`.`id`, `leads`.`fname`, `leads`.`lname`, `leads`.`lead_type`, `leads`.`addr_street`, `leads`.`addr_city`, `leads`.`addr_zip`, `leads`.`phone`, `leads`.`phone_alt`, `leads`.`note`, `leads`.`created_by`, `leads`.`created` FROM `leads`,`users`,`leads_assignment`";
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond);
}
$query .= ' AND `leads`.`id` = `leads_assignment`.`id_lead`'
. ' AND `users`.`id` = `leads_assignment`.`id_user`';
$stmt = $db->prepare($query);
$stmt->execute($params);
//TABLE BUILDER
$lead = '';
$lead .= '<div class="leads">';
$lead .= '<table class="lead_table">';
$lead .= '<tr>';
$lead .= '<td>Customer</td>';
$lead .= '<td>Phone</td>';
$lead .= '<td>Lead Type</td>';
$lead .= '<td>Status</td>';
$lead .= '<td>Operations</td>';
$lead .= '</tr>';
foreach ($stmt->fetchAll(PDO::FETCH_OBJ) as $row) {
$id = $row->id;
$status = get_statusLast($id);
$fname = $row->fname;
$lname = $row->lname;
$lead_type = $row->lead_type;
$addr_street = $row->addr_street;
$addr_city = $row->addr_city;
$addr_zip = $row->addr_zip;
$phone = $row->phone;
$phone_alt = $row->phone_alt;
$note = $row->note;
$created_by = $row->created_by;
$created = $row->created;
$lead .= "<tr id='$id'>";
$lead .= '<td>' . $fname . ' ' . $lname . '<br />' . $addr_street . '<br />' . $addr_city . ' ' . $addr_zip . '</td>';
$lead .= '<td>' . $phone . '<br />' . $phone_alt . '</td>';
$lead .= '<td>' . $lead_type . '</td>';
$lead .= '<td>' . $status . '</td>';
$lead .= '<td><button type="button" class="view" name="view">View Notes</button><br />'
. '<button type="button" class="update" name="update">Update Status</button></td>';
}
$lead .= '</table>';
$lead .= '</div>';
$db = null;
print $lead;
Relevent section of modul.js:
$("#lead_wrapper_a").on('click', '.view', function() {
alert($('tr', this).attr('id'));
});

Because your selction is incorrect. Use closest to get to the clicked buttons parent row (tr). Using the syntax $('tr', this) you are trying to find tr that are descendant of the button .view which is incorrect. You need to go upwards to get to the tr. this in the handler will be the button.
alert($(this).closest('tr').attr('id'));

You are trying to search row tr in descendant of button but button is descendant of row tr. You probably need closest() to get the ancestor row, to get the parent row of button having class view.
$("#lead_wrapper_a").on('click', '.view', function() {
alert($(this).closest('tr').attr('id'));
});

You cant find tr within the context of this, Because tr is the ancestor of the source button in your case. So you have to use .closest() to achieve the desired result.
Try,
$("#lead_wrapper_a").on('click', '.view', function() {
$( "#dialog_view" ).dialog( "open" );
alert($(this).closest('tr').attr('id'));
});

when it comes to table its bit tricky.
for your first line you want to select the entire path of class "view". I dont know your exact path but it should be someting like this.
$("#lead_wrapper_a").on('click', '"#lead_wrapper_a > table > tbody > tr > td.view', function() {
});
Hope this helps

Related

I want to display subject for specific class i.e A or B but current I display only A?

I try to display every each data on the specific td, but I dont know where to fix my code. Please check the screenshop below to understand the clearly problems. Please any help to solve this problems.
<table class="table table-hover table-bordered ">
<tr><th>Day</th><th colspan="2">08:00-08:40</th><th colspan="2">8:40-09:20</th><th colspan="2">09:20-10:00</th><th>10:00-10:15</th><th colspan="2">10:15-10:55</th><th colspan="2">10:55-11:35</th><th colspan="2">11:35-12:15</th><th>12:15-01:15</th><th colspan="2">01:15-01:55</th><th colspan="2">01:55-02:35</th></tr>
<?php
$timesVariants = array("08:00-08:40", "08:40-09:20", "09:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-01:15", "01:15-01:55","01:55-02:35");
$sqlquery = "SELECT * FROM timetable,classroom,subprogramme WHERE classroom.classid = timetable.classid AND subprogramme.subid = timetable.subid";
$res = $connect->query($sqlquery);
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('courseid'=> $row['cid'], 'classname' => $row['classname'], 'subname' => $row['subname']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time])){
print "<td>*</td><td>*</td>";
}
else{
print '<td>' . $teacher[$time]['courseid'] . '</td><td>' . $teacher[$time]['subname'] . ''. $teacher[$time]['classname'] . '</td>';
}
}
print '</tr>';
}
}
?>
</table>
Output
Results display on the webpage
You trouble is in the GROUP BY. MySql have no strict restrictions (by default) that each column should use aggregation function, so the result is the first row, instead of complicating SQL use PHP, your result seems not to be huge, so another loop will not affect performance:
$timesVariants = array("08:00-08:40", "08:40-09:20", "09:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-1:15", "01:15-01:55","01:55-02:35");
$sqlquery = "SELECT * FROM timetable";
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('subject'=> $row['subject'], 'class' => $row['class'], 'progid' => $row['progid']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time]))
print "<td>None</td><td>None</td>";
else
print '<td>' . $teacher[$time]['subject'] . '</td><td>' . $teacher[$time]['class'] . '</td>';
}
print '</tr>';
}
}
<?php
if(isset($_POST["tid"])){
$tid = $connect->real_escape_string($_POST["tid"]);
$sqlquery = "SELECT * FROM timetable,classroom,subprogramme WHERE classroom.classid = timetable.classid AND subprogramme.subid = timetable.subid AND timetable.tid = ".$tid." ORDER BY timetable.timid ASC";
$res = $connect->query($sqlquery);
if($res->num_rows > 0){
?>
<table class="table table-bordered table-striped">
<tr><th>Day</th><th colspan="2">8:00-8:40</th><th colspan="2">8:40-9:20</th><th colspan="2">9:20-10:00</th><th colspan="2">10:00-10:15</th><th colspan="2">10:15-10:55</th><th colspan="2">10:55-11:35</th><th colspan="2">11:35-12:15</th><th colspan="2">12:15-1:15</th><th colspan="2">1:15-1:55</th><th colspan="2">1:55-2:35</th></tr>
<?php
$timesVariants = array("8:00-8:40", "8:40-9:20", "9:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-01:15", "1:15-1:55","1:55-2:35");
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('courseid'=> $row['cid'], 'classname' => $row['classname'], 'subname' => $row['subname']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time])){
print "<td>*</td><td>*</td>";
}
else{
print '<td>' . $teacher[$time]['courseid'] . '</td><td>' . $teacher[$time]['subname'] . ''. $teacher[$time]['classname'] . '</td>';
}
}
print '</tr>';
}
}
?>
</table>
<?php
}
else{ print "<div class='alert alert-danger col-md-4'><span class='glyphicon glyphicon-remove'></span> Not yet set timetable</div>"; }
} ?>
</div>
The problems was on td I forgot to put colspan = 2, and other problem on sql query I forgot to inner join the tables in order to get all right that i want to display on the page.

function only returns one value multiple times

I have this function:
function get_content($text_to_match) {
$query = "SELECT * ";
$query .= "FROM table_name ";
$query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
$cont = mysqli_query($connection, $query);
if($content = mysqli_fetch_assoc($cont)) {
return $content;
} else {
return null;
}
}
But when I call it like:
<div>
<?php
for ($i = 1; $i < count(get_content("text_to_match")); $i++) {
echo '<article>' .
'<h3>' . get_content("text_to_match")["string1"] . '</h3>'.
'<p>' . get_content("text_to_match")["string2"] . '</p>' .
'</article>';
}
?>
</div>
I only get the first match in the DB repeated as many times as the number of found items.
Where have I gone wrong?
use this code then fetch data properly
while($content = mysql_fetch_array($cont))
{
return $content;
}
Your logic is at fault. You are calling get_content function to get all matches for the loop, as well as to get individual elements out of the list. This is:
bad logic - the 2nd use case doesn't make sense
excessive - you shouldn't need to run a database query just to output an already retrieved result
What you probably want to do is:
foreach (get_content('text_to_match') as $content) {
echo '<article>';
echo '<h3>' . $content['string1'] . '</h3>';
echo '<p>' . $content['string2'] . '</p>';
echo '</article>';
}
With a few modifications in combination with tips from #Anant and #Unix One's answer, I arrived at this working solution:
Function definition
function get_content($text_to_match, $multiple=false) {
$query = "SELECT * ";
$query .= "FROM table_name ";
$query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
$cont = mysqli_query($connection, $query);
if ($multiple) {
$content_array = [];
while($content = mysqli_fetch_array($cont)) {
$content_array[] = $content;
}
return $content_array;
} else {
if($content = mysqli_fetch_assoc($cont)) {
return $content;
} else {
return null;
}
}
}
Function calls
<?php
/* multiple items */
foreach(get_content("text_to_match", true) as $content) {
echo '<article>' .
'<h3>' . $content["string1"] . '</h3>' .
'<p>' . $content["string2"] . '</p>' .
'</article>';
}
?>
<?php
/* one item */
echo get_content("text_to_match")["string"];
?>

PHP JQuery Checkbox Array - Selecting only 1 value

Following is an ajax post page which renders the checkboxes on run-time. I am facing issue while writting the script for select all button, when I click on the button only 1 value is getting selected not the entire array:
<?php
session_start();
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("../includes/functions.php");
if(isset($_REQUEST['t']))
{
$td = $_REQUEST['t'];
$t = split(",",$td);
$all = "";
$box_in_row = 0 ;
$this_box="<table border=0><tr>";
foreach($t as $table)
{
$this_box = "<td><h3>$table</h3>";
$result = mysql_query("SHOW FULL COLUMNS FROM $table FROM prfxcom1_prfx");
$options = "";
while($r = mysql_fetch_object($result))
{
if(!empty($r->Comment))
{
$options .= "<br><input type=checkbox name=\"".$table."[]\" value='$r->Field' id=\"$table\">" . $r->Field;
}
}
if($table == "transfer_req")
{
$options .= "<br><input type=checkbox name=\"".$table."[]\" value='Net Profit' id=\"$table\">NetProfit";
}
$this_box .= $options;
// Button
$click = "$('#$table').attr('checked', 'checked')";
$button = "<br /><input style='margin-top:10px;' type='button' name='$table_button' id='$table_button' value=' Select All ' onclick=\"$click\"/>";
$all .= "<div class='tblBox'>".$this_box.$button."</div></td>";
}
//$all = "<table class=\"listing form\" cellpadding=\"0\" cellspacing=\"0\">".$all."</table>";
echo $all;
}
?>
Issue is faced in the line:
$click = "$('#$table').attr('checked', 'checked')";
Please suggest, I am stuck on this.
Thanks,
Hardik
WHAT???
$click = "$('#$table').attr('checked', 'checked')";
How can you write Javascript in the middle of a PHP file? It needs to be in script tags but even then PHP runs at the server and will not render your Javascript for you.
Add script tags, change your ID's to separate ones and give them the same class like tableClassName, and then write the following.
$(function(){
$('.tableClassName').attr('checked', 'checked')";
});
Ignoring the many issues with the code and simply answering the question:
You need to refer to the checkboxes using a class name not a ID (you have given them all the same ID)
For these lines: $options .= "<br><input type=checkbox name=\"".$table."[]\" value='$r->Field' id=\"$table\">" . $r->Field;
Change to: $options .= "<br><input type=checkbox name='" . $table . "[]' value='" . $r->Field ."' class='" . $table . "'>" . $r->Field;
For this line: $click = "$('#$table').attr('checked', 'checked')"; use single quotes or escape the $
Change to: $click = '$("."'.$table.'").attr("checked", "checked")';

How to fill a table with PHP & JSON?

In CodeIgniter, I'm trying to create a table which fills with data from the Facebook Graph API.
The JSON loads a controller which passes data to a view, and it is this view which is added to a pre-existing table.
My PHP view looks like this:
if (array_key_exists('is_community_page', $json)==FALSE){
echo '<tr>';
echo '<td>ID</td>';
echo '<td><a href="' . $json['link'] . '">'. $json['name'] .'</td>';
if (!empty($json['website'])) {
if (!preg_match("~^(?:f|ht)tps?://~i", $json['website'])) {
$json['website'] = "http://" . $json['website'];
}
echo '<td>' . $json['website'] . '</td>';
}
else {
echo '<td>N/A</td>';
}
if (!empty($json['likes'])) {
echo '<td class="num">' . number_format($json['likes']) . '</td>';
}
if (!empty($json['checkins'])) {
echo '<td class="num">' . number_format($json['checkins']) . '</td>';
}
echo '</tr>';
}
And the jQuery/JSON looks like this:
$.ajax({
url: "<?php echo site_url('controller/function'); ?>",
type: 'POST',
data: form_data,
success: function(data) {
$('#results_table').html(data);
}
});
But when the data is returned, it just inserts the <a> elements between the <table> tags, and none of the <td> or <tr>.
Can anyone see why it might be ignoring the table row and table data tags, yet still keeping anchor tags and all the desired content?
Have you tried print_r($json) before the if to see if you're getting any output whatsoever from the Facebook data?
As per the comments, adding <tbody> to the table seemed to fix this adequately.
Perhaps try appending markup to a string and return the final value?
$row_data = '';
if (array_key_exists('is_community_page', $json)==FALSE){
$row_data .= '<tr>';
$row_data .= '<td>ID</td>';
$row_data .= '<td><a href="' . $json['link'] . '">'. $json['name'] .'</td>';
if (!empty($json['website'])) {
if (!preg_match("~^(?:f|ht)tps?://~i", $json['website'])) {
$json['website'] = "http://" . $json['website'];
}
$row_data .= '<td>' . $json['website'] . '</td>';
} else {
$row_data .= '<td>N/A</td>';
}
if (!empty($json['likes'])) {
$row_data .= '<td class="num">' . number_format($json['likes']) . '</td>';
}
if (!empty($json['checkins'])) {
$row_data .= '<td class="num">' . number_format($json['checkins']) . '</td>';
}
$row_data .= '</tr>';
return $row_data;
}

HTML form - PHP not inserting into Database correctly

i'm only tring to make a form work.
Its a similar for than i am fillin now: question, text, tags.
Fine,
this is when i print the form
function imprimir_formulario_pregunta(){
$html = '<form id="pregunta" name ="pregunta" method="post" action="preguntas.php">';
$html .= '<h2>Pregunta</h2>';
$html .= '<input name="q" id="q" type="text" value=" "></input>';
$html .= '<h2>Explica tu duda</h2>';
$html .= '<textarea name="texto" id="texto" /
></textarea>';
$html .= '<h2>Etiquetas (separadas por comas)</h2>';
$html .= '<input name="tags" id="tags"/>';
$html .= '<input name="responde_a" style="display:none;" id="responde_a" value="0"/>';
$html .= '<button name="pregunta" id="pregunta" type="submit" >Publicar</button>';
$html .= '</form>';
echo $html;
}
this is when i recive data
if(isset($_POST['pregunta'])){
$p_title = $_POST['q'];
$p_text = $_POST['texto'];
$p_et = $_POST['etiquetas'];
$p_resp = $_POST['responde_a'];
post_pregunta($p_title,$p_text, $p_et, $p_resp);
this is when i process data
function obtener_id_pregunta($p,$t){
$consulta = mysql_query("SELECT * FROM preguntas WHERE pregunta='$p' && texto='$t'");
while($item = mysql_fetch_array($consulta)){
return $item['id'];
}
}
function post_pregunta($a,$t,$et,$r){
mostrar_notificacion("hemos entrado");
//// ******
if($a != '' && $t != ''){
$b = $a;
guardar_pregunta($b,$t,$r);
$id = obtener_id_pregunta($b,$t);
$temp = new etiqueta(0, '');
$basura = $temp->guardar_etiquetas($et, $id, $_SESSION['id']);
}else
mostrar_notificacion("hemos salido $a $t");
}
function guardar_pregunta($p,$t,$r){
$id_tmp = $_SESSION['id'];
$insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('$p','$t','$id_tmp',NOW(),'$r')";
$qry = mysql_query($insert);
if(mysql_affected_rows())
{
mostrar_notificacion("La pregunta $p ($t)($r) se guardo");
return true;
}
else
{
mostrar_notificacion("Error Ingresando datos");
return false;
}
return false;
}
Result:
I get the insert in the database done, but the 'q' field has a '' value....
Notes:
It looses the value in the step ** because it enters in the condition, but it doesn't in the next one wich is the same question...
Please tell me you have my answer, been too long on this.. and i need it done this week for class
Thanks in advance
It's hard to see what's going on - as #vincebowdren says, you just need to debug this every step of the way.
However, more worryingly you're using $_POST data directly in a SQL query - this is an SQL injection attack waiting to happen.
Ensure you wrap ALL such variables in a mysql_real_escape_string function within your queries.
e.g.:
$insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('".mysql_real_escape_string($p)."','".mysql_real_escape_string($t)."','$id_tmp',NOW(),'".mysql_real_escape_string($r)."')";
See How can I prevent SQL injection in PHP? for more information.
Use echo to print out the value of the troublesome variable ($_POST['q'], $p_title, $a) at every stage. Then you will see when it gets a value you weren't expecting.
#Toni Michel Caubet: I rewrote your code a little to make it more readable and should be slightly easier to debug as well. Please heed the /* comments */. I've left a lot of the work up to you with just some guides here and there.
Receive data:
if(isset($_POST['pregunta']))
{
$p_title = $_POST['q'];
$p_text = $_POST['texto'];
$p_et = $_POST['tags'];
$p_resp = $_POST['responde_a'];
/* Never trust user input, validate the data you're retrieving */
/* Keep variable names the same, or risk confusing yourself later */
post_pregunta($p_title, $p_text, $p_et, $p_resp);
}
Process data:
function post_pregunta($p_title, $p_text, $p_et, $p_resp)
{
mostrar_notificacion("hemos entrado");
/* You should handle validation like this after initially receiving post
data, the ideal would be to validate the data in a central location
and then only pass the valid data on to other functions to avoid
having to recheck everything.
*/
if($p_title != '' && $p_text != '')
{
guardar_pregunta($p_title, $p_text, $p_resp);
$id = obtener_id_pregunta($p_title, $p_text);
$temp = new etiqueta(0, '');
$basura = $temp->guardar_etiquetas($p_et, $id, $_SESSION['id']);
}
else
{
mostrar_notificacion("hemos salido $p_title $p_text");
}
}
function obtener_id_pregunta($p_title, $p_text)
{
/* This query may also be susceptible to SQL injection */
$consulta = mysql_query("SELECT id FROM preguntas WHERE pregunta='" . $p . "' AND texto='" . $t . "'");
while($item = mysql_fetch_array($consulta))
{
return $item['id'];
}
}
function guardar_pregunta($p_title, $p_text, $p_resp)
{
$id_tmp = $_SESSION['id'];
/* This query is susceptible to SQL injection not least because there's
no data validation. */
$insert = "INSERT INTO preguntas (pregunta, texto, id_usuario, fecha, responde_a) VALUES ('$p_title', '$p_text', '$id_tmp', NOW(), '$p_resp')";
$qry = mysql_query($insert);
if(mysql_affected_rows())
{
mostrar_notificacion("La pregunta $p_title ($p_text)($p_resp) se guardo");
return true;
}
else
{
mostrar_notificacion("Error Ingresando datos");
return false;
}
return false;
}
Print form:
function imprimir_formulario_pregunta()
{
$html = '<form id="preguntas" name="preguntas" method="post" action="preguntas.php">' . "\n";
$html .= ' <div>' . "\n";
$html .= ' <h2>Pregunta</h2>' . "\n";
$html .= ' <input name="q" id="q" type="text" />' . "\n";
$html .= ' </div>' . "\n";
$html .= ' <div>' . "\n";
$html .= ' <h2>Explica tu duda</h2>' . "\n";
$html .= ' <textarea name="texto" id="texto"></textarea>' . "\n";
$html .= ' </div>' . "\n";
$html .= ' <div>' . "\n";
$html .= ' <h2>Etiquetas (separadas por comas)</h2>' . "\n";
$html .= ' <input name="tags" id="tags" />' . "\n";
$html .= ' </div>' . "\n";
$html .= ' <div>' . "\n";
$html .= ' <input name="responde_a" style="display:none;" id="responde_a" value="0" />' . "\n";
$html .= ' <button name="pregunta" id="pregunta" type="submit">Publicar</button>' . "\n";
$html .= ' </div>' . "\n";
$html .= '</form>' . "\n";
echo $html;
}

Categories