PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label forms. Show all posts
Showing posts with label forms. Show all posts

Friday, November 18, 2022

[FIXED] How do center text to a text area?

 November 18, 2022     alignment, css, forms, html-table, vertical-alignment     No comments   

Issue

I would like my "feild labels" to be aligned in the center of their corresponding text fields. I have tried many different ways, and to get it centered on the page, I used tables. I am currently using "display: inline-block;" and "vertical-align: middle;" with no success.

Image Link

My HTML Code:

<!DOCTYPE html>
<html>
    <head>
    <title>DNA Translator</title>
    <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="script.js"></script>
    <script></script>
    </head>
    <body>
        <div>
            <form>
                <table valign="center" id="table1">
                    <tr>
                        <td class="labels">DNA:</td>
                        <td class="spacer"></td>
                        <td><input type="text" name="dna" placeholder="DNA"></td>
                    </tr>
                    <tr>
                        <td class="labels">mRNA:</td>
                        <td class="spacer"></td>
                        <td><input type="text" name="mrna" placeholder="mRNA"></td>
                    </tr>
                    <tr>
                        <td class="labels">tRNA:</td>
                        <td class="spacer"></td>
                        <td><input type="text" name="trna" placeholder="tRNA"></td>
                    </tr>
                    <tr>
                        <td class="labels">Amino Acids:</td>
                        <td class="spacer"></td>
                        <td><input type="text" name="aminoAcids" placeholder="Amino Acids"></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td class="spacer"></td>
                        <td class="button"><button id="button_translate" type="button">Tanslate</button>
                        <button id="button_clear" type="button">Clear</button></td>
                    </tr>
                </table>

                <!--<div id="text">
                    <p>DNA: </p><input type="text" name="dna" placeholder="DNA"><br>
                    <p>mRNA: </p><input type="text" name="mrna" placeholder="mRNA"><br>
                    <p>tRNA: </p><input type="text" name="trna" placeholder="tRNA"><br>
                    <p>Amino Acids: </p><input type="text" name="aminoAcids" placeholder="Amino Acids"><br>
                </div>
                <div>
                    <button id="button_translate" type="button">Tanslate</button>
                    <button id="button_clear" type="button">Clear</button>
                </div>-->
            </form>
        </div>
    </body>
</html>

My CSS (as you can see I've tried a lot of things):

div.container {
    width:98%; 
    margin:1%;
  }

table#table1 { 
    margin-left:auto; 
    margin-right:auto; 
    /*width:530px;*/
  }

td {
    height:20px;
    }

td.button {
    height:40px;
    }

td.labels {
    width:89px;
    display: inline-block;
    text-align:right;
    vertical-align: middle;
  }

td.spacer {
    width:15px;
  }

#button_translate
{
    opacity: 0.7;
    display: inline-block;
    height:35px;
    width:200px;
    background-color:#293FE3;
    font-family:arial;
    font-weight:bold;
    color:#ffffff;
    border-radius: 5px;
    text-align:center;
    margin-top:2px;
    /*display: block;*/
    margin: 15px auto;
}

#button_clear
{
    opacity: 0.7;
    display: inline-block;
    height:35px;
    width:200px;
    background-color:#293FE3;
    font-family:arial;
    font-weight:bold;
    color:#ffffff;
    border-radius: 5px;
    text-align:center;
    margin-top:2px;
    /*display: block;*/
    margin: 15px auto;
}

input[type="text"]
{
width: 390px;
display:/*block;*/ inline-block;
vertical-align:middle;
height:20px;
padding:4px 6px;
margin-bottom:20px;
font-size:14px;
line-height:20px;
color:#555;
vertical-align:middle;
-webkit-border-radius:4px;
-moz-border-radius:4px;
border-radius:4px
background-color:#fff;
border:1px solid #ccc;
-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);
-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);
box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);
-webkit-transition:border linear .2s,box-shadow linear .2s;
-moz-transition:border linear .2s,box-shadow linear .2s;
-o-transition:border linear .2s,box-shadow linear .2s;
transition:border linear .2s,box-shadow linear .2s
}

#text
{
    width: 450px ;
    margin-top; 800px;
    margin-left: auto ;
    margin-right: auto ;
}

Solution

You can add padding to your .labels css property, in your case, around 6px should do it!

td.labels {
    width: 89px;
    display: inline-block;
    text-align: right;
    padding-top: 6px;
    vertical-align: middle;
}

Also, you have way too many elements for something that could be so simple:

DEMO: http://jsfiddle.net/shannonhochkins/d4rLD/2/



Answered By - Shannon Hochkins
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, November 17, 2022

[FIXED] How can i vertical align center forms

 November 17, 2022     bootstrap-4, forms, vertical-alignment     No comments   

Issue

Before i ask i must first say i tried vertical methods align, it didnt work so i must post this problem of mine.Sry it might be trivial question,but im struggling with it.

<div class="container-fluid">
  <div class="row">
    <div class="col-sm-3">
      One of three columns
    </div>
    <div class="col-sm-6">
        <section>
        <h1>Signup</h1>
            <form action="includes/signup.inc.php" method="post">
                <input type="text" name="uid" placeholder="Username">
                <input type="text" name="mail" placeholder="E-mail">
                <input type="password" name="pwd" placeholder="Password">
                <input type="password" name="pwd-repeat" placeholder="Repeat password">
                <button class="btn btn-default" type="submit" name="signup-submit">Signup</button>
            </form>
        </section>
    </div>
    <div class="col-sm-3">
      One of three columns
    </div>
  </div>
</div>

Solution

add form-control class with each input element.

<input class="form-control" type="text" name="uid" placeholder="Username">
<input class="form-control" type="text" name="mail" placeholder="E-mail">
<input class="form-control" type="password" name="pwd" placeholder="Password">
<input class="form-control" type="password" name="pwd-repeat" placeholder="Repeat password">

enter image description here



Answered By - Azhr-M
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 15, 2022

[FIXED] How to give Laravel 6 validation attributes a custom name for error message?

 November 15, 2022     forms, laravel, laravel-6, php, validation     No comments   

Issue

I am trying to change the way my errors display when my Laravel form is not filled in correctly. Currently, when I get an error. It displays like this.

name mag niet groter zijn dan 255 karakters.

Because this language is Dutch, I would like to change the 'name' attribute to 'naam'. I have tried to change the $attributesNames like this but unfortunately it did not work.

$attributeNames = [
   'name' => 'Naam'   
];

This is what my validation function currently looks like.

/**
 * @return array
 */
public function validateCampaign() {
    // name needs to render as 'Naam'

    return request()->validate([
        'name' => 'required|max:255',
    ]);
}

Solution

As it turns out. I needed to edit the 'attributes' array in my resources/lang/xx/validation.php file.

It turns out like this:

'attributes' => [
    'name' => 'Naam'
]


Answered By - Niels Bosman
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to give Laravel 6 validation attributes a custom name for error message?

 November 15, 2022     forms, laravel, laravel-6, php, validation     No comments   

Issue

I am trying to change the way my errors display when my Laravel form is not filled in correctly. Currently, when I get an error. It displays like this.

name mag niet groter zijn dan 255 karakters.

Because this language is Dutch, I would like to change the 'name' attribute to 'naam'. I have tried to change the $attributesNames like this but unfortunately it did not work.

$attributeNames = [
   'name' => 'Naam'   
];

This is what my validation function currently looks like.

/**
 * @return array
 */
public function validateCampaign() {
    // name needs to render as 'Naam'

    return request()->validate([
        'name' => 'required|max:255',
    ]);
}

Solution

As it turns out. I needed to edit the 'attributes' array in my resources/lang/xx/validation.php file.

It turns out like this:

'attributes' => [
    'name' => 'Naam'
]


Answered By - Niels Bosman
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 13, 2022

[FIXED] where to place POST method on my webserver?

 November 13, 2022     forms, joomla, php, plesk, post     No comments   

Issue

I am hosting my first webserver ever. I got myself a ubuntu based vserver and installes plesk and joomla.

Stupid question, but I wanted to create a form and and handle the input with a post.php file with a POST-method. But I have no clue where to place it on my server. Right now it is just in /var/www/vhosts/[MY WEBSITE.DE]/httpdocs/post.php, but this might be wrong.

Is there a specific file that I have to change or do I have to place my php-files in a specific directory? This question might be so stupid, I couldn't even find an answer on Google :D


Solution

Well, you can place your own code anywhere in the directory that plesk is using for your website. In your case : /var/www/vhosts/[MY WEBSITE.DE]/httpdocs/.

It is then your job to use that in your code where needed (I assume you have a form of some sort and that's why you are talking about a "post method", you just need to point that form to your whatever.php page you uploaded).

Please use FTP/your website username to upload your code into your website directory and not the root user or you'll end up with permission issues and nothing will correctly work.

A good start would be Getting Started with Managing Websites in Plesk and Option A. Upload Content



Answered By - Maiko Bossuyt
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 8, 2022

[FIXED] How to create a HTML Cancel button that redirects to a URL

 November 08, 2022     forms, html, javascript     No comments   

Issue

I am playing with the Buttons in the w3schools Tryit editor, and I am trying to figure out how to make my browser redirect to an URL when I click on the "Cancel" button.

Here's what I have tried:

<form action="demo_form.asp" method="get">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <button type="submit" value="Submit">Submit</button>
  <button type="reset" value="Reset">Reset</button>
  <button type="cancel" onclick="javascript:window.location='http://stackoverflow.com';">Cancel</button>
</form>

But it doesn't work. Any ideas?


Solution

cancel is not a valid value for a type attribute, so the button is probably defaulting to submit and continuing to submit the form. You probably mean type="button".

(The javascript: should be removed though, while it doesn't do any harm, it is an entirely useless label)

You don't have any button-like functionality though, so would be better off with:

<a href="http://stackoverflow.com"> Cancel </a>

… possibly with some CSS to make it look like a button.



Answered By - Quentin
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to display your custom app on home page

 November 08, 2022     forms, menu, odoo-14, view     No comments   

Issue

I tried to make a menu for my custom app but it doesn't display to home page. Any idea on how to make it happen? I wanted to display my app beside to installed apps. I am using Odoo 14.

This is my form:

<record id="view_custom_module_form" model="ir.ui.view">
            <field name="name">view.custom.module.form</field>
            <field name="model">custom.model</field>
            <field name="type">form</field>
            <field name="arch" type="xml">
                <form string="Custom" create="false" delete="false" edit="false">
                    <sheet>
                        <group>
                            <group>
                                <field name="name" readonly="1"/>
                                <field name="number" readonly="1"/>
                            </group>
                        </group>
                    </sheet>
                </form>
            </field>
        </record>
        
        
        <record id="action_custom_module" model="ir.actions.act_window">
            <field name="name">Custom Module</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">custom.model</field>
            <field name="view_mode">form</field>
            <field name="view_id" ref="view_custom_module_form"/>
        </record>

And this is my menu:

        <menuitem
            name="Custom" 
            id="menu_custom_menu"
            sequence="1"
            web_icon="custom_module,static/description/icon.png"
            groups="base.group_user,base.group_partner_manager"/>
        
        <menuitem id="submenu_custom_menu"
            name="Custom"
            parent="menu_custom_menu"
            action="action_custom_menu"
            sequence="1"/>

And I wanted to display my custom app icon here: enter image description here


Solution

I already solved it. This is what I did to show my app. I put the sequence on it. Make sure you already make your form view so that your custom module will show up.

<menuitem id="menu_custom_form_root"
              name="Custom FOrm"
              sequence="9"/>

    <menuitem id="menu_form"
              name="Forms"
              parent="menu_custom_form_root"
              action="action_forms"
              sequence="9"/>


Answered By - Kai Ning
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 6, 2022

[FIXED] How to style the "Search Computer" File Upload button for eMail Contact Form 7?

 November 06, 2022     contacts, css, forms, html, wordpress     No comments   

Issue

I have a standard "Contact Form 7" Send File as Attachment Form on wordpress:

DEFAULT VALUES

<label>UPLOAD FILE
[file uploadedfile]
</label>

Screenshot of my Button

I am already searched stackoverflow etc etc etc. After 2hrs I gave up :(


How can I change the Color of the background and the font size easily?

If I get in touch with the file form control directly it will blast up like a giant. This is not useful for computers and never responsiv für mobile.

And as a second question.

Is it possible to format the "No file selected" differently from the "Search computer (Durchsuchen)"?


Solution

Although it's difficult to style a file input itself due to browser compatibility, you can instead apply styling to its label to achieve the same result.

Take a look at this example input:

<label for="fileInput">
    Upload file
</label>
<input id="fileInput" type="file">

Because the label is directly linked to the input, it will open the file browser once you click on either the label or the input. Since that's the case, you can hide the input itself and only display the label.

<style>
input[type="file"] {
    display: none;
}
</style>

Now that you're left with only the label, you can apply styling to the element to make it look more like a button instead of a label. Take a look at this basic example of CSS you could use to style the label.

<style>
label[for="fileInput"] {
    border: 1px solid black;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}
</style>

Here's what you'll end up with after hiding the input and add styling to the label. Of course, this is just a basic example, but there are almost no limits to what you can achieve through CSS, so you could style the label any way you'd like.

enter image description here

Putting it all together, the final code for this implementation will look something like the following:

input[type="file"] {
  display: none;
}

label[for="fileInput"] {
  border: 1px solid black;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer;
}
<!doctype html>
<html>

<head>
  <title>File upload styling</title>
</head>

<body>
  <form method="post">
    <label for="fileInput">
    Upload file
</label>
    <input id="fileInput" type="file">
  </form>
</body>

</html>

Since you're using WordPress, you'll just end up putting the CSS in your theme styles, but the implementation should be almost identical as to what it would be with a static HTML site.



Answered By - Austin
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Which part of this contact form I have to change if I am supposed to set up this form for my own website?

 November 06, 2022     action, contact, css, email, forms     No comments   

Issue

As an amateur who has never created/designed any kind of "form actions", I need help to use this form for a website I am currently designing. I feel okay with "CSS" and structure of the form itself. Just want to know which part of this contact form should be changed. Where to put my Email address?

<div class="segment contact-form">
  <div class="center-wrap">
    <div class='gf_browser_unknown gform_wrapper holla-form_wrapper' id='gform_wrapper_1'>
      <form method='post' enctype='multipart/form-data' id='gform_1' class='holla-form' action='http://mammothmedia.tv/contact/'>
        <div class='gform_body'>
          <ul id='gform_fields_1' class='gform_fields top_label form_sublabel_below description_below'>
            <li id='field_1_1' class='gfield gfield_contains_required field_sublabel_below field_description_below'>
              <label class='gfield_label' for='input_1_1'>First Name<span class='gfield_required'>*</span>
              </label>
              <div class='ginput_container'>
                <input name='input_1' id='input_1_1' type='text' value='' class='medium' tabindex='1' />
              </div>
            </li>
            <li id='field_1_8' class='gfield gfield_contains_required field_sublabel_below field_description_below'>
              <label class='gfield_label' for='input_1_8'>Last Name<span class='gfield_required'>*</span>
              </label>
              <div class='ginput_container'>
                <input name='input_8' id='input_1_8' type='text' value='' class='medium' tabindex='2' />
              </div>
            </li>
            <li id='field_1_2' class='gfield gfield_contains_required field_sublabel_below field_description_below'>
              <label class='gfield_label' for='input_1_2'>Email<span class='gfield_required'>*</span>
              </label>
              <div class='ginput_container'>
                <input name='input_2' id='input_1_2' type='text' value='' class='medium' tabindex='3' />
              </div>
            </li>
            <li id='field_1_3' class='gfield field_sublabel_below field_description_below'>
              <label class='gfield_label' for='input_1_3'>Phone</label>
              <div class='ginput_container'>
                <input name='input_3' id='input_1_3' type='text' value='' class='medium' tabindex='4' />
              </div>
            </li>
            <li id='field_1_6' class='gfield field_sublabel_below field_description_below'>
              <label class='gfield_label' for='input_1_6'>Budget Range</label>
              <div class='ginput_container'>
                <input name='input_6' id='input_1_6' type='text' value='' class='medium' tabindex='5' />
              </div>
            </li>
            <li id='field_1_5' class='gfield ginput_textarea field_sublabel_below field_description_below'>
              <label class='gfield_label' for='input_1_5'>Comments</label>
              <div class='ginput_container'>
                <textarea name='input_5' id='input_1_5' class='textarea medium' tabindex='6' rows='10' cols='50'></textarea>
              </div>
            </li>
            <li id='field_1_7' class='gfield ginput_subscribe field_sublabel_below field_description_below'>
              <label class='gfield_label'></label>
              <div class='ginput_container'>
                <ul class='gfield_checkbox' id='input_1_7'>
                  <li class='gchoice_1_7_1'>
                    <input name='input_7.1' type='checkbox' value='Subscribe to our newsletter' id='choice_1_7_1' tabindex='7' />
                    <label for='choice_1_7_1' id='label_1_7_1'>Subscribe to our newsletter</label>
                  </li>
                </ul>
              </div>
            </li>
            <li id='field_1_9' class='gfield gform_validation_container field_sublabel_below field_description_below'>
              <label class='gfield_label' for='input_1_9'>Comments</label>
              <div class='ginput_container'>
                <input name='input_9' id='input_1_9' type='text' value='' />
              </div>
              <div class='gfield_description'>This field is for validation purposes and should be left unchanged.</div>
            </li>
          </ul>
        </div>
        <div class='gform_footer top_label'>
          <input type='submit' id='gform_submit_button_1' class='gform_button button' value='Submit' tabindex='8' onclick='if(window["gf_submitting_1"]){return false;}  window["gf_submitting_1"]=true;  ' />
          <input type='hidden' class='gform_hidden' name='is_submit_1' value='1' />
          <input type='hidden' class='gform_hidden' name='gform_submit' value='1' />
          <input type='hidden' class='gform_hidden' name='gform_unique_id' value='' />
          <input type='hidden' class='gform_hidden' name='state_1' value='WyJbXSIsIjA0OGE5MTQyNDdhM2NhZjFiMTc5Nzk5ZjM1ZTIzZjYzIl0=' />
          <input type='hidden' class='gform_hidden' name='gform_target_page_number_1' id='gform_target_page_number_1' value='0' />
          <input type='hidden' class='gform_hidden' name='gform_source_page_number_1' id='gform_source_page_number_1' value='1' />
          <input type='hidden' name='gform_field_values' value='' />
        </div>
      </form>
    </div>
    <script type='text/javascript'>
      jQuery(document).bind('gform_post_render', function(event, formId, currentPage) {
        if (formId == 1) {
          jQuery('#input_1_3').mask('(999) 999-9999').bind('keypress', function(e) {
            if (e.which == 13) {
              jQuery(this).blur();
            }
          });
        }
      });
      jQuery(document).bind('gform_post_conditional_logic', function(event, formId, fields, isInit) {});
    </script>
    <script type='text/javascript'>
      jQuery(document).ready(function({
            jQuery(document).trigger('gform_post_render', [1, 1])
          });
    </script>
  </div>
</div>


Solution

You will not be able to use this because this form uses a WordPress Plugin called Gravity Form's

Also most form's use PHP and you wont be able to grab PHP from client side.



Answered By - user4563161
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 21, 2022

[FIXED] How to 'unlock' a field in a CakePHP form when it is part of a hasMany association

 October 21, 2022     cakephp, cakephp-2.0, forms, has-many, php     No comments   

Issue

I have a form that represents a RewardModifier table in our database. That RewardModifier hasMany RewardOption.

My form is structured like this (image):

enter image description here

So, the RewardModifier can have many elements on the page, each with many RewardOption items.

The Problem

The problem is, that users can delete sections of this form using Javascript, which essentially removes it from the DOM. When they do that, it breaks the security component, because the POST'ed fields do not match the token supplied when the page was generated.

Now, I have been using unlockedFields to handle this before:

$this->Security->disabledFields = array(
   'PrjRewardModifier.reward_id',
   'PrjRewardModifier.title',
   'PrjRewardModifier.option_type',
   'PrjRewardOption.description',
   'PrjRewardOption.modifier',
   'PrjRewardOption.amount'
);

I know that disabledFields is deprecated, but we are using that for the time being.

When I debug the posted form data in the SecurityComponent, I see the following:

(int) 8 => 'PrjRewardModifier.0.reward_id',
(int) 9 => 'PrjRewardModifier.0.title',
(int) 10 => 'PrjRewardModifier.0.option_type',
(int) 11 => 'PrjRewardModifier.0.PrjRewardOption.0.description',
(int) 12 => 'PrjRewardModifier.0.PrjRewardOption.0.modifier',
(int) 13 => 'PrjRewardModifier.0.PrjRewardOption.0.amount'

I need to know how to edit the data being passed to unlockedFields so that it can disregard these fields that are keyed for hasMany relationships.

Thanks.


Solution

I had a similar problem. I found adding (the equivalent of) this to the RewardModifier controller did the trick:

public function beforeFilter(){
     $this->Security->unlockedFields = array('RewardOption');
}


Answered By - Will Stone
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, October 19, 2022

[FIXED] How to Auto Invite all users of selected Group using Django admin inlines form?

 October 19, 2022     admin, django, django-admin, forms, inlines     No comments   

Issue

I am working on an application where currently, I have
1) Staff Model is connected to User model via OneToOne Relationship and can have more than one Group.
2) Meeting model can also assigned to many Group.
3) RSVPinline is a part with MeetingAdmin as a inline form.

Here i was trying to automatically ADD all 'Staff' associated in Selected Groups in django admin form while creating Meetings.

I have tried save_model to add current user in meeting's 'creator' field.

models.py

class Group(models.Model):
    name = models.CharField(max_length=200)

class Staff(models.Model):
    fullname = models.CharField(max_length = 250,verbose_name = "First Name")
    group = models.ManyToManyField(Group, blank=False,verbose_name = "Meeting Group")  # protect error left to add
    is_active = models.BooleanField(default=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True,verbose_name = "Associated as User")  # protect error left to add
    left_date = models.DateField(null=True, blank=True,verbose_name = "Resigned Date")

class Meeting(models.Model):
    title = models.CharField(_('Title'), blank=True, max_length=200)
    start = models.DateTimeField(_('Start'))
    group = models.ManyToManyField(Group, blank=False,verbose_name = "Meeting Group")  # protect error left to add
    location = models.ForeignKey(Location, blank=False,verbose_name = "Location",on_delete=models.CASCADE)  # protect error left to add

class RSVP(models.Model):
    meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE)
    responder =  models.ForeignKey(User, editable=True, on_delete=models.CASCADE, null=True, blank=True,verbose_name = "Attendees", related_name='guest')
    response = models.CharField(max_length = 20, choices= MEETING_RSVP, default='No response', verbose_name = "Status",null=True, blank=True)

admin.py

class RSVPInline(admin.TabularInline):
    model = RSVP
    extra = 0


class MeetingAdmin(admin.ModelAdmin):
    form = MeetingForm
    list_display = ('title', 'location', 'start','creator' )
    inlines = [RSVPInline, TaskInline]

    #Currently using save_model to automatically add current user as a creator
    def save_model(self, request, obj, form, change):
        obj.creator = request.user
        super().save_model(request, obj, form, change)

My pseudo code is:

grouplist = Get group's list from submitted MeetingForm
stafflist = Staff.objects.filter(department__in =grouplist).values_list('id', flat=True).distinct()
Add to RSVPInline:
    values = list(for staff in stafflist:
              'responder' = staff
              'meeting' = 'meeting from  MeetingForm' 
              'response' = has a default value in model

    bulk_create() RSVPInline with values

Solution

You can extend save_related() ModelAdmin method to perform additional actions after form object (Meeting) and its Inlines (RSVPs, if present in submitted form) are saved:

class MeetingAdmin(admin.ModelAdmin):
    ...

    def save_related(self, request, form, formsets, change):
        # call original method - saves Meeting and inlines
        super(MeetingAdmin, self).save_related(request, form, formsets, change)
        # get this form Meeting
        obj = form.instance
        # get Staff members of this meeting groups
        # and we can exclude ones already having
        # RSVP for this meeting
        stafflist = Staff.objects.filter(
            group__in=obj.group.all()
        ).exclude(
            user__guest__meeting=obj
        )
        rsvps = list(
            RSVP(responder=staff.user, meeting=obj)
            for staff in stafflist
        )
        # calls bulk_create() under the hood
        obj.rsvp_set.add(*rsvps, bulk=False)

** Few possibly useful notes:

  • group field may be better to be called groups as it represents ManyToMany relation and returns multiple objects
  • related_name represents relation from the related object back to this one so it may be more logical to use something like invites instead of guest


Answered By - Oleg Russkin
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Auto Invite all users of selected Group using Django admin inlines form?

 October 19, 2022     admin, django, django-admin, forms, inlines     No comments   

Issue

I am working on an application where currently, I have
1) Staff Model is connected to User model via OneToOne Relationship and can have more than one Group.
2) Meeting model can also assigned to many Group.
3) RSVPinline is a part with MeetingAdmin as a inline form.

Here i was trying to automatically ADD all 'Staff' associated in Selected Groups in django admin form while creating Meetings.

I have tried save_model to add current user in meeting's 'creator' field.

models.py

class Group(models.Model):
    name = models.CharField(max_length=200)

class Staff(models.Model):
    fullname = models.CharField(max_length = 250,verbose_name = "First Name")
    group = models.ManyToManyField(Group, blank=False,verbose_name = "Meeting Group")  # protect error left to add
    is_active = models.BooleanField(default=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True,verbose_name = "Associated as User")  # protect error left to add
    left_date = models.DateField(null=True, blank=True,verbose_name = "Resigned Date")

class Meeting(models.Model):
    title = models.CharField(_('Title'), blank=True, max_length=200)
    start = models.DateTimeField(_('Start'))
    group = models.ManyToManyField(Group, blank=False,verbose_name = "Meeting Group")  # protect error left to add
    location = models.ForeignKey(Location, blank=False,verbose_name = "Location",on_delete=models.CASCADE)  # protect error left to add

class RSVP(models.Model):
    meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE)
    responder =  models.ForeignKey(User, editable=True, on_delete=models.CASCADE, null=True, blank=True,verbose_name = "Attendees", related_name='guest')
    response = models.CharField(max_length = 20, choices= MEETING_RSVP, default='No response', verbose_name = "Status",null=True, blank=True)

admin.py

class RSVPInline(admin.TabularInline):
    model = RSVP
    extra = 0


class MeetingAdmin(admin.ModelAdmin):
    form = MeetingForm
    list_display = ('title', 'location', 'start','creator' )
    inlines = [RSVPInline, TaskInline]

    #Currently using save_model to automatically add current user as a creator
    def save_model(self, request, obj, form, change):
        obj.creator = request.user
        super().save_model(request, obj, form, change)

My pseudo code is:

grouplist = Get group's list from submitted MeetingForm
stafflist = Staff.objects.filter(department__in =grouplist).values_list('id', flat=True).distinct()
Add to RSVPInline:
    values = list(for staff in stafflist:
              'responder' = staff
              'meeting' = 'meeting from  MeetingForm' 
              'response' = has a default value in model

    bulk_create() RSVPInline with values

Solution

You can extend save_related() ModelAdmin method to perform additional actions after form object (Meeting) and its Inlines (RSVPs, if present in submitted form) are saved:

class MeetingAdmin(admin.ModelAdmin):
    ...

    def save_related(self, request, form, formsets, change):
        # call original method - saves Meeting and inlines
        super(MeetingAdmin, self).save_related(request, form, formsets, change)
        # get this form Meeting
        obj = form.instance
        # get Staff members of this meeting groups
        # and we can exclude ones already having
        # RSVP for this meeting
        stafflist = Staff.objects.filter(
            group__in=obj.group.all()
        ).exclude(
            user__guest__meeting=obj
        )
        rsvps = list(
            RSVP(responder=staff.user, meeting=obj)
            for staff in stafflist
        )
        # calls bulk_create() under the hood
        obj.rsvp_set.add(*rsvps, bulk=False)

** Few possibly useful notes:

  • group field may be better to be called groups as it represents ManyToMany relation and returns multiple objects
  • related_name represents relation from the related object back to this one so it may be more logical to use something like invites instead of guest


Answered By - Oleg Russkin
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to set initial data for Django admin model add instance form?

 October 19, 2022     admin, django, forms, model     No comments   

Issue

How can I set an initial value of a field in the automatically generated form for adding a Django model instance, before the form is displayed? I am using Django 1.3.1.

My model is the following:

class Foo(models.Model):
  title = models.CharField(max_length=50)
  description = models.TextField()

and the current admin form is really nothing special

class FooAdmin(admin.ModelAdmin):
  ordering = ('title',)

When I use the admin page to add a new instance of Foo, I get a nice form with empty fields for title and description. What I would like is that the description field is set with a template that I obtain by calling a function.

My current best attempt at getting there is this:

def get_default_content():
  return 'this is a template for a Foo description'

class FooAdminForm(django.forms.ModelForm):

  class Meta:
      model = Foo

  def __init__(self, *args, **kwargs):
      kwargs['initial'].update({'description': get_default_content()})
      super(FooAdminForm, self).__init__(self, *args, **kwargs)

class FooAdmin(admin.ModelAdmin):
  ordering = ('title',)
  form = FooAdminForm

but if I try this I get this Django error:

AttributeError at /admin/bar/foo/add/ 
   'FooForm' object has no attribute 'get'
Request Method: GET
Request URL:    http://localhost:8000/admin/bar/foo/add/
Django Version: 1.3.1
Exception Type: AttributeError
Exception Value:    'FooForm' object has no attribute 'get'
Exception Location: /www/django-site/venv/lib/python2.6/site-packages/django/forms/widgets.py in value_from_datadict, line 178

I don't know what is wrong here, and what I should do to make it work. What I also find strange about this error (apart from the fact that I see it at all) is that there is no FooForm in my code at all?


Solution

You need to include self as the first argument in your __init__ method definition, but should not include it when you call the superclass' method.

def __init__(self, *args, **kwargs):
    # We can't assume that kwargs['initial'] exists! 
    if 'initial' not in kwargs:
        kwargs['initial'] = {}
    kwargs['initial'].update({'description': get_default_content()})
    super(FooAdminForm, self).__init__(*args, **kwargs)

Having said that, a model field can take a callable for its default, so you may not have to define a custom admin form at all.

class Foo(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField(default=get_default_content)


Answered By - Alasdair
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 15, 2022

[FIXED] How to access contents of file uploaded from <input type="file" /> without sending to server?

 October 15, 2022     dom, forms, google-chrome-extension, javascript, reactjs     No comments   

Issue

I'm trying to upload JSON file from local disk to upload chrome storage but when I use the tag and useRef on the current value, it only returns the filename prefixed with 'C:\fakepath...'

ImportExport Component:

const ImportExport = () => {
  const uploadValue = useRef()

  const download = () => {
    chrome.storage.sync.get(null, res => {
      let blob = new Blob([JSON.stringify(res)], {type: "application/json"})
      let url = window.URL.createObjectURL(blob)
      chrome.runtime.sendMessage({method: 'download', data: url}, () => {
        window.URL.revokeObjectURL(url)
      })
    })
  }

  const upload = async () => {
    let bb = new Blob([uploadValue.current.value], {type: "application/json"})
    let contents = await bb.text()
    console.log(contents) // logs 'C:\fakepath\notes.json'
  }

  return (
    <div className="flex flex-col items-center justify-start rounded-sm mx-auto w-1/2 shadow-md h-5/6">
      <h2 className="text-3xl m-5">Import/Export</h2>
      <form>
        <label htmlFor="import" className={styles.button}>Import</label>
        <input onChange={upload} ref={uploadValue} type="file" accept="application/json" id="import" />
        <button onClick={download}className={styles.button}>Export</button>
      </form>
      
      <h3 className="text-2xl m-3">Note:</h3>
      <p className="text-center w-1/2">This exports the data to .JSON file which can then be used to import back to chrome storage</p>
    </div>
  )
}

I've read that I can use File API or Blob API. I've tried both but none of them where able to actually access the data contained. They could only access the path 'C:\fakepath\data.json'.

I've been looking scraping the web for answers and all I could find is it looks like I need to send this to a server first. However, my app is a chrome extension and has no web server.

Can anyone help me figure this out? It would be much appreciated.


Solution

Try it like this (use files[0] instead of value)

  const upload = async () => {
    let bb = new Blob([uploadValue.current.files[0]], {type: "application/json"})
   ...
  }


Answered By - Nikolay
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 11, 2022

[FIXED] How to prevent duplicate names in SQL database when submitting a form via PHP?

 October 11, 2022     duplicates, forms, php, phpmyadmin     No comments   

Issue

Via a form on the site, organizations can be added to the database. The organization ID is unique in PhpMyAdmin, but organizations with the same name can be added multiple times. Any suggestions on how to fix this within PHP or PhpMyAdmin?

The database has the following structure:

SQL table

And in funtions.php, I have the following code:

    // Add sport organizations to database
if (isset($_POST['button'])){
    $data = array(
        'organization' => $_POST['organization'],
        'description' => $_POST['description'],
        'website' => $_POST['website'],
        'facebook' => $_POST['facebook'],
        'instagram' => $_POST['instagram'],
        'phone' => $_POST['phone'],
        'email' => $_POST['email'],
    );
    $table_name = 'organizations';

    $result = $wpdb->insert($table_name, $data, $format=NULL);

    if ($result==1) {
        echo "<script>alert('Organizations saved');</script>";
    }
    else {
        header("refresh: 0; url=/");
        echo "<script>alert('Unable to save organization');</script>";
    }
}

And for reference, this is the HTML code:

<form autocomplete="off" role="form" method="POST">
            <div class="container">
                <div class="form-group">
                    <input id="organization" name="organization" type="text" placeholder="Name of organization" class="form-control input-sm" required="">
                </div>
                <div class="form-group">
                    <input id="description" name="description" type="textarea" placeholder="Description" class="form-control input-sm" required="">
                </div>
                <div class="form-group">
                    <input id="website" name="website" type="text" placeholder="Website" class="form-control input-sm">
                </div>
                <div class="form-group">
                    <input id="facebook" name="facebook" type="text" placeholder="Facebook" class="form-control input-sm">
                </div>
                <div class="form-group">
                    <input id="instagram" name="instagram" type="text" placeholder="Instagram" class="form-control input-sm">
                </div>
                <div class="form-group">
                    <input id="phone" name="phone" type="text" placeholder="Phone" class="form-control input-sm">
                </div>
                <div class="form-group">
                    <input id="email" name="email" type="text" placeholder="Email" class="form-control input-sm">
                </div>
            </div>
<div class="container">
                <div class="row justify-content-center">
                    <div class="col-xs-4 col-sm-4 col-md-4">
                        <input type="submit" class="btn btn-info btn-block" name="submitbtn">
                    </div>
                </div>
            </div>
        </form>

Solution

Basically you need to add unique index to the organizations table but you have to consider proper error handling since any attempt to add organization with duplicated name will throw an error.

ALTER TABLE `organizations` ADD UNIQUE INDEX `unq_organization` (`organization`);


Answered By - DINK74
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 4, 2022

[FIXED] how to submit a form after a file has been uploaded while including some data in the post[]

 October 04, 2022     file-upload, forms, html, php, phpexcel     No comments   

Issue

hi i have following html form and i am using it to upload a .xlx file.

<form action="dashboard.php" method="post" enctype="multipart/form-data">
                            <div class="file-upload">  


                                <div class="col-md-12 m-b-15">
                                    <div class="col-md-3">
                                        Note No :
                                    </div>
                                    <div class="col-md-8">
                                        <input class=" form-control m-b-15 " id="note_number_for_the_alert" name="note_number_for_the_alert" readonly="">                              
                                    </div>
                                </div> 
                                <div class="row">
                                    <div class="col-md-8 m-l-10">

                                        <div class=" formError validateAlert" id="alert_to_upload_file_in_vendor_delivery_note_management" >
                                            <div class="formErrorContent" id="test">please Select the .XLSX file <br></div>
                                            <div class="formErrorArrow"></div>                                
                                        </div>
                                        <input type="file" id="file" name="file2" multiple="multiple" />
                                        <p style="text-align: right; margin-top: 20px;">
                                            <input type="submit"  value="Upload Files" name="submit2" class= "btn btn-success" />
                                        </p>
                                    </div>
                                    <div class="col-md-4"></div>
                                </div>


                            </div>
                        </form>

following phpexcel code lines used to upload the file.

$uploadedStatus = 0;
$name2 = '';
if (isset($_POST["submit2"])) {
    if (isset($_FILES["file2"])) {

        if ($_FILES["file2"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        } else {
            if (file_exists($_FILES["file2"]["name"])) {
                unlink($_FILES["file2"]["name"]);
                $uploadedStatus = 2;
            }
            $name = basename($_FILES['file2']['name']);
            $name2 = explode('.', $name);
            if ($name2[count($name2) - 1] == 'csv' || $name2[count($name2) - 1] == 'xlsx') {

                $target_path = "uploads/programming/";
                $target_location = $target_path . basename($_FILES['file2']['name']);

                move_uploaded_file($_FILES["file2"]["tmp_name"], $target_location);
                $uploadedStatus = 1;
}


        }
    } else {
        echo "No file selected <br />";
    }
    }
}

these two working perfectly in separately , no issue with the file upload. but i need to send some values to the dashboard.php using the same time.

currently before the file is uploading page is redirect to the dashboard.php, any suggestion to submit the form once got $uploadedStatus = 1 where after the file uploading process has completed.


Solution

To answer your question, you can use JQuery to upload the file. So the page won't get reload. When you press the upload button show an loading image tells the users that you are working on the upload.

<form action="dashboard.php" method="post" enctype="multipart/form-data" id="form_id">

JQuery & Ajax

function submitForm() {
  var formData = new FormData($("#form_id"));
  // show your loader image

    $.ajax({
        url: upload.php,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
           // hide your loader image
        },
        cache: false,
        contentType: false,
        processData: false
    });
}

Note: Formdata won't work on older browsers. There are some fallback for that, read this thread



Answered By - Rinto George
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, September 30, 2022

[FIXED] How can I have a XNOR-like behaviour on required input?

 September 30, 2022     bootstrap-5, forms, html, javascript     No comments   

Issue

I have the following form:

<form>
        <input type="text" name="input1">
        <input type="text" name="input2">
        <button type="submit">submit</button>
    </form>

Using Bootstrap, I am trying to prevent the user from inputting only 1 field ; i.e. Not inputting anything is fine, inputting both fields is fine, inputting one field but not the other is not fine.
I read Validation but could not find a solution to my problem.
What is the best way to solve this issue ?


Solution

You can compare the comparisons with an empty string to tell if they're both empty or both non-empty.

document.querySelector("form").addEventListener("submit", e => {
  let value1 = document.querySelector('[name=input1]').value;
  let value2 = document.querySelector('[name=input2]').value;
  if ((value1 == '') != (value2 == '')) {
    e.preventDefault();
    console.log('Fill in both inputs or neither');
  } else {
    e.preventDefault(); // just for snippet here
    console.log('Form was submitted');
  }
});
<form>
  <input type="text" name="input1">
  <input type="text" name="input2">
  <button type="submit">submit</button>
</form>



Answered By - Barmar
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 18, 2022

[FIXED] How to convert .pdf from post method to .jpg in PHP

 September 18, 2022     forms, imagick, php     No comments   

Issue

so while developing a webapp I encountered a problem I could not find an answer to. Let's say we have this html

<form method="post" enctype="multipart/form-data" action="/upload.php">
    <label> Upload .pdf here 
        <input name="menu" type="file" accept=".pdf"> 
    </label>  
    <button>Submit</button>
</form>

And now this PHP to handle it:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
        $menu = $_POST['menu'];

        //convert whatever type menu is to something readable for Imagick

         // create Imagick object
        $imagick = new Imagick();
        // Reads image from PDF
        $imagick->readImage($menu);
        // Writes an image or image sequence Example- converted-0.jpg, converted-1.jpg
        $imagick->writeImages('menu.jpg', false);
        echo $imagick;

I couldn't find any solution anywhere else so I thought I'd ask my first ever queston on stackoverflow. Thanks for helping me out!


Solution

If you upload a file with name "menu", the actual file data is contained in $_FILES['menu']["tmp_name"] on submission to a php script.

Hence, please change $_POST['menu'] in your code to $_FILES['menu']["tmp_name"] for further processing.

HTML

<form method="post" enctype="multipart/form-data" action="pdfconvert.php">
    <label> Upload .pdf here 
        <input name="menu" type="file"> 
    </label>  
    <button>Submit</button>
</form>

pdfconvert.php (I amended the codes so as to handle multiple pages in a pdf file)

<?php

$im = new Imagick($_FILES['menu']["tmp_name"]);


$pages = $im->getNumberImages(); 



for ($i = 0; $i < $pages; $i++) { 

$url = $_FILES['menu']["tmp_name"].'['.$i.']'; 

$image = new Imagick($url);
$image->setImageFormat("jpg"); 
$image->writeImage('menu_'. $i. '.jpg'); 

echo "writing page " . $i. "<br>"; 
}

?>

Last but not least:

  1. please make sure that the target folder is writable (otherwise the system cannot write the jpg files
  2. it is better to create a separate folder (e.g. ./upload/) for the processing so that the system will not "mix" the generated jpg files with your php scripts
  3. better add a random string to the generated file names so that even if you upload two files with the same name, the old files will not get overwritten.


Answered By - Ken Lee
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, September 17, 2022

[FIXED] How can I insert a Print button that prints a form in a webpage

 September 17, 2022     forms, html, javascript, printing     No comments   

Issue

So, lets say I got a simple form inside a page like this:

<form style="text-align:center;">
    <p> STUFF </p>
</form>

I wanna add a button so when the user clicks on it the browser's Print dialog shows up, how can I do that?

Edit: I wanna print the form, not the page.


Solution

Print the whole page

Try adding a button that calls window.print()

<input type="button" value="Print this page" onClick="window.print()">

Print a specific portion/container in a page

<div id="print-content">
 <form>

  <input type="button" onclick="printDiv('print-content')" value="print a div!"/>
</form>
</div>

then in the HTML file, add this script code

<script type="text/javascript">
    function printDiv(divName) {
        var printContents = document.getElementById(divName).innerHTML;
        w=window.open();
        w.document.write(printContents);
        w.print();
        w.close();
    }
</script>

Refer Print <div id="printarea"></div> only?



Answered By - Murali Murugesan
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 8, 2022

[FIXED] Why does my radio button group not properly add to my database?

 September 08, 2022     ajax, database, forms, php, radio-button     No comments   

Issue

In my app I have an index page called Contacts.html. I have a form called newContactForm.php which I display on the Contacts.html page via an ajax function. When a user enters details into the form an presses submit it uses a form action to send the data to and ajax function called insert. the insert function takes the data and sends it to newContact.php which saves the data to my database table. the insert function then (onreadystatechange) triggers an ajax function called showGroup which displays all the contacts in the database on the Contacts.html page.

My issue is that my radio button value is always entered as "on" and not the value that it should be (i.e. Colleagues or Family, etc... etc...). My code for the pages that are relative to this issue are below. I have tried to solve this on my own but can't find the issue.

my ajax functions:

    function createObject() 
{
    var request_type;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer")
    {
        request_type = new ActiveXObject("Microsoft.XMLHTTP");
    }

    else    
    {
        request_type = new XMLHttpRequest();
    }

    return request_type;
}

var http = createObject();


//value used to solve an Internet Explorer cache issue
var nocache = 0;
function insert() 
{
    // Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
    var newFname= encodeURI(document.getElementById('newFname').value);
    var newLname = encodeURI(document.getElementById('newLname').value);
    var newPhone = encodeURI(document.getElementById('newPhone').value);
    var newEmail = encodeURI(document.getElementById('newEmail').value);
    var newAddress = encodeURI(document.getElementById('newAddress').value);
    var group = encodeURI(document.getElementById('group').value);

    // Set te random number to add to URL request
    nocache = Math.random();
    // Pass the login variables like URL variable
    http.open('get', 'newContact.php?newFname='+newFname+'&newLname=' +newLname+'&newPhone=' +newPhone+'&newEmail=' +newEmail+'&newAddress=' +newAddress+'&group=' +group+'&nocache = '+nocache);
    http.onreadystatechange = showGroup;
    http.send(null);
    }

function showGroup(str)
    {
    document.getElementById("content01").innerHTML="";
    if (str=="")
    {
    document.getElementById("content01").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("content01").innerHTML=xmlhttp.responseText;
    document.getElementById("content02").innerHTML = "";
    }
    }
    xmlhttp.open("GET","getGroup.php?contactGroup="+str,true);
    xmlhttp.send();
    }

my newContact.php file:

    <!-- Include Database connections info. -->
<?php include('config.php'); ?>

<?php

//If the values are set (i.e the txt fields/radio button are filled in then run the sql insert statement to add the contact.
if(isset($_GET['newFname']) && isset($_GET['newLname']) && isset($_GET['newPhone']) && isset($_GET['newEmail']) && isset($_GET['newAddress']) && isset($_GET['group'])) 
{

    $newFname = $_GET["newFname"] ;
    $newLname = $_GET["newLname"] ;
    $newPhone = $_GET["newPhone"] ;
    $newEmail = $_GET["newEmail"] ;
    $newAddress = $_GET["newAddress"] ;
    $group = $_GET["group"] ;

    //SQL insert statement used to add the user entered data to the database table.
    $insertContact_sql = "INSERT INTO `test`.`contacts` (`newFname`, `newLname`, `newPhone`, `newEmail`, `newAddress`, `group`) VALUES ('{$newFname}' , '{$newLname}' , '{$newPhone}' , '{$newEmail}' , '{$newAddress}' , '{$group}')";
    $insertContact= mysql_query($insertContact_sql) or die(mysql_error());

} 

//else if the fields do not contain data then display this error message.
else 
{ 
    echo 'Error! Please fill all fileds!';
}

?>

My newContactForm.php file:

    <!--This line of code is used to direct the "form action='javascript:insert()' to the 'insert' function located in the mentioned .js file"-->
<script src="ajax_framework.js" language="javascript"></script>

<?php   $addContact = $_GET['addContact']; //index which sends new contact form to the html page via ajax function "showAddContact" which is located in the ajax.js file.

//form which users can use to enter the details of a new contact to add to the database.
echo "Add A Contact:";
echo "<FORM action='javascript:insert()' method='get'>";
echo "<table>";
echo "<tr>";
echo "<td>First Name:</td><td><input id='newFname' name='newFname' type='text' size'20'></input></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Last Name:</td><td><input id='newLname' name='newLname' type='text' size'20'></input></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Phone Number:</td><td><input id='newPhone' name='newPhone' type='text' size'12'></input></td>";
echo "</tr>";
echo "<td>Email Address:</td><td><input id='newEmail' name='newEmail' type='text' size'30'></input></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Postal Address:</td><td><input id='newAddress' name='newAddress' type='text' size'65'></input></td>";
echo "</tr>";
echo "<td>Group:</td><td> <input id='group' type='radio' name='group'/>No Group <input id='group' type='radio' name='group'/>Friend";
echo "<input id='group' type='radio' name='group'/>Colleagues <input id='group' type='radio' name='group'/>Family";
echo "</table>";
//submit button that submits the contact information to an ajax function.
echo "<input type='submit' name='Submit' value='Add Contact'/>";
echo "</FORM>";

?>

Solution

You don't have a value for any of your radio buttons. Add the value attribute:

<input id='group' type='radio' name='group' value='No Group'/>No Group
<input id='group' type='radio' name='group' value='Friend'/>Friend
<input id='group' type='radio' name='group' value='Colleagues'/>Colleagues
<input id='group' type='radio' name='group' value='Family'/>Family


Answered By - Mark Parnell
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing