I'm attempting to make a button that, based on the selected form/inputs on the page, will bring you to a page called "typeDefine.php?openness=3?conscientiousness=2?extroversion=1?agreeableness=2?neuroticism=1"(the numbers varying based on the selected inputs). However, $selectedNum- the variable that would ideally be containing the $_POST for each input- is returning an error immediately once the page is loaded, saying:
Undefined index
<?php
$typeWords = array("openness", "conscientiousness", "extroversion", "agreeableness", "neuroticism");
$typeLetters = array("o", "c", "e", "a", "n");
$typePath = "";
$correspondingLetters = array("I", "II", "III");
$isFirst = true;
foreach($typeWords as $typeWord)
{
$selectedNum = $_POST[$typeWord];//error here!!!
if(isset($selectedNum))//if got $typeWord in a form
{
$separationChar;
if($isFirst)
{
$separationChar = "?";
$isFirst = false;
}
else
{
$separationChar = "&";
}
$typePath = $typePath . $separationChar . $typeWord . "=" . $selectedNum;//e.g. $typePath = "?openness=3?conscientiousness=2?extroversion=1?agreeableness=2?neuroticism=1" for $_GET method after arriving on next page
}
}
echo 'search for type
<div>';
foreach($typeWords as $typeWord)
{
$typeLetter = substr($typeWord, 0, 1);
echo '<form method = "post" class = "column">';
for($i = 1; $i <= 3; $i++)
{
echo '<input type = "radio" name = "' . $typeWord . '" id = "' . $typeLetter . $i . '"><label for = "' . $typeLetter . $i . '">' . $correspondingLetters[$i - 1] . '</label>';//sets each input name to $typeWord for $_POST above
}
echo '<li class = "textHighlight">' . $typeWord . '</li>
</form>';
}
echo '</div>';
?>
What can I do to fix this error, in turn filling $typePath and making the script correctly bring you to the desired url upon the button's click?
Thanks in advance!
You should perform the isset() test on the $_POST element, not the variable that you set from it.
foreach ($typeWords as $typeWord)
{
if (isset($_POST[$typeWord])) {
$selectedNum = $_POST[$typeWord];
$typePath = $typePath . "?" . $typeWord . "=" . $selectedNum;
}
}
Note that multiple parameters need to be separated with &, ? should only be used at the beginning. There's a built-in function that will create a query string from an array, you can use that:
$typeArray = [];
foreach ($typeWords as $typeWord)
{
if (isset($_POST[$typeWord])) {
$selectedNum = $_POST[$typeWord];
$typeArray[$typeWord] = $selectedNum;
}
}
$typePath = $typePath . "?" . http_build_query($typeArray);
You can also replace the loop with:
$typeArray = array_intersect_key($_POST, array_flip($typeWords));
You execute your code immidiately without a present $_POST array.
You have to wrap your post related code with an if statement like this:
if ($_POST) {
$selectedNum = $_POST[$typeWord];
}
I'm developing a searcher and I made a function that gets the data from a db, saves each ad in a variable and saves pagination (from another function) in another variable, so they can be returned in an array to be printed in the html later.
It works like this: you hit a buy or rent button and you go to the search page (/search?do?=buy/rent) then you have to select the property type, optionally a city/zone and hit search. Ajax sends the data via post (to search.php, the same file), hides the first container and shows the second container that has the list of properties with a pagination at the end of the page.
These are the main variables and a script to hide/show containers:
$mode = filter_input(INPUT_GET, 'do', FILTER_SANITIZE_STRING); // buy or rent
$prop_type = filter_input(INPUT_POST, 'prop_type', FILTER_SANITIZE_STRING); // res or com AJAX
$city = filter_input(INPUT_POST, 'city', FILTER_SANITIZE_NUMBER_INT); // AJAX
$zone = filter_input(INPUT_POST, 'zone', FILTER_SANITIZE_NUMBER_INT); // AJAX
$page_number = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT);
if (isset($page_number) && $page_number >= 1) {
$cont1 = 'display: none;';
$cont2 = NULL;
// need a way to get the prop_type (the checked checkbox before changing the page) without using $_GET.
} else {
$cont1 = NULL;
$cont2 = 'display: none;';
}
This is the function:
function get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage) {
if ($prop_type == 'res') {
$table2 = 'res_prop';
} else if ($prop_type == 'com') {
$table2 = 'com_prop';
}
if ($city != 0) {
$optional_cond = ' WHERE t2.city = ' . $city;
$optional_cond2 = NULL;
if ($zone != 0) {
$optional_cond2 = ' AND t2.zone = ' . $zone;
}
} else $optional_cond = $optional_cond2 = NULL;
$mysqli = new mysqli('127.0.0.1', 'db', '123456', 'name');
// pagination
if ($stmt = $mysqli->prepare('SELECT COUNT(id) FROM ' . $table)) {
$stmt->execute();
$stmt->bind_result($totalitems);
$stmt->fetch();
if (!isset($page)) {
$page = (int)$page_number <= 0 ? 1 : (int)$page_number;
}
$limit = 4;
if ($page > ceil($totalitems / $limit)) {
$page = ceil($totalitems / $limit);
}
$start = ($page - 1) * $limit;
$stmt->close();
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1
INNER JOIN ' . $table2 . ' t2 ON t2.id = t1.id
' . $optional_cond . $optional_cond2 . '
LIMIT ?, ?')) {
$stmt->bind_param('ii', $start, $limit);
$stmt->execute();
$stmt->bind_result($id, $id, $type, $status, $bhk, $baths, $area1, $area2, $age, $description, $price, $city, $zone, $img1, $img2, $img3, $img4);
$test = "";
while ($row = $stmt->fetch()) {
if ($status === 0) {
$possesion = 'En construcción';
} else if ($status === 1 || $status === 2) {
$possesion = 'Inmediata';
} else $possesion = 'Desconocida';
if ($prop_type == 'res') {
$is_res = '<p><span class="bath">Bed</span>: <span class="two">' . $bhk . ' BHK</span></p>
<p><span class="bath1">Baths</span>: <span class="two">' . $baths . '</span></p>';
} else $is_res = NULL;
$test .= '<div class="box-col">
<div class="col-sm-6 left-side ">
<img class="img-responsive" src="' . $img1 . '" alt="">
</div>
<div class="col-sm-6 middle-side">
<h4>Disponibilidad: ' . $possesion . '</h4>
' . $is_res . '
<p><span class="bath2">Built-up Area</span>: <span class="two">' . $area1 . ' m²</span></p>
<p><span class="bath3">Plot Area</span>: <span class="two">' . $area2 . ' m²</span></p>
<p><span class="bath4">Age of property</span>: <span class="two">' . $age . ' Year(s)</span></p>
<p><span class="bath5">Price</span>: <span class="two">' . $price . ' €</span></p>
<div class="right-side">
Contact Builder
</div>
</div>
<div class="clearfix"> </div>
</div>
';
$pagination = functions::getPaginationString($page, $totalitems, $limit, $adjacents = 1, $targetpage, $pagestring = "&page=");
}
} //else echo "Statement failed: " . $mysqli->error . "<br>";
} //else echo "Statement failed: " . $mysqli->error . "<br>";
return array($test, $pagination);
}
This is the main code:
if (empty($_GET)) {
echo 'under construction';
}
else if (isset($mode) && $mode == 'buy') {
$table = 'to_sell';
$targetpage = '/search?do=buy';;
if (isset($prop_type)) {
$data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
$test = $data[0];
$pagination = $data[1];
}
}
else if (isset($mode) && $mode == 'rent') {
$table = 'to_rent';
$targetpage = '/search?do=rent';;
if (isset($prop_type)) {
$data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
$test = $data[0];
$pagination = $data[1];
}
}
else {
echo 'invalid url';
}
This is the AJAX script that sends the checkbox value via post (it's not working correctly, I don't get an undefined error in $prop_type (I don't know why???) but I get it in $table2, that it's inside the if ($prop_type == '')):
$('.search, .pagination').click(function() { // search button and change page
if ($('#res_prop').is(':checked')) {
$prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
$prop_type = $('#com_prop').val();
}
$.post('search.php', { // same file, maybe self
prop_type: $prop_type,
city: $('select[name=city]').val(), // optional
zone: $('select[name=zone]').val(), // option value="0" by default
success: function(){
$('.cont-1').hide();
$('.cont-2').show();
}
});
});
It works perfectly if I manually set $prop_type = 'res';. Any ideas?
Another problem is that the pagination buttons link does not work, it just triggers the ajax script (they need to send the data, otherwise the script will restart when changing pages).
I really would appreciate any optimization to the scripts. Thanks.
You're mixing your javascript and php here.
In PHP you declare a variable with $varname, in Javascript, $ represents the jQuery operator. As such your code that says $prop_type is totally invalid since this is javascript code. You're telling jQuery to execute some functionality called prop_type which doesn't exist, and as such you're getting an error that this is undefined.
if ($('#res_prop').is(':checked')) {
var prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
var prop_type = $('#com_prop').val();
}
And change the line which reads prop_type: $prop_type, to prop_type: prop_type,
If you want to import the <div class="results"></div> container with ajax:
you should use this tested and working code:
$(document).ready(function(){
$('.search, .pagination').click(function() { // search button and change page
$prop_type = '';
if ($('#res_prop').is(':checked')) {
$prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
$prop_type = $('#com_prop').val();
}
$.ajax({
method: "POST",
url: "go.php",
data: {
'prop_type': $prop_type,
'city': $('select[name="city"]').val(),
'zone': $('select[name="zone"]').val()
}
}).done(function(data) {
var _html = $.parseHTML(data);
$('.cont-1').hide();
$('.cont-2').show();
$(_html).each(function(i, el) {
if (el.className == 'results') {
$('.results').html($(el).html());
};
});
});
return false;
});
});
In my php class I created a method for concatenated select form (ajax call)
Now I've a strange problem because in firefox, chrome and other browsers the method
go well displaying the rows of my query select while in ie 8-9 no display rows but only a "white" window.
public function ShowCat_2( $idca2, $idca1 ) {
// for edit function
$where = "";
if(isset($idca1)){ $where .= " idcat_1='$idca1'"; }
if(isset($_POST['idcat_1'])) { $where .= " idcat_1='$_POST[idcat_1]'"; }
// query
$this->db->result = $this->db->mysqli->query("SELECT * FROM cat_2 WHERE $where");
$cat_2 = '<option value="0">Select</option>';
while($row = $this->db->result->fetch_assoc()) {
$cat_2 .= '<option value="' . $row['idcat_2'] . '"';
if($idca2 == $row['idcat_2']){ $cat_2 .= ' selected'; } // for edit fun
$cat_2 .= '>' . utf8_encode(ucfirst(strtolower($row['descr']))) . '</option>';
}
return $cat_2;
}
Can you tell me what could be the problem and how to solve?
Thanks
Take a look at the page source. There may be a PHP warning / notice in there that's breaking the HTML code.
The site I'm working on wants data organized in a specific way. I need to split it into two columns if it's over 8 td's long. Here is my code right now. I've put it into an array as I had an idea about doing that and using the count to display data but I haven't figured out how to make that work.
$resultFound = false;
$prevWeek = -1;
$count = 0;
while($row = mysqli_fetch_array($result)) {
$adjustedWeek = dateToWeek($row['date']) - 35;
if($_GET['keywords'] != "") {
$id = search($row, $_GET['keywords']);
if($row['id'] == $id) {
if($validWeek) {
if($week == $adjustedWeek) {
include('test2.php');
}
}
else {
include('test2.php');
}
}
}
foreach($tableArray as $table) {
echo $table;
}
Here is my code for test2.php
$table = "";
if($prevWeek != $adjustedWeek) {
$table .= ('<th colspan=2>Week' . $adjustedWeek . '</th>');
$prevWeek = $adjustedWeek;
}
$table .= '<tr>';
$table .= ('<td colspan=12><a href="details.php?id=' . $row['id'] . '">'
. getGameTitleText($row) . '</a></td>');
$table .= '</tr>';
$resultFound = true;
$tableArray[] = $table;
$count++;
I need the code to do something like this:
If (all items of any week > 8)
write out 8 items to column one
then write the rest to column two
I've accounted for the total number of entries it's searching but not specific to a week, and I don't want to have to make lots of variables for that either to keep track.
How could I get the result like I want?
Warning!! the following code is to illustrate the idea only. Not tested on machine, but I think you can iron the possible error out.
pseudo code example:
$arr=array();
while($row = mysqli_fetch_array($result)) {
$arr[]['data']=$row['data'];
$arr[]['whatever']=$row['whatever'];
}
$columns=floor(count($arr)/8);
$output="<table>";
foreach ($arr as $i=>$a){
$output.="<tr>";
$output.="<td>{$arr[$i]['data']}</td>";
if ($columes>0){
for($j=0;$j<$columes;$j++){
$row_number=$i+($j+1)*8;
$output.="<td>{$arr[$row_number]['data']}</td>";
}
}
$output.="</tr>";
}
$output.="</table>";
This code will continue to add the third column if 2 is not enough.
You may still want to put a test for the end of array, so you don't get a bunch of warning when the $row_number is larger than count($arr)
This is how I ended up doing it. It's a bit "dirty" because it echo's out an extra /table and /tr at the beginning but it works for my purposes and is simpler than the code already posted. That was too complex for me
$table = "";
if($prevWeek != $adjustedWeek) {
$table .= '</tr></table><table class="vault_table">';
$table .= ('<tr><th>Week ' . $adjustedWeek . '</th></tr>');
$table .= '<table class="vault_table">';
$prevWeek = $adjustedWeek;
}
if($count % 2 == 0) {
$table .= '<tr>';
}
$table .= ('<td><a href="details.php?id=' . $row['id'] . '">'
. getGameTitleText($row) . '</a></td>');
$resultFound = true;
$tableArray[] = $table;
$count++;
The class is just for styling the table. Didn't have anything to do with how it's being layed out. other than each side of the table being 50% width of the container
I have a php page on which has a ajax function makerequest(serverPage, objID) , it works fine it has three links they also works fine my content comes on that page in the <div id=pageId>. in this page the third page has a dropdown list populated by mysql with on change event. in this page a lot of rows on every option so I have to decide that the data show on multiple page by php pagination class,it also works fine, but when I click on next page all the data lost due to reload the page and get the default value in the dropdown list.
Some of code content is here:
<div id="menu">
<!-- <a href="?id=AllIndiaengineringCollege" What part we want to link to onClick="makerequest('page.php?id=AllIndiaengineringCollege', 'content'); return false;" For AJAX - Load page into the div>AllIndiaengineringCollege</a>-->
<a href="?id=AllIndiaengineringCollege" onClick="makerequest('id=AllIndiaengineringCollege', 'content'); return false;" style="text-decoration:none;color: #3E5AAB" >All India Engineering College</a>
Deemed Universities
State Engineering College
</div>
</font></div>
<div id='content'style="text-align:left;width:897px; height:auto; background-color:#99CCFF;padding:1px">
<?PHP
if (isset($_GET['id'])) {
$pageId = $_GET['id'];
if ($pageId == 'AllIndiaengineringCollege') {
include("/pagination/index.php");
}
if ($pageId == 'Deemed') {
include("/pagination/state.php");
}
if ($pageId == 'state') {
include("/pagination/state.php");
}
}
?>
</div>
it works fine
my third page is
<?php
$result = mysql_query("SELECT Id,state FROM state");
echo "<select name=State id='Id' class='select' onchange='showUser(this.value)'>";
while ($nt = mysql_fetch_array($result)) {
echo ('<option value="' . $nt['Id'] . '" if($State===' . $nt['Id'] . ') echo $sel; >' . $nt['state'] . '</option>');
}
echo "</select>";
?>
</div>
<div id="state"><b><center>xxxxxxxx.</center></b>
showUser function is like here
function showUser(str) {
if (str == "") {
document.getElementById("state").innerHTML = "";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("state").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "pagination/statelist.php?state=" + str, false);
xmlhttp.send();
}
And the pagination code is like here:
<?php
include('db.php');
include('function.php');
$q = $_GET["state"];
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 2;
$statement = "college where State= '" . $q . "'";
$url = "BTech.php?id=state&State=" . $q . "&";
$startpoint = ($page * $limit) - $limit;
?>
I think if you corrected this, it would be fine
while ($nt = mysql_fetch_array($result)) {
echo ('<option value="' . $nt['Id'] . '" if($State===' . $nt['Id'] . ') echo $sel; >' . $nt['state'] . '</option>');
}
as something like this,
while ($nt = mysql_fetch_array($result)) {
echo "<option value=\"{$nt['Id']}\"".(($State===$nt['Id'])?'selected="selected"':"") .">{$nt['state']}</option>";
}
You can't evaluate conditions that way, nested echo wont work either.
Look at this previous SO question