Not getting $_POST data - php

I've never run into this situation I'm having now. And am using this setup in another part of the site. I cannot figure out why I don't get any post data, my session variables never update.
Here is the html form, dynamically creating a row of check boxes:
$html .= '<form id="status_form">';
foreach ($leads as $key => $type) {
$html .= '<input type="checkbox" name"' . $key . '" id="' . $key . '" class="box_status" value="1"';
if (something = true) {
$html .= ' checked="checked"';
}
$html .= ' />';
$html .= '<label class="checkbox-inline" for"' . $key . '">' . $type . ' (' . #$count[$key] . ')</label>';
}
$html .= '</form>';
echo $html;
Each time a checkbox is checked, javascript is submitting the form to primarily update session variables and then reload the page:
function update_report() {
var form_data = $("#status_form").serialize();
$.ajax({
type: 'POST',
url: 'scripts/test.php',
data: form_data,
success: function() {
window.location.reload(true);
}
});
}
$('.box_status').change(function(){
update_report();
});
And here is the test.php file:
session_start();
if (isset ($_POST)) {
$_SESSION['crm']['reports']['index'] = array();
foreach ($_POST as $k => $v) {
$_SESSION['crm']['reports']['index'][] = $k;
}
$_SESSION['post'] = $_POST;
echo true;
}
I've double checked and the form is displayed correctly, the ajax makes the call, I've done "hello world" checks in test.php.. it even goes into the if(isset($_POST)) portion, but the session variables don't change, and if I assign $_POST to another session variable, it shows me nothing.

You have an error in your string concatenation:
$html .= '<input type="checkbox" name"' . $key . '" id="' . $key . '" class="box_status" value="1"';
name"' is supposed to be name="' You forgot the equal sign. jQuery serialize only takes input tags with names.
Your solution:
$html .= '<input type="checkbox" name="' . $key . '" id="' . $key . '" class="box_status" value="1"';
Note:
The best way to debug this sort of problem is to take a look at your generated html. When you load the page, check the page source. You also made the same error on your label tag.

Related

Issues posting data

I'm trying to insert data to a Wordpress database from a form using the post method. Beofre inserting (code will go where comment is) I'm trying to print the results to screen. When I test my code to collect this data from the form it errors only on one field for some reason. The others post correctly so I'm at a bit of a loss. Below is the code:
global $mydb;
echo '<form name="newProducts" method="post">';
$output = "<div>";
// array of column names
$table_name = $mydb->prefix . '`my-table-names`';
foreach ( $mydb->get_col( "DESC " . $table_name, 0 ) as $column_name ) {
if($column_name!='id'){
$table_name = $mydb->prefix . '`my-table-names`';
$field_name = $column_name;
$getSpecColNameOne = $mydb->get_var($mydb->prepare( "SELECT {$field_name} FROM {$table_name} WHERE id=%d", 0));
$output .= '<div>';
$output .= '<div>' . $getSpecColNameOne . '</div>';
$output .= '<div><input name="' . $column_name . '" type="text" value=""></div>';
$output .= '</div>';
}
}
$output .= '</div>';
echo $output;
$_POST = array_map( 'stripslashes_deep', $_POST );
echo '<div class="btnWrapper">';
echo '<input class="btn border-width-0 btn-text-skin btn-color-jevc btn-square btn-icon-left adduserBtn" type="submit" name="btnSubmit">';
echo '</form>';
if ($_POST) {
$skipKeys = array(
'btnSubmit',
'id',
);
foreach($_POST as $key =>$value){
if(!in_array($key,$skipKeys)){
///insert into db here////////
echo '</br>';
echo"Key:";
print_r ($key);
echo '</br>';
echo"value:";
print_r ($value);
}
}
}
The output I get if I don't fill out column_1 looks like this:
Key:column_1
value:
Key:column_2
value:Input Test 2
Key:column_3
value:Input Test 3
However, if I fill in data into column_1 input field it errors and I get redirected to a 404 page.
column_1 html output looks ok:
<input name="column_1" type="text" value="">
Any ideas appreciated.

UPDATE not working with arrays

I am trying to get the info stored in the array updated to the database. I cannot seem to get it to work. Any help will be appreciated. Thanks.
In the Config Class:
function update_cfg(array $upd)
{
if(is_array($upd))
{
$sql = array();
foreach($upd as $column => $info)
{
if(isset($info) && $column != 'update_cfg')
{
$sql[] = "`" . $column . "`='" . $info . "'";
}
}
if(is_array($sql))
{
$result = $this->Sys->db->query("UPDATE `dj_settings` SET " . implode(', ', $sql));
if($result)
{
unset($sql);
return TRUE;
}
else
{
unset($sql);
return FALSE;
}
}
}
}
Script:
<?php
global $Sys;
if(isset($_POST['update_cfg']))
{
unset($_POST['update_cfg']);
$update = $_POST;
unset($_POST);
if($Sys->Config->update_cfg($update))
{
$Sys->Template->setAlerts('The website has been successfully updated!');
}
else
{
$Sys->Template->setAlerts('The website has not been updated.', 'error');
}
unset($update);
}
?>
<div id="webCfg">
<h2>Website Configuration</h2>
<?php
global $Sys;
global $handle;
$alerts = $Sys->Template->getAlerts();
if ($alerts != '') { echo '<div><ul class="alerts">' . $alerts . '</ul></div>'; }
asort($handle);
if($handle['status'] == 1)
{
$enable = 'checked="checked"';
}
else
{
$disable = 'checked="checked"';
}
foreach ($handle as $key => $val)
{
$label = str_replace('_', ' ', $key);
if(strlen($val) <= 50 && !is_numeric($val))
{
$input[$key] = '<tr><td class="label"><label for="' . $key . '">' . ucwords($label) . '</label></td><td class="content"><input type="text" id="' . $key . '" name="' . $key . '" value="' . $val . '"/></td></tr>';
}
elseif(strlen($val) >= 51 && !is_numeric($val))
{
$input[$key] = '<tr><td class="label"><label for="' . $key . '">' . ucwords($label) . '</label></td><td class="content"><textarea id="' . $key . '" name="' . $key . '">' . ucfirst($val) . '</textarea></td></tr>';
}
elseif(is_numeric($val))
{
$input[$key] = '<tr><td class="label"><label for="' . $key . '">Website Status</label></td><td class="content"><input type="radio" id="' . $key . '" name="' . $key . '" value="1" ' . $enable . '> Enable <input type="radio" id="' . $key . '" name="' . $key . '" value="0" ' . $disable . '> Disable </td></tr>';
}
}
?>
<form action="" method="post">
<table cellpadding="1" cellspacing="0" id="webCfgTbl">
<?php
foreach (array_keys($input) as $key)
{
echo '<div class="row">' . $input[$key] . '</div>';
}
?>
<tr><td class="label"><label for="submit"></label></td><td class="content"><div class="row submitrow"><input type="submit" id="submit" name="update_cfg" class="submit" value="Update Settings" /></div></td></tr>
</table>
</form>
</div>
?>
The info from the database is loaded when the page is. When I change the values and click Update Settings, $Sys->Config->update_cfg() returns FALSE everytime. I am stumped on this and would appreciate any help. Thanks.
EDIT
When I echo the query in the update_cfg() function after the foreach() loop I get this:
UPDATE `dj_settings` SET `status`='0', `disabled_msg`=':: Test Message for Disabled Website ::', `email_auto_response`='Thank you so much for your email. I will respond back as soon as I am able. Usually within 30 minutes. Please feel free to look at the pictures and videos on our website, and the FAQ and Pricing tab is a great resource also. I will respond personally to any questions you may have shortly. Have a great day! Some tips on picking the right DJ: For most hiring a DJ is a first time experience. Picking the right DJ can be daunting and sometimes overwhelming task. Here are some good tips to follow to help you through your process. 1. Make sure they have their LLC or INC, and have a business license for your area. 2. Make sure they are insured. 3. Make sure that you sign some kind of a contract throughout the booking process. 4. Check reviews on reputable websites. ie.. thumbtack.com , weddingwire.com, or yellowpages.com. 5. If the price is too good to be true, it is. This is a big one, because you definitely get what you pay for when you hire a DJ. 6. Sit down with a couple of DJ's and talk them, generally your own intuition will get you far. If you follow those steps, you're sure to get a good DJ. No matter who it is, with my company or with a competitor. Your event will go off smoothly 99% of the time. Marshall Bracewell-Owner Dynamic DJ Company, LLC 803-807-1243 http://www.dynamicdjcompany.com', `web_url`='http://www.dynamicdjcompany.com', `web_email`='marshall#dynamicdjcompany.com'
Well...that's a start I guess...at least the update is working. Try first doing $info = $this->Sys->db->real_escape_string($info); then putting that into the "" . $column . "='" . $info . "'";

Trying to change statement so create_radio function is only called once (PHP)

I have a function that creates a radio button in PHP:
// This function creates a radio button.
// The function takes two arguments: the value and the name.
// The function also makes the button "sticky".
function create_radio($value, $name = 'gallon_price')
{
// Start the element:
echo '<input type="radio" name="' .
$name .'" value="' . $value . '"';
// Check for stickiness:
if (isset($_POST[$name]) && ($_POST[$name] == $value))
{
echo ' checked="checked"';
}
// Complete the element:
echo " /> $value ";
} // End of create_radio() function.
I then leave the PHP form to create an html form and call the function three times with values that represent three different gas prices.
<span class="input">
<?php
create_radio('3.00');
create_radio('3.50');
create_radio('4.00');
?>
</span>
I am wondering how I could change this code so it would be possible to get the same output and only make one call to the create_radio function.
Thanks!
function create_radio($value, $name = 'gallon_price')
{
$output = "";
if (is_array($value)) {
while (count($value) > 0) {
$arr_value = array_pop($value);
$output .= create_radio($arr_value);
}
} else {
// Start the element:
$output .= '<input type="radio" name="' .
$name .'" value="' . $value . '"';
// Check for stickiness:
if (isset($_POST[$name]) && ($_POST[$name] == $value))
{
$output .= ' checked="checked"';
}
// Complete the element:
$output .= " /> $value ";
}
return $output;
}
A quick bit of recursion will allow the function to work for arrays and non arrays. Note: in the html you will need to echo the call to create_radio not just call it.
you could make $value an array create_radio(array('3.00','3.50','4.00')); just loop inside the function:
function create_radio($value,$name = 'gallon_price'){
foreach($value as $v){
// Start the element:
$out. = '<input type="radio" name="'.$name.'" value="'.$v.'"';
// Check for stickiness:
if(isset($_POST[$name])&&($_POST[$name]==$v)){
$out .= ' checked="checked"';
}
// Complete the element:
$out .= " /> $v ";
}
return $out;
} // End of create_radio() function.
call it:
echo create_radio(array('3.00','3.50','4.00'));
it is usually better not to echo inside the function.

Load data from database & retain data between postbacks

In PHP Project, I'm creating page a which retrieve the data from database on page load then allow the user to change data & Update. I have to use input text and option controls to display data. Editing form data may involve in few POST requests. To load data from database and retain data between POSTs I use this approach.
Load Data from Database
$oClass = new DataClass();
$oClass ->GetRecordById($_REQUEST['id']);
$dataName = $oClass ->Name;
$dataYear = $oClass ->Year;
INPUT TEXTs
<input type="text" name="txtName" value="<?php echo isset($_POST['txtName']) ? $_POST['txtName'] : $dataName ?>" >
OPTIONs
$arrYears = GetYears();
foreach ($arrYears as $year) {
if (isset($_POST['ddlYear'])) {
if ($_POST['ddlYear'] == $year) {
echo '<option value="' . $year . '" selected="selected">' . $year . '</option>';
} else {
echo '<option value="' . $year . '">' . $year . '</option>';
}
} else {
if ($dataYear == $year) {
echo '<option value="' . $year . '" selected="selected">' . $year . '</option>';
} else {
echo '<option value="' . $year . '">' . $year . '</option>';
}
}
}
Is there a better approach to retain data between posts than using like
if (isset($_POST['NAME']))
{$_POST['NAME']}
else
{$name}
Is there a reason why you need to retain the info? If a user submits the form it will update the info and therefore will need to be fetched again for the next person to come in and update or read.
Above though you assign $year = $oClass ->Year; but it's not referenced anywhere. the $year in the foreach loop is a local scope variable only for that foreach loop, after that loop finishes executing it disappears.
you can do stuff like this.
if (isset($_POST['txtName']))
{
$name = $_POST['txtName'];
}
else
{
$name = '';
}
<input type="text" name="txtName" value="<?php echo $name; ?>" />
Since the only difference between the options in the foreach loops are whether or not the selected attribute is applied you can shorten both of them to the following.
if (isset($_POST['ddlYear'])) {
echo '<option value="' . $year . ($_POST['ddlYear'] == $year) ? '" selected="selected"' : '' . '>' . $year . '</option>';
}
else {
echo '<option value="' . $year . ($movieyear == $year) ? '" selected="selected"' : '' . '>' . $year . '</option>';
}
Also to get a quicker answer please provide the simplest working use case, for example above example has $_POST variables that aren't defined anywhere and others like $movieyear also not defined.

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;
}

Categories