Si este tutorial no es lo que necesita y Usted todavía tiene preguntas o sugerencias – póngase en contacto con nosotros. ¡Por favor, ayúdenos a servirle!

Su Nombre

Su Email

Su Mensaje (obligatorio)

captcha

Agregar campos al formulario de contacto en HTML

Este tutorial le presenta instrucciones para agregar campos al formulario de contacto en HTML. Este tutorial es una continuación del tutorial ¿Cómo crear un formulario de contacto en HTML?. Si tiene los ficheros de este tutorial, abralos para continuar, o puede descargarlos.

Parte 1. HTML

Abra el fichero index.html con ayuda de su editor HTML preferido. Tenemos 2 input, 1 elemento textarea y dos botones. Así que vamos a añadir más elementos, como checkboxes (casillas de verificación), botones de radio y una lista desplegable. La sintaxis HTML para todos los elementos es muy fácil y se puede revisarla abajo. Agregue este código después de botones Submit y Reset.

Opciones adicionales:

	<input type="checkbox" name="check[]" value="USA">USA<br />
	<input type="checkbox" name="check[]" value="Canada">Canada<br />
	<input type="checkbox" name="check[]" value="Mexico">Mexico<br />

¿Está de acuerdo?

<input type="radio" value="yes" name="cf_radio_button">Yes
<input type="radio" value="no" name="cf_radio_button">No

Elija un elemento de la lista desplegable:

<select size="1" name="cf_drop_down">
	<option>php</option>
	<option>html</option>
	<option>css</option>
	<option>asp</option>
	<option>ajax</option>
	<option>javascript</option>
</select>

Vamos a analizar algunos momentos interesantes en este código. Usted puede notar que los nombres asignados a las casillas de verificación no son diferentes, como en el caso con el campo de texto añadido anteriormente, también tienen corchetes al final. Los corchetes definen que es una variable de array (variable de matriz). Así es como funciona. Para cada casilla de verificación, array check[] recibe el valor de las casillas de verificación pulsadas. Por ejemplo, después de marcar dos casillas de Estados Unidos y Canadá, su array check[] contiene los valores checked_usa y check_canada como sus elementos.

Ahora vamos a revisar los botones de radio y desplegables. Hemos asignado el mismo nombre “cf_radio_button” a dos de los botones de radio, como no se puede elegir ambos al mismo tiempo, por lo que cada uno de ellos no necesita un nombre único.

La sintaxis de la lista desplegable es muy fácil también. Abra la etiqueta <select>, a continuación liste las opciones, ‘envueltas’ en etiquetas <option>…</option> y al final utilice etiqueta </select>. La etiqueta <select> tiene dos atributos asignados, uno es el nombre, y el segundo – tamaño. El atributo de tamaño especifica el número de opciones visibles de una lista desplegable.

Aquí está el resultado:

HTML contact form(haga clic para ampliar)

Parte 2. PHP

Así que, ahora tenemos los elementos de la página y debemos procesar sus datos enviados y agregar a email enviado. Abajo puede encontrar el código final de fichero contact.php

<?php
// Grabbing data sent from the form and assigning it to variables
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_message = $_POST['cf_message'];

foreach($_POST['check'] as $value) {
	$check_boxes .= $value." ";
}

$radio_button = $_POST['cf_radio_button'];
$drop_down_item = $_POST['cf_drop_down'];

// Composing body of the message
$mail_to = 'gordon@template-help.com';
$subject = 'Message from a site visitor '.$field_name;

$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Message: '.$field_message."\n";
$body_message .= "Additional options checked: ".$check_boxes."\n";
$body_message .= "Did the customer agree: ".$radio_button."\n";
$body_message .= "Selected item from the dropdown list: ".$drop_down_item;

// Creating headers of the message
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";

$mail_status = mail($mail_to, $subject, $body_message, $headers);

if ($mail_status) { ?>
	<script language="javascript" type="text/javascript">
		alert('Thank you for the message. We will contact you shortly.');
		history.back(1);
	</script>
<?php
}

else { ?>
	<script language="javascript" type="text/javascript">
		alert('Message failed. Please, send an email to gordon@template-help.com');
		history.back(1);
	</script>
<?php
}
?>

Vamos a utilizar la función de php foreach() para recorrer una matriz (array) "check" y guardar cada elemento de array en una variable llamada $value. Entonces creamos la variable $check_boxes y se incrementará con el valor de cada elemento de matriz.

foreach($_POST['check'] as $value) {
	$check_boxes .= $value." ";
}

Como se puede revisar abajo, los botones de radio y la lista desplegable son definidos de una manera similar. Creamos una variable php y asignamos los datos enviados de una casilla de radio o lista desplegable a esta variable.

$radio_button = $_POST['cf_radio_button'];
$drop_down_item = $_POST['cf_drop_down'];

Este código también es similar a lo que hemos hecho antes. Solamente agregamos nuevos datos a email final

$body_message .= "Additional options checked: ".$check_boxes."\n";
$body_message .= "Did the customer agree: ".$radio_button."\n";
$body_message .= "Selected item from the dropdown list: ".$drop_down_item;

SUGERENCIA: Una pequeña actualización que puede ser útil. En la versión anterior del script, después del mensaje de alerta de JavaScript, había una redirección manual a la página especificada en el código window.location = ‘contact_page.html’;. Así que si cambia el nombre contact_page.html por otra cosa, tendrá que corregir el nombre en el fichero contact.php. Una manera mejor es reemplazar ese código con esto.

history.back(1);

Básicamente, el código ‘explica’ lo que hace. Esto es lo mismo que hacer clic en Back (volver) en su navegador.

  • no1jester

    great guide i just have 1 question
    can i just insert the information on the contact page into a page on my webpage instead of the “contact” page?

    No votes yet.
    Please wait...
    • Anónimo

      Yes you can do this.

      No votes yet.
      Please wait...
  • Brian

    This guide was quite helpful and I learned a few valuable things. However, I found that the resulting email message did not contain ANY headers. I didn’t know any PHP before this, but when I experimented and changed ‘$cf_email’ in the headers section to ‘$field_email’, my problem was resolved. Perhaps this was a typo?

    No votes yet.
    Please wait...
  • Gordon J. Blair

    Thank you Brian for noting the error. The code has been corrected

    No votes yet.
    Please wait...
  • wcs

    i dont seem to be getting sent an email i change where i saw your email to mine as well as $mail_to = ‘my email’ it comes up saying the mail was sent successfully but i never receive anything any ideas?

    No votes yet.
    Please wait...
  • wcs

    i seem to be struggling a little i dont get an error but i also dont receive the email but i get the msg saying it has been sent

    No votes yet.
    Please wait...
    • Anónimo

      Please make sure you set the correct email adress to receive messages.Also make sure your mail server is configured correctly. You can contact your hosting provider to check mail server.
      Also please contact our technicians using our online help desk at http://esupport.template-help.com/index.php?/Tickets/Submit, they will provide you with further assistance.

      No votes yet.
      Please wait...
  • Amechi Ofozor

    Thank you for the wonderful and explicit exposition of these codes. However, i woul like to know where to put the contact.php , because i put mine in the public_html yet i don’t receive emails sent by visitors on the website. Your candid response is appreciated.

    No votes yet.
    Please wait...
    • Gordon J. Blair

      The contact.php file should be placed into the same directory as the .html file with the contact form. So if your contact_page.html file is for example in folder /public_html/test/ then the .php file should be there as well

      No votes yet.
      Please wait...
  • Kim Harrison

    Hi,
    Thank you very much for this tutorial! I’m finding that it’s not working for me.. and I’m sure it’s something I’m doing wrong.

    When I click submit, it changes to an error page and when I look at the link, it’s actually gone to the contact.php page. Is this supposed to happen?

    Also, I’m not sure if this is the reason why, but for my website, I’m using php files and I’m using the php includes for things such as the navigation, footer and the contact form. These are in a separate folder called includes. The form is also in this folder but I also put the contact.php file in there too.

    What am i doing wrong?

    No votes yet.
    Please wait...
    • Gordon

      Can’t say for sure where the source of the issue lies. Please, submit your issue to our Online Help Center http://esupport.template-help.com/index.php?_m=tickets&_a=submit and provide FTP access so we could investigate the issue

      No votes yet.
      Please wait...
  • Steve

    Great help and thank you!

    Can you please tell me how I can add a phone number between the email and message fields?

    No votes yet.
    Please wait...
    • Anónimo

      This cab done the same way as described in the tutorial, but instead of readio button or select box use the text input:

      No votes yet.
      Please wait...
      • Steve

        Great, got it. One thing more – I am trying to get the info coming back to me to include “From”. The info only comes back in the subject part of the email and the from is blank.

        Here is the code from the contact.php – What do I need to add to get the from in the from instead of all in the subject? Thanks Steve.

        <?php
        $field_name = $_POST['cf_name'];
        $field_email = $_POST['cf_email'];
        $field_phone = $_POST['cf_phone'];
        $field_message = $_POST['cf_message'];

        $mail_to = 'steve@emailaddress.biz';
        $subject = 'Message from contact visitor '.$field_name;

        $body_message = 'From: '.$field_name."n";
        $body_message .= 'E-mail: '.$field_email."n";
        $body_message .= 'Phone: '.$field_phone."n";
        $body_message .= 'Message: '.$field_message."n";

        $headers = 'From: '.$cf_email."rn";
        $headers .= 'Reply-To: '.$cf_email."rn";

        $mail_status = mail($mail_to, $subject, $body_message, $headers);
        ……

        No votes yet.
        Please wait...
        • Gordon

          there was a small error in the tutorial files. Replace
          $headers = ‘From: ‘.$cf_email.”rn”;
          $headers .= ‘Reply-To: ‘.$cf_email.”rn”;

          with

          $headers = ‘From: ‘.$field_email.”rn”;
          $headers .= ‘Reply-To: ‘.$field_email.”rn”;

          The code in the files and tutorial has been updated

          No votes yet.
          Please wait...
  • Steve

    How do you add captcha security to the form?

    No votes yet.
    Please wait...
    • Anónimo

      Adding captcha is an additional customization and is beyond of our sphere of free support services. We recommend you to search google. It offers a lot of affordable solutions

      No votes yet.
      Please wait...
  • Victor Chia

    Great tutorial. Is there a way where i could custom style the pop-up mail status message? please advise.

    No votes yet.
    Please wait...
    • Anónimo

      Unfortunately it’s not possible to change the pop-up window style in this contact form example. You can only do that if you are using the JavaScript based contact form.

      No votes yet.
      Please wait...
  • Brock

    Hello, Im hoping someone can help. I am also using the contact.php code provided by template monster, but I can’t get the code to work 100%.

    I get one of the following things happen:

    1) if i use…

    $headers = ‘From: ‘.$cf_email.”rn”;
    $headers .= ‘Reply-To: ‘.$cf_email.”rn”;

    …I recieve an email, but I get 2 “undefined variable” error msgs for the above 2 lines.

    2) if I use…

    $headers = “From: $cf_emailrn”;
    $headers .= “Reply-To: $cf_emailrn”;

    …no email will send, but no error msgs either?

    Please help, it’s driving me mad!

    No votes yet.
    Please wait...
    • Anónimo

      Please replace the variable $cf_email with $field_email

      No votes yet.
      Please wait...
  • Gordon

    If you get full php code of the file, it means PHP is not installed or enabled on the server. You need to consult with your host provider

    No votes yet.
    Please wait...
  • Satyam Saini

    Hi..

    could you please design the php form for the code below?

    Name (required)

    Email (required)

    Website

    Thank you!

    No votes yet.
    Please wait...
    • Anónimo

      We regret but our team do not offer customization services. You can contact our partner at templatetuning.com and get any kind of customization there.

      No votes yet.
      Please wait...
  • Alex Ross

    You should use unique names for your select boxes like cf_drop_down1 and cf_drop_down2. Then in PHP you can use:
    $drop_down_item1 = $_POST[‘cf_drop_down1’];

    $drop_down_item2 = $_POST[‘cf_drop_down2’];

    No votes yet.
    Please wait...
    • mistergookey

      I figured it out a few minutes after commenting in the end but thanks anyway!

      No votes yet.
      Please wait...
  • Teriann Shrum

    THANK YOU for this tutorial. I just needed a very simple contact form and you provided it with excellent instruction!

    No votes yet.
    Please wait...
 
Chat en Vivo
We help you to choose the right product.
Comenzar Chat