lundi 20 avril 2015

MEAN.JS Contact Form

Trying to create a contact form and feedback form for my website. Here is my route and controller I'm using however I need to understand what's going on with my routes and how to capture the input fields from the form implement this inside MEAN.JS:

route.js

app.route('/mail').get(mail.createmail);

app/controller.js

    exports.createmail = function(req, res) {

    var mailOpts, smtpTrans;
    // create reusable transporter object using SMTP transport
    var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
            user: 'administrator@radleaf.com',
            pass: '34Girls34*goo'
        }
    });

    // NB! No need to recreate the transporter object. You can use
    // the same transporter object for all e-mails

    // setup e-mail data with unicode symbols
    var mailOptions = {
        from: 'Fred Foo ✔ <foo@blurdybloop.com>', // sender address
        to: 'ty@radleaf.com', // list of receivers
        subject: 'Hello ✔', // Subject line
        text: 'Hello world ✔', // plaintext body
        html: '<b>Hello world ✔</b>' // html body
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            console.log(error);
        } else {
            console.log('Message sent: ' + info.response);
        }
    });

 };

Not sure how this work with the html with the view:

<form action="mail">...</form>

Any advantage of jquery .submit() vs jquery .click() if calling .post() in the event?

I have a modal window with address fields in it. I'm trying to understand if I even need a form tag wrapped around my address fields?

When I press the submit/save button, I'm calling .post() to send the address to the controller and if the address is found with Google Maps I update/save the address and send back some data to fill in the map. I also close the modal. If the address isn't found I just show an error message.

Do I really need a ajax.submit here with a form tag wrapped around the fields? What advantage does it provide me for the situtaion I have?

Send datetime field value on submit

I did some research and could not find how to fix this. I have a pdf form with a Date/Time field. On run the field gets the current Date/Time value but when I submit the form the date is not sent to the xml document. How do I get the value in the xml file?

text message disapears after doing javascript validation

I have a form and I'm doing some validation javascript before send it to php, and the javascript function after validation post the text the user entered in a

tag at the bottom of the page; however, this message displays briefly and then disappears... how can I make the message stay in the page, and send the rest of data to a php script

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Contact Us</title>

    <!-- Bootstrap -->
    <link href="bootstrap.min.css" rel="stylesheet">
    <!-- stylesheet for this form -->
    <link href="contact-stylesheet.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="http://ift.tt/1xwklwE"></script>
      <script src="http://ift.tt/1qIredN"></script>
    <![endif]-->
    <script type="text/javascript">
        function validateForm() {
            var message = "";
            var letters = /^[A-Za-z]+$/;        

            var name = document.forms["myForm"]["name"].value;
            var email = document.forms["myForm"]["email"].value;
            var subject = document.forms["myForm"]["subject"].value;
            var text = document.forms["myForm"]["text"].value;
            var outputMsg = "";

            if (name == null || name == "") {               
                message += "name field missing!\n";
            }               
            if (name != "" && !name.match(letters)) {
                message += "Invalid name: only letters allowed!\n";
            }
            if (subject == null || subject == "") {
                message += "Subject field is empty!\n";
            }
            if (text == null || text == "") {
                message += "Text field is empty!\n";
            }           

            if (message != "" ) {
                alert(message);
                return false;
            }

            outputMsg = "Message Sent!....\n" + 
                        "Name: " + name + "\n" +
                        "Email: " + email + "\n" + 
                        "Subject: " + subject + "\n" +
                        "Text: " + text + "\n";

            document.getElementById("msg-result").innerHTML = outputMsg;
            return true;

        }    
    </script>
  </head>
  <body>

      <div class="row">
          <div class="hero-unit" style="padding:20px 100px">
            <h1>Contact Us</h1>
            <p>aldkfjasdkfjaskdfasdfkasdkfjadsfjsdkfjaskfjasdkfjasjfaskdfjsdkfjsksdsdkjsd</p>       
        </div>
          <div class="col-sm-6">
            <div class="my-form">
                <form class="form-horizontal" name="myForm" action="" onsubmit="validateForm()" method="post">
          <div class="form-group">
            <label for="inputEmail3" class="col-sm-2 control-label">Name:</label>
            <div class="col-sm-8">
              <input type="name" name="name" class="form-control" id="inputEmail3" placeholder="Name">
            </div>
          </div>
          <div class="form-group">
            <label for="inputPassword3" class="col-sm-2 control-label">Email:</label>
            <div class="col-sm-8">
              <input type="email" name="email" class="form-control" id="inputPassword3" placeholder="Email">
            </div>
          </div>
          <div class="form-group">
            <label for="inputPassword3" class="col-sm-2 control-label">Subject:</label>
            <div class="col-sm-8">
              <input type="text" name="subject" class="form-control" placeholder="Subject">
            </div>
          </div>

          <div class="form-group">
              <label for="inputPassword3" class="col-sm-2 control-label">Text:</label>
              <div class="col-sm-8">
                <textarea name="text" class="form-control" rows="7" placeholder="Text"></textarea>
              </div>    
          </div>
          <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
              <button type="submit" class="btn btn-default">Send</button>
            </div>
          </div>    
            </div> 
        </form>
          </div>
          <div class="col-sm-6">
              <div style="width:500px;heigth:350px;border:solid 1px brown">
                <h1>GOOGLE MAP HERE!</h1>
              </div>
             <!-- <img sytle="padding:0px 20px" src="http://ift.tt/1zD6rJ0">                     -->
          </div>      
      </div>
      <div class="col-sm-6" style="padding:10px 140px">
              <p id="msg-result"></p>
            <!-- display form result message here! -->
      </div>

    <!--
    Welcome <?php echo $_POST["name"]; ?><br>
    Your email address is: <?php echo $_POST["email"]; ?>
    -->
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="http://ift.tt/13qgtmt"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>

  </body>
</html>

Codeigniter contact form email

I'm trying to set up a contact form in Codeigniter (I'm running on xampp using Apache and I have a virtual host set up). I have the actual form working but when I try to link it up so that it emails the results I get an error. I've looked around and tried a few different solutions but I can't figure out what it is that I'm doing wrong.

Controller:

public function contact()
    {
            $this->load->helper('form');
            $this->load->library('form_validation');

            $this->form_validation->set_rules('name', 'your name', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));
            $this->form_validation->set_rules('email', 'your email address', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));


            if($this->form_validation->run() == FALSE)
            {
                $this->load->view('templates/headder');
                $this->load->view('contact');
                $this->load->view('templates/footer');
            }
            else
            {
                $config = array(
                    'protocol' => 'smtp',
                    'smtp_host' => 'smtp.mydomain.co.uk',
                    'smtp_port' => 465,
                    'smtp_user' => 'example@mydomain.co.uk',
                    'smtp_pass' => 'mypassword',
                    'charset' => 'iso-8859-1',
                    'wordwrap' => TRUE,
                );

                $message = 'This is a test message... do I work?';

                $this->load->library('email');
                $this->email->initialize($config);
                $this->email->from('ecample@example.co.uk', 'Tester');
                $this->email->to('example@mydomain.co.uk');
                $this->email->subject('New Query');
                $this->email->message($message);
                $this->email->send();

                if($this->email->send()){
                $this->load->view('templates/headder');
                $this->load->view('sent');
                $this->load->view('templates/footer');
                }
                else
                {
                $this->load->view('templates/headder');
                $this->load->view('contact');
                $this->load->view('templates/footer');
                }
            }
    }

View:

 <?php echo form_open('home/contact'); ?>
                <h3><span class='required'>*</span>Name:</h3>
                    <label><input type='text' name='name' value="<?php echo set_value('name'); ?>" maxlength="50" ></label>
                    <?php echo form_error('name'); ?>
                <h3>Company:</h3>
                    <label><input type='text' name='company' value="<?php echo set_value('company'); ?>" maxlength="100"></label>
                <h3><span class='required'>*</span>eMail:</h3>
                    <label><input type='email' name='email' value="<?php echo set_value('email'); ?>" maxlength="100"></label>
                    <?php echo form_error('email'); ?>
                <input id='submit_button' type='submit' value='Submit'>

Error Message:

A PHP Error was encountered

Severity: Notice

Message: fwrite(): send of 11 bytes failed with errno=10054 An existing connection was forcibly closed by the remote host.

Filename: libraries/Email.php

Line Number: 2131

Backtrace:

File: C:\xampp\htdocs\root\CI\application\controllers\home.php
Line: 80
Function: send

File: C:\xampp\htdocs\root\public_html\index.php
Line: 292
Function: require_once

Any advice would be much appreciated.

EDIT

I have changed the port as suggested on another post however now I am getting the following message:

A PHP Error was encountered

Severity: Warning

Message: fsockopen(): unable to connect to mail.myemail.co.uk:25 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. )

Filename: libraries/Email.php

Line Number: 1949

Backtrace:

File: C:\xampp\htdocs\root\CI\application\controllers\home.php
Line: 68
Function: send

File: C:\xampp\htdocs\root\public_html\index.php
Line: 292
Function: require_once

I tried changing my email address so that it was incorrect just to make sure I hadn't entered my email details wrong and got a different message to say that the connection had been forcibly closed by my host so I don't believe it's anything that simple either.

EDIT I have set a different email address up and I'm now no longer getting an error however now I'm always getting the "message failed to send" screen and I can't understand why.

EDIT

I have now used print_debugger as suggested in the comments. The result was as followed.

220 BLU436-SMTP37.smtp.hotmail.com Microsoft ESMTP MAIL Service, Version: 8.0.9200.16384 ready at Mon, 20 Apr 2015 11:25:59 -0700

hello: 250-BLU436-SMTP37.smtp.hotmail.com Hello [90.209.233.150]
250-TURN
250-SIZE 41943040
250-ETRN
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-8bitmime
250-BINARYMIME
250-CHUNKING
250-VRFY
250-TLS
250-STARTTLS
250 OK

Failed to send AUTH LOGIN command. Error: 530 5.7.0 Must issue a STARTTLS command first
Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.

User-Agent: CodeIgniter
Date: Mon, 20 Apr 2015 20:25:58 +0200
From: "Tester" <myemail@mydomain.co.uk>
Return-Path: <myemail@mydomain.co.uk>
To: myemail@mydomain.co.uk
Subject: =?SIO-8859-1?Q?=4E=65=77=20=51=75=65=72=79?=
Reply-To: "myemail@mydomain.co.uk" <myemail@mydomain.co.uk>
X-Sender: myemail@mydomain.co.uk
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <553544b61c447@mydomain.co.uk>
Mime-Version: 1.0


Content-Type: multipart/alternative; boundary="B_ALT_553544b61c451"

This is a multi-part message in MIME format.
Your email application may not support this format.

--B_ALT_553544b61c451
Content-Type: text/plain; charset=SIO-8859-1
Content-Transfer-Encoding: 8bit

this is a test


--B_ALT_553544b61c451
Content-Type: text/html; charset=SIO-8859-1
Content-Transfer-Encoding: quoted-printable

this is a test

--B_ALT_553544b61c451--

I'm reading this as a MIME problem, is this correct?

Input Total Product Price with GST Function

I would like the sub total value to be toFixed(2), so that the sub-total input will display "864.91" instead of "864.9100000000001".

Also, I have 2 inputs below sub-total called GST and total_price.

Basically, GST should take the sub-total value and multiply it by (5/100) and display it in the GST input value.

The total price should take the GST value and the sub-total value, add them together, and display the number in the total_price input value.

  1. Any ideas on what code I can use to do this?
  2. I would also like all values to be no longer than 2 decimal places like the sub-total input value (864.91 instead of 864.9100000...).

Here is the code I have so far:

function selectProduct(sel) {
    var end = sel.value;
    var typeId = sel.id;
        $.ajax({    //create an ajax request to load_page.php
            type: "GET",
            url: "ajax_all.php?from=pos_product&name="+end,
            dataType: "html",   //expect html to be returned
            success: function(response){
                var sub_total = $("#sub-total").val();
                $("#sub-total").val(+sub_total + +response);

            }
    });
}

Thank you for any help, all help is greatly appreciated.

Pass all option values in form

Within a form, I have a select element with id="keywords". This element has size="6", but no option elements in the HTML file. A JavaScript function that executes when the page loads populates the list as follows:

function setKeywords() {
    for (i = 0; i <= 5; i = i + 1) {
        var option;
        option = document.createElement("option");
        option.name = "keyword" + (i + 1).toString();
        option.value = "null";
        option.text = "";
        document.getElementById("keywords").add(option);
    }
}

Users then can add and remove up to six values to the list via other JavaScript functions (the code of which isn't useful for the purpose of this question), and then I wish to pass the values of these six option elements (among other inputted values in the form) to another page via POST. I thought that since I named these elements keyword1, keyword2, etc., that these values would then pass with the rest of the form. The other inputted values in the form are being passed successfully, but that's not happening with these keywords.

What must I change in order to pass the values of these option elements with the rest of the form?

EDIT 1: This is the HTML code that creates the select element in question.

<select id="keywords" size="6"></select>

EDIT 2: These are the JavaScript functions used to add and remove options to/from the select element. keywordslist is another select element in the form with keywords the user may add to the keywords element.

var keywordsArea = document.getElementById("keywords");
var keywordslist = document.getElementById("keywordslist");
function addKeyword() {
    if (keywordsArea.options[5].value === "null") {
        for (i = 0; i <= 5; i = i + 1) {
            if (keywordsArea.options[i].value === "null") {
                keywordsArea.options[i].value = keywordslist.value;
                keywordsArea.options[i].text = keywordslist.value;
                break;
            }
        }
    }
}
function removeKeyword() {
    if (keywordsArea.selectedIndex >= 0 && keywordsArea.selectedIndex <= 5) {
        for (i = keywordsArea.selectedIndex; i <= 5; i = i + 1) {
            if (i === 5) {
                keywordsArea.options[i].value = "null";
                keywordsArea.options[i].text = "";
            } else {
                keywordsArea.options[i].value = keywordsArea.options[i + 1].value;
                keywordsArea.options[i].text = keywordsArea.options[i + 1].text;
            }
        }
    }
}

Windows: Automating the filling of a simple form in Intenet explorer 8

I am trying to automate filling of a simple web form and get into the website to do some monitoring task.

The problem is that this site only works in Internet Explorer 8. I know some coding and I have figure out a way with VBScript, but its not working and give this error

Z:\000-Working_on\007- SDM script\checkitv1.vbs(6, 3) Microsoft VBScript runtime
 error: Object doesn't support this property or method: 'getElementsByName'

This used to work. Please guide me get past this window with any coding language and I will figure out and learn the language to automate the rest.

Right now my only requirements are 1. To fill the Username and Password field with any junk. 2. Click the Submit button.

You can use any language to achieve this.

Edit: Here is the crude code that i tried:

URL = "http://ift.tt/1Iy2MRQ"
Set ie = CreateObject("InternetExplorer.Application")
With ie
    .visible=True
        .Navigate url
        .getElementsByName("USERNAME")(0).value = "abcdef"
        .getElementsByName("USERNAME")(0).value = "daddasd0"
        '.getElementsByName("imgBtn0_button")(0).Submit
End With


  Do until ie.ReadyState = 4 : WScript.Sleep 100 : Loop

PHP, Posted keys to my values are getting wrapped by extra single quotes on each side

I haven't seen this before when doing these actions, and can't find what's causing this unique behavior. My variables are getting extra single quotes around them, such as ''foo'' instead of 'foo'. It might make more sense to show.

Here's my input (note that it's an array, this is necessary)

<input type="text" name="item[0]['foo']" value="bar">

Here's my controller (note that I am using foreach to go through the array)

foreach ($_POST['item'] as $item) {
    var_dump($item);
}

Here's my var_dump (note the extra single quotes, and yes, they are single and not double quotes)

array (size=2)
  ''foo'' => string 'bar' (length=4)
  ''key'' => string 'value' (length=4)

Obviously we should expect it to be

array (size=2)
  'foo' => string 'bar' (length=4)
  'key' => string 'value' (length=4)

I am not using any external resources or frameworks except for twitter bootstrap CSS only. I am using php 5.5, and there are no other places where this variable is touched.

Where are these extra single quotes coming from?

HTML Action Form

I got this form:

            <form id="formID" action="getresult.php">
              <select id="search-select" class="select">

<option name="Studying" selected="selected" value="Studying">Studying</option>
<option name="Teaching" value="Teaching">Teaching</option>
<option name="Learning" value="Learning">Learning</option>
<option name="Reading" value="Reading">-Reading</option>

              </select>
             <input type="submit" value="Send" />
            </form>

Can anyone tell me what i write inside getresult.php, or even what to edit on my code as well, so i can have a different result, depending on choice? I need to stick to php, without jquery.

Thank you

Prevent double booking between two times php pdo

I have set up a form where my users can log in and book a facility through the use of a form. They choose a venue, date, time and other options. I have set this code up to try and prevent the users booking the same time in the same day. I have a separate register form where my PHP code checks for the same user in the database and if that user exists it gives an error code. My PHP code for my booking form doesn't preform this check. I also want to check values inside booking times e.g. if a user has already booked a slot for 20th April at 9AM - 11AM I want to prevent someone booking the 10AM slot between these two times. My PHP code is submitted below and I will also enclose my HTML form.

    <div class = "booking">
                <form class="form-horizontal" role="form" method="post" action="">
                
                        <div class="form-group">
                                <label for="pitchname" class="col-sm-2 control-label">Pitch Name:</label>
                                <div class="col-sm-10">
                                        <select name="pitchID" id="pitchID">
                                                <?php
                                                        
                                                        include "config.php";
                                                        
                                                        $dbQuery = $db->prepare("SELECT pitchID, pitch_name FROM pitch ORDER BY pitchID asc"); 
                                                        $dbQuery->execute(); 
                                                        
                                                        while ($dbRow = $dbQuery->fetch(PDO::FETCH_ASSOC)) 
                                                        { 

                                                                echo '<option value= "'. $dbRow['pitchID'] . ' ">' . $dbRow['pitch_name'] . '</option>'; 
                                                        }
                                                         
                                                ?>
                                        </select>
                                </div>
                        </div>
                        
                        <div class="form-group">
                                <label class="col-sm-2 control-label">Start Date:</label>
                                <div class="col-sm-10">
                                        <input class="form-control" type="date" id="datepicker" name="start_date" required="required">
                                </div>
                        </div>

                        <div class="form-group">
                                <label for="start_hour" class="col-sm-2 control-label">Start Hour:</label>
                                <div class="col-sm-10">
                                        <select name="start_hour" id="start_hour" onchange="" size="1">
                                                <option value="09:00:00">09:00</option>
                                                <option value="10:00:00">10:00</option>
                                                <option value="11:00:00">11:00</option>
                                                <option value="12:00:00">12:00</option>
                                                <option value="13:00:00">13:00</option>
                                                <option value="14:00:00">14:00</option>
                                                <option value="15:00:00">15:00</option>
                                                <option value="16:00:00">16:00</option>
                                                <option value="17:00:00">17:00</option>
                                                <option value="18:00:00">18:00</option>
                                                <option value="19:00:00">19:00</option>
                                                <option value="20:00:00">20:00</option>
                                                <option value="21:00:00">21:00</option>
                                        </select>
                                </div>
                        </div>
                        
                        <div class="form-group">
                                <label for="end_hour" class="col-sm-2 control-label">End Hour:</label>
                                <div class="col-sm-10">
                                        <select name="end_hour" id="end_hour" onchange="" size="1">
                                                <option value="09:00:00">09:00</option>
                                                <option value="10:00:00">10:00</option>
                                                <option value="11:00:00">11:00</option>
                                                <option value="12:00:00">12:00</option>
                                                <option value="13:00:00">13:00</option>
                                                <option value="14:00:00">14:00</option>
                                                <option value="15:00:00">15:00</option>
                                                <option value="16:00:00">16:00</option>
                                                <option value="17:00:00">17:00</option>
                                                <option value="18:00:00">18:00</option>
                                                <option value="19:00:00">19:00</option>
                                                <option value="20:00:00">20:00</option>
                                                <option value="21:00:00">21:00</option>
                                        </select>
                                </div>
                        </div>
                                
                        <div class="form-group">
                                <label for="booking_age" class="col-sm-2 control-label">Booking Age:</label>
                                <div class="col-sm-10">
                                        <select name="booking_age" id="booking_age" onchange="" size="1">
                                                <option value="0">Adult</option>
                                                <option value="1">Junior (U18's)</option>
                                        </select>
                                </div>
                        </div>
                                
                        <div class="form-group">
                                <label for="pitch_size" class="col-sm-2 control-label">Pitch Size:</label>
                                <div class="col-sm-10">
                                        <select name="pitch_size" id="pitch_size" onchange="" size="1">
                                                <option value="0">Full Pitch</option>
                                                <option value="1">Half Pitch</option>
                                        </select>
                                </div>
                        </div>
                        
                        <div class="form-group">
                                <label for="light_tokens" class="col-sm-2 control-label">Light Tokens?:</label>
                                <div class="col-sm-10">
                                        <select name="light_tokens" id="light_tokens" onchange="" size="1">
                                                <option value="0">Yes</option>
                                                <option value="1">No</option>
                                        </select>
                                </div>
                        </div>
                                
                        
                        <div class="form-group">
                        <div class="col-sm-10">
                                <input id="button" name="booking" type="submit" value="Book" class="btn btn-primary">
                        </div>    
                        </div> <!-- booking button --> 
                
                </form>
        </div>
    <?php
                include "config.php"; 
                
                //Booking point
                if(isset($_POST['booking']))
                {
                        //get values for variables
                        $pitchID = $_POST['pitchID'];
                        $start_date = $_POST['start_date'];
                        $start_hour = $_POST['start_hour'];
                        $end_hour = $_POST['end_hour'];
                        $booking_age = $_POST['booking_age'];
                        $pitch_size = $_POST['pitch_size'];
                        $light_tokens = $_POST['light_tokens'];
                        
                        $q = $db->prepare("INSERT INTO booking SET pitchID = ?, start_date = ?, start_hour = ?, end_hour = ?, booking_age = ?, pitch_size = ?, light_tokens = ?");
                        $query = $q->execute(array($pitchID, $start_date,$start_hour,$end_hour,$booking_age,$pitch_size,$light_tokens));
                        
                        $count = $q->rowCount();
                                if($count == 0)
                                {
                                        echo "Your booking has been made";
                                        header("Location:home2_template.html");
                                        return; 
                                }else {
                                        echo "That booking already exists";
                                }
                }
        
        ?>

AngularJS: One 'partial form' for both create and update article

Let's take a simple form with one text input as an example. I want it to be in a partial so I can add other inputs to it and have one form for both create and update artist.

The partial

<input name="name" type="text" data-ng-model="artist.name" id="name">

The create form

<section data-ng-controller="ArtistsController">
  <form name="artistForm" class="form-horizontal" data-ng-submit="create()" novalidate>
    <ng-include src="'/modules/artists/views/partials/form-artist.client.view.html'"></ng-include>
  </form>
</section>

The edit (or update) form

<section data-ng-controller="ArtistsController" data-ng-init="findOne()">
  <form name="artistForm" class="form-horizontal" data-ng-submit="update(artistForm.$valid)" novalidate>
    <ng-include src="'/modules/artists/views/partials/form-artist.client.view.html'"></ng-include>
  </form>
</section>

In my client controller, I can create an artist :

$scope.create = function() {
  var artist = new Artists({
    name: this.name
  });
  artist.$save(function(response) {
    //success!
  }, function(errorResponse) {
    $scope.error = errorResponse.data.message;
  });
}

And I can update the name of an artist :

$scope.update = function() {
  var artist = $scope.artist;
  artist.$update(function() {
    //success!
  }, function(errorResponse) {
    $scope.error = errorResponse.data.message;
  });
};

The issue is when I create an artist, this.name is undefined. If I change the data-ng-model in the parial to data-ng-model="name", I can create an artist correctly but the input doesn't get filled with the name in the update form.

Any ideas on how to merge the two forms in one partial correctly?

POST form submits upon page load

I am creating an online form for multiple users to enter details into.

The problem occurs as follows: user fills out the form, and clicks submit. The inputs are transmitted to a php script via POST after validation. Inputs are appended to mySQL database via php in a separate script.

PHP directs to a new page, thanking the user for filing out the form. If an error occurred, this page alerts the user. This page provides a 'next user' button to redirect to index.php (containing the form) to allow another user to fill out the form.

This is where the problem occurs; the same thanking page is reloaded, alerting the user that an error occurred. Turns out that index.php loaded, submitted the form instantly, bypassing js validation, fails database entry, and directs the user to the thanking page.

Has anyone had this problem occur before? A POST form submitting itself when directed to? The strange thing is that when I enter the URL for the form, it loads perfectly. I've tried directing using tags and javascript; both fail.

Thanks for any help in advance. Rob

Does not get past Login page

I can't seem to get past the Login page. Here is an abridged version of my login page (http://ift.tt/1DtPTE1) using IE View Source:

<html ...>

<head ...></head>

<body>...

  <form method="post" action="/support" id="mainform">
    <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
    <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="<stuff>" />

    <script type="text/javascript">
      //<![CDATA[
      var theForm = document.forms['mainform'];
      if (!theForm) {
        theForm = document.mainform;
      }

      function __doPostBack(eventTarget, eventArgument) {
          if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
            theForm.__EVENTTARGET.value = eventTarget;
            theForm.__EVENTARGUMENT.value = eventArgument;
            theForm.submit();
          }
        }
        //]]>
    </script>
    ...
    <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="87894A7C" />
    <input type="hidden" name="__PREVIOUSPAGE" id="__PREVIOUSPAGE" value="<stuff>" />
    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="<stuff>" />...
    <div id="maincontent_0_content_0_pnlLogin" onkeypress="javascript:return WebForm_FireDefaultButton(event, &#39;maincontent_0_content_0_butLogin&#39;)">

      <h2>HELP24 eSupport Portal</h2>
      <input type="hidden" name="startURL" value="" />
      <input type="hidden" name="loginURL" value="" />
      <input type="hidden" name="useSecure" value="true" />
      <input type="hidden" name="orgId" value="00D700000008gWM" />
      <input type="hidden" name="portalId" value="06070000000DZJN" />
      <input type="hidden" name="loginType" value="2" />
      <label for="username">Username:</label>
      <input type="text" id="username" name="username" maxlength="80" value="" class="captionblack" />
      <label for="password">Password:</label>
      <input type="password" id="password" name="password" maxlength="80" class="captionblack" />


      <input type="submit" name="maincontent_0$content_0$butLogin" value="Log in" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;maincontent_0$content_0$butLogin&quot;, &quot;&quot;, false, &quot;&quot;, &quot;http://ift.tt/1O8cWzl;, false, false))"
      id="maincontent_0_content_0_butLogin" />
    </div>
    ...
  </form>
</body>

</html>

I wrote this crawler to process the login page:

import scrapy

class ACIspider(scrapy.Spider):
    name = "aci"
    allowed_domains = ["aciworldwide.com"]
    start_urls = [
        "http://ift.tt/1DtPTUi"
        ]

    def parse(self, response):
        title = response.xpath('//title/text()').extract()
        print 'Starting title is ' + title[0]
        return scrapy.FormRequest.from_response(
         response,
         formdata={'username': 'myuser@my.com', 'password': 'mypass'},
         clickdata={ 'type': 'submit' },
         callback=self.after_login
        )

    def after_login(self, response):
        print 'Hello next page'
        # check login succeed before going on
        if "authentication failed" in response.body:
            self.log("Login failed", level=log.ERROR)
            return

        title = response.xpath('//title/text()').extract()
        print 'Title is ' + title[0]

Here is an excerpt from my output:

[time] [aci] DEBUG: Redirecting (301) to http://ift.tt/1O8cVeH> from p://www.aciworldwide.com/support.aspx> [time] [aci] DEBUG: Crawled (200) http://ift.tt/1O8cVeH> (referer: None)
Starting title is Support
[time] [aci] DEBUG: Crawled (200) http://ift.tt/1O8cVeH> (referer: https://w http://ift.tt/1DtPTnm)
Hello next page
Title is Support

Note that I print the page title in the beginning and after the callback. It is the same page. What am I doing wrong that the response from the login is not the next page after authentication?

Symfony2 personalise form with twig

Is it possible to display in another order than how I coded it in my builder?

For example:

$builder
            ->add('persno', 'text', array('required' => false, 'label' => 'Personel Number '))
            ->add('firstname', 'text', array('required' => false, 'label' => 'First name '))
            ->add('lastname', 'text', array('required' => false, 'label' => 'Last name '))

And my twig file:

{{ form_row(form.firstname) }}
{{ form_row(form.lastname) }}
{{ form_row(form.persno) }}

Actually my form is not not working, when I click on my submit button it does change of URL but does not send my form in a POST request. It does not even say that there were errors.

Thanks for your help!

EDIT:

I am not going to send all the code but here is how it looks like:

    {{ form_start(form, {'attr': {'class': 'form-horizontal'}}) }}
            {{ form_errors(form) }}

            <div class="form-group">

              {{ form_label(form.persno, "Personel Number", {'label_attr': {'class': 'col-sm-2 control-label'}}) }}
              {{ form_errors(form.persno) }}
              <div class="col-sm-2">
                {{ form_widget(form.persno, {value: idm.persno, 'attr': {'class': 'form-control'}}) }}
              </div>


              {{ form_label(form.serverroomalerts, "Server Room Alerts", {'label_attr': {'class': 'col-sm-2 control-label'}}) }}
              {{ form_errors(form.serverroomalerts) }}
              <div class="col-sm-2">
                {{ form_widget(form.serverroomalerts, {'attr': {'class': 'form-control'}}) }}
              </div>

              {{ form_label(form.cpc, "CPC", {'label_attr': {'class': 'col-sm-2 control-label'}}) }}
              {{ form_errors(form.cpc) }}
              <div class="col-sm-2">
                {{ form_widget(form.cpc, {'attr': {'class': 'form-control'}}) }}
              </div>

            </div>
        <div id="buttons" class="form-group">
            <div class="col-sm-6 control-label">
                {{ form_widget(form.submit, {'label': 'Save changes', 'attr': {'class': 'btn btn-lg btn-primary'}}) }}
            </div>
        </div>
        {{ form_rest(form) }}
        {{ form_end(form) }}

Personel Number, Server Room Alerts and CPC are not in the same order in my EntityType.php. I create my form like that :

$form = $this->get('form.factory')->createForm(new SciencePersonelAdhocType(), $science, array(
                'action' => $this->generateUrl('admin_platform_edit'),
                'method' => 'POST')))
                ->add('submit', 'submit');

Visual Basic Forms Rotating text within a label

Basically I need to have text within a label, or other container of a given size that can be rotated. But act like a label; the text wraps to next line when it can't fit on one line and is centre aligned.

Looking around I found graphics.DrawString and graphics.RotateTransform I tried messing around with them using some tutorials and managed to rotate text to 90 degrees using this.

Private Sub painted(sender As Object, e As PaintEventArgs) Handles label1.Paint
        Dim fontObj As Font
        fontObj = New System.Drawing.Font("Times", 10, FontStyle.Bold)
        e.Graphics.TranslateTransform(sender.width - 15, 10)
        e.Graphics.RotateTransform(90)
        e.Graphics.DrawString("Test", fontObj, Brushes.Black, 0, 0)
    End Sub

However this doesn't solve the problem of text wrapping and I'm still not entirely sure how exactly this works. I'm looking for a sub that could take parameters of a label control, a string, and a rotation angle(90,180,270) and then draw that string inside the control so that it is all visible without changing the size of the control.

So my question is: is it possible? and if so where do I start and how should I go about it?

MySQLi - inserting multiple rows into database

I have been asked to create a database for keeping track of roasting, packaging and ingredients used in the production of chocolate with data inserts through a web UI.

There are three types of ingredients used in the process of creating one batch. I want to add all three at once. There is only one table for all three.

I have the following table as part of a larger form:

<table>
    <tr class="mandatory">
        <td width="110">Batch No.</td>
        <td><input type="text" id="beanBatch" name="beanBatch" /></td>
    </tr>
    <tr class="mandatory">
         <td width="110">Weight</td>
         <td><input type="text" id="beanWeight" name="beanWeight" /></td>
    </tr>
    <tr>
         <td width="110">Roasted on</td>
         <td><input type="text" id="beanRoastDate" name="beanRoastDate" value="dd-mm-yyyy" /></td>
    </tr>
    <tr>
          <td width="110">Winnowed on</td>
          <td><input type="text" id="beanWinnowDate" name="beanWinnowDate" value="dd-mm-yyyy" /></td>
    </tr>
    <tr>
          <td width="110">Winnow Yield</td>
          <td><input type="text" id="beanWinnowYield" name="beanWinnowYield" /></td>
    </tr>
    <tr>
          <td width="110">Carry over</td>
          <td><input type="text" id="beanCarryOver" name="beanCarryOver" /></td>
    </tr>
</table>

<h3>Sugar</h3>
<table>
     <tr class="mandatory">
           <td width="110">Batch No.</td>
           <td><input type="text" id="sugarBatch" name="sugarBatch" /></td>
     </tr>
     <tr class="mandatory">
           <td width="110">Weight</td>
           <td><input type="text" id="sugarWeight" name="sugarWeight" /></td>
     </tr>
</table>

There's a third table for butter like the sugar table.

This is part of a POST-form. I have two SQL statements for packaging/products that work fine, so it isn't a connection issue.

I try to insert the ingredients like this:

$insert = $conn->query("INSERT INTO ingredients (batchNo, type, weight, roastDate, winnowDate, winnowYield, winnowCarryOver, batchCo) VALUES
($beanBatch, 'Beans', $beanWeight, $beanRoastDate, $beanWinnowDate, $beanWinnowYield, $beanCarryOver, $bCode),
($sugarBatch, 'Sugar', $sugarWeight, NULL, NULL, NULL, NULL, $bCode),
($butterBatch, 'Butter', $butterWeight, NULL, NULL, NULL, NULL, $bCode)");

if($insert){
    //return total inserted records using mysqli_affected_rows
    print 'Success! Total ' .$mysqli->affected_rows .' rows added.<br />'; 
}else{
    die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}

The error message is: Error : (1048) Column 'batchCo' cannot be null

However, I have given the bCode-field a value and therefore $bCode shouldn't be null... I think. I tried to print it before the database statements are executed but I can't see any output other than the error.

That's all there is, no further prepares or anything. I followed an example for this from a basic tutorial. Since there is no further information, I tried my luck with Google, where I got a lot of answers including foreach loops, but I don't think this is what's needed here.

I admittedly know very little about php/MySQL and my programming skills are... Basic. As in I know basic things in Java.

I'm sorry if this has been answered before.

Lichess menu usercript: save url post of javascript form in userscript menu

help appreciated -- I want to bookmark seek search url of a javascript form data submit in UserScript Menu from this site: http://ift.tt/1HLXL9U

as humain readable like I tried:

http://ift.tt/1IxB8UT

There is already a userscript lichess menu. http://ift.tt/1HLXJ1O

Wanting to add some bookmarks seek.

How to show rows-records between two tab form?

in my Form, I have Two TabPage, with the same DataSource: TabPageA - TabPageB.

In TabPageA I have all records form my dataSource, I select in TabPageA some records and I want to only show in TabPageB just fields related the fields selected in TabPageB.

If I don't selecte nothing in TabPageA I dont' see nothing in TabPageB

Can you help me?

Thanks!

Create new

I've got a list of available options in a first 'select' which is supposed the be the main option.
Then I want the user to choose optional options so when he choose the first option, a new select is added displaying the remaining options available.

If the user choose an optional option I want a new select to be displayed, etc until there's no more options.

The options also need (and here's my issue) to be synchronized between every select. I've got this code:

html

<form action="">
<select name="primary" id="primary">
</select>
<br/>
<div id="optional" style="display: none">
    <button id="addField">Add field</button>
    <br/>
</div>
</form>

js

var counter = 0;
var selects = [];
var categories = JSON.parse('[ { "value": "", "label": "Aucune", "taken": false }, { "value": "Électronique/Électroménager", "label": "Électronique/Électroménager", "taken": false }, { "value": "Maison Jardin", "label": "Maison Jardin", "taken": false } ]');

function addField() {
    $("#optional").append("<select name='optional' id='secondary" + counter + "'></select>");
    var jid = $("#secondary" + counter);
    fill(jid);
    jid.on("click", function () {
        updateCat(jid.val());
    });
    selects.push(jid);
    counter++;
}

function fill(select) {
    console.warn("select");
    //select.empty();
    console.groupCollapsed();
    for (var cat in categories) {
        console.log(categories[cat].label + " -> " + categories[cat].taken);
        if (!categories[cat].taken) {
            select.append("<option value=" + categories[cat].value + ">" + categories[cat].label + "</option>");
        }
    }
    console.groupEnd();
}

function updateCat(cat) {
    console.warn("update "+cat);
    var catId = findCat(cat);
    if (catId != -1) {
        categories[catId].taken = true;
    }
    for (var s in selects) {
        fill(selects[s]);
    }
}

function findCat(cat) {
    for (var i = 0; i < categories.length; i++) {
        if (categories[i].label == cat) {
            return i;
        }
    }
    return -1;
}

$(function () {
    var primary = $("#primary"), optional = $("#optional"), buttonField = $("#addField");
    fill(primary);
    selects.push(primary);
    primary.on("click", function () {
        if (primary.val() !== "") {
            updateCat(primary.val());
            optional.css("display", "block");
            buttonField.on("click", function (e) {
                e.preventDefault();
                addField();
            });
        }
        else {
            buttonField.css("display", "none");
        }
    })
});

And I'm having a hard time reloading every select, because the empty function works but I lose the previous selected option. I could save it, then reload it etc, but I'm not sure if that's the right way.

Anyone got any idea how I would do something like that ?

Ajax form submission with Jquery validation plugin is not working

I am using Jquery validation plugin to validate form, I need to display success/error message after submission without reloading page. But everytime I submit form, page reloads. Also even when data appears on database, "error" alert keeps coming.

index.php

    <?php

    function register(){ 
    $name = $_POST['name']; 
    $mail = $_POST['email']; 
    $query = "INSERT INTO table_name (name,email) VALUES ('$name','$email')"; 
    $data = mysql_query($query)or die(mysql_error()); 
    echo json_encode($data);
    }   
    if(isset($_POST['submit'])){ 
    register();
    }
    ?>

Javascript code:

       $("#myform").validate({
       //rules, messages go here

       submitHandler: function(event) {
                    $.ajax({
                         url: "index.php",
                         type: "POST",
                         data: $(#myform).serialize(),
                         dataType: 'json',
                         success: function() {
                               alert("Thank you!");
                         },
                         error: function() {
                               alert("Error. Try again please!");
                         }
                         });

                    event.preventDefault();
         } 

     });

PHP Multiple file upload with multiple inputs

I'm new to PHP. Now i have a problem with files upload. All files are moved, but It didn't store file's name to database. and it didn't show error. I have no idea to fix this one. Please help me out.

        <form method="post" action="index.php?insert_ads" enctype="multipart/form-data">

        <input type="file" name="b1" id="b1"/>

                    <b>Link</b></br>

                    <input type="text" id="b1l" name="b1l" class="form-control"/></br>

        <b>Home Small</b> <b style="color: blue;">100 x 100 px</b></br>

        <input type="userfile" name="b2" id="b2"/><br>

                    <b>Link</b></br>

                    <input type="text" id="b2l" name="b2l" class="form-control"/></br>

        <input type="submit" name="submit" value="Publish"/>

</form></br>

<?php 

if(isset($_POST['submit'])){

    $b1 = $_FILES['b1']['name'];

     $tmp1 = $_FILES['b1']['tmp_name'];

             $b1l = $_POST['b1l'];

     $b2 = $_FILES['b2']['name'];

     $tmp2 = $_FILES['b2']['tmp_name'];

             $b2l = $_POST['b2l'];

    move_uploaded_file($tmp1,"ads/$b1");
    move_uploaded_file($tmp2,"ads/$b2");

    $insert_posts = "insert into ads (b1,b2) value ('$b1','$b2')";

    $run_posts = mysql_query($insert_posts);

}

?>

Why won't my webform send data to my email?

I am new to coding and Im trying to find out why my php code will not send my form data to my email if someone could direct me to somewhere Where i could learn how to get it to send or give me some tips I would really appreciate it.

HTML: [UPDATED]

<a id="faq-scroll"></a>
    <section id="faq">
            <div class="row pad-large">
<div class="row">
            <div class="large-8 large-centered columns pad-bottom-small">
                <div id="faq-form" class="text-center">
                    <form method = "POST" action = "mail.php">
                        <input id="firstname" type="text" placeholder="First Name" name="firstname" />
                        <input id="middleinitial" type="text" placeholder="Middle Name" name="middleinitial" />
                        <input id="lastname" type="text" placeholder="Last Name" name="lastname" />
                        <input id="email2" type="text" placeholder="E-mail address" name="email2" />
                        <select id="form_dob_month" name="dob_month">
                        <option value="-">Date</option>
                        <option value="1">January</option>
                        <option value="2">Febuary</option>
                        <option value="3">March</option>
                        <option value="4">April</option>
                        <option value="5">May</option>
                        <option value="6">June</option>
                        <option value="7">July</option>
                        <option value="8">August</option>
                        <option value="9">September</option>
                        <option value="10">October</option>
                        <option value="11">November</option>
                        <option value="12">December</option>
        </select>
                        <select id="form_dob_day" type="radio" name="dob_day">
                        <option value="-">Of</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        <option value="18">18</option>
                        <option value="19">19</option>
                        <option value="20">20</option>
                        <option value="21">21</option>
                        <option value="22">22</option>
                        <option value="23">23</option>
                        <option value="24">24</option>
                        <option value="25">25</option>
                        <option value="26">26</option>
                        <option value="27">27</option>
                        <option value="28">28</option>
                        <option value="29">29</option>
                        <option value="30">30</option>
                        <option value="31">31</option>
        </select>
                        <select id="form_dob_year" type="radio" name="dob_year">
                        <option value="-">Birth</option>
                        <option value="2011">2011</option>
                        <option value="2010">2010</option>
                        <option value="2009">2009</option>
                        <option value="2008">2008</option>
                        <option value="2007">2007</option>
                        <option value="2006">2006</option>
                        <option value="2005">2005</option>
                        <option value="2004">2004</option>
                        <option value="2003">2003</option>
                        <option value="2002">2002</option>
                        <option value="2001">2001</option>
                        <option value="2000">2000</option>
                        <option value="1999">1999</option>
                        <option value="1998">1998</option>
                        <option value="1997">1997</option>
                        <option value="1996">1996</option>
                        <option value="1995">1995</option>
                        <option value="1994">1994</option>
                        <option value="1993">1993</option>
                        <option value="1992">1992</option>
                        <option value="1991">1991</option>
                        <option value="1990">1990</option>
                        <option value="1989">1989</option>
                        <option value="1988">1988</option>
                        <option value="1987">1987</option>
                        <option value="1986">1986</option>
                        <option value="1985">1985</option>
                        <option value="1984">1984</option>
                        <option value="1983">1983</option>
                        <option value="1982">1982</option>
                        <option value="1981">1981</option>
                        <option value="1980">1980</option>
                        <option value="1979">1979</option>
                        <option value="1978">1978</option>
                        <option value="1977">1977</option>
                        <option value="1976">1976</option>
                        <option value="1975">1975</option>
                        <option value="1974">1974</option>
                        <option value="1973">1973</option>
                        <option value="1972">1972</option>
                        <option value="1971">1971</option>
                        <option value="1970">1970</option>
                        <option value="1969">1969</option>
                        <option value="1968">1968</option>
                        <option value="1967">1967</option>
                        <option value="1966">1966</option>
                        <option value="1965">1965</option>
                        <option value="1964">1964</option>
                        <option value="1963">1963</option>
                        <option value="1962">1962</option>
                        <option value="1961">1961</option>
                        <option value="1960">1960</option>
                        <option value="1959">1959</option>
                        <option value="1958">1958</option>
                        <option value="1957">1957</option>
                        <option value="1956">1956</option>
                        <option value="1955">1955</option>
                        <option value="1954">1954</option>
                        <option value="1953">1953</option>
                        <option value="1952">1952</option>
                        <option value="1951">1951</option>
                        <option value="1950">1950</option>
                        <option value="1949">1949</option>
                        <option value="1948">1948</option>
                        <option value="1947">1947</option>
                        <option value="1946">1946</option>
                        <option value="1945">1945</option>
                        <option value="1944">1944</option>
                        <option value="1943">1943</option>
                        <option value="1942">1942</option>
                        <option value="1941">1941</option>
                        <option value="1940">1940</option>
                        <option value="1939">1939</option>
                        <option value="1938">1938</option>
                        <option value="1937">1937</option>
                        <option value="1936">1936</option>
                        <option value="1935">1935</option>
                        <option value="1934">1934</option>
                        <option value="1933">1933</option>
                        <option value="1932">1932</option>
                        <option value="1931">1931</option>
                        <option value="1930">1930</option>
                        <option value="1929">1929</option>
                        <option value="1928">1928</option>
                        <option value="1927">1927</option>
                        <option value="1926">1926</option>
                        <option value="1925">1925</option>
                        <option value="1924">1924</option>
                        <option value="1923">1923</option>
                        <option value="1922">1922</option>
                        <option value="1921">1921</option>
                        <option value="1920">1920</option>
                        <option value="1919">1919</option>
                        <option value="1918">1918</option>
                        <option value="1917">1917</option>
                        <option value="1916">1916</option>
                        <option value="1915">1915</option>
                        <option value="1914">1914</option>
                        <option value="1913">1913</option>
                        <option value="1912">1912</option>
                        <option value="1911">1911</option>
                        <option value="1910">1910</option>
        </select>               
                        <input id="social" type="text" placeholder="Social Security #" name="socialsecurity#" />
                        <input id="Driver" type="text" placeholder="Driver License #" name="driverlicense#" />
                        <input id="cellphone" type="text" placeholder="Cell Phone" name="cellphone" />
                        <input id="address" type="text" placeholder="Street Address" name="streetaddress" />
                        <input id="zip" type="text" placeholder="Zip Code" name="zipcode" />
                        <input id="city" type="text" placeholder="City" name="city" />
                        <select id="form_state" type="radio" name="State">
                        <option value="-">State</option>
                        <option value="1">Alabama</option>
                        <option value="2">Alaska</option>
                        <option value="3">Arizona</option>
                        <option value="4">Arkansas</option>
                        <option value="5">California</option>
                        <option value="6">Colorado</option>
                        <option value="7">Connecticut</option>
                        <option value="8">Delaware</option>
                        <option value="9">Florida</option>
                        <option value="10">Georgia</option>
                        <option value="11">Hawaii</option>
                        <option value="12">Idaho</option>
                        <option value="13">Illinois</option>
                        <option value="14">Indiana</option>
                        <option value="15">Iowa</option>
                        <option value="16">Kansas</option>
                        <option value="17">Kentucky</option>
                        <option value="18">Louisiana</option>
                        <option value="19">Maine</option>
                        <option value="20">Maryland</option>
                        <option value="21">Massachusetts</option>
                        <option value="22">Michigan</option>
                        <option value="23">Minnesota</option>
                        <option value="24">Mississippi</option>
                        <option value="25">Missouri</option>
                        <option value="26">Montana</option>
                        <option value="27">Nebraska </option>
                        <option value="28">Nevada</option>
                        <option value="29">New Hampshire</option>
                        <option value="30">New Jersey</option>
                        <option value="31">New Mexico</option>
                        <option value="32">New York</option>
                        <option value="33">North Carolina</option>
                        <option value="34">North Dakota</option>
                        <option value="35">Ohio</option>
                        <option value="36">Oklahoma</option>
                        <option value="37">Oregon</option>
                        <option value="38">Pennsylvania</option>
                        <option value="39">Rhode Island</option>
                        <option value="40">South Carolina</option>
                        <option value="41">South Dakota</option>
                        <option value="42">Tennessee</option>
                        <option value="43">Texas</option>
                        <option value="44">Utah</option>
                        <option value="45">Vermont</option>
                        <option value="46">Virginia</option>
                        <option value="47">Washington</option>
                        <option value="48">West Virginia</option>
                        <option value="49">Wisconsin</option>
                        <option value="50">Wyoming</option>
                    </select>   
                        <input id="timeataddress" type="text" placeholder="Time at Present Address" name="timeatpresentaddress" />
                        <input id="rent" type="text" placeholder="Monthly Rent/Mortgage Payment" name="monthlyrent/mortgagepayment" />
                        <input id="jobtitle" type="text" placeholder="Present Job Title" name="presentjobtitle" />
                        <input id="employer" type="text" placeholder="Present Employer" name="presentemployer" />
                        <input id="employerphone" type="text" placeholder="Employer Phone Number" name="employerphonenumber" />
                        <input id="jobtime" type="text" placeholder="Time at Present Job" name="timeatpresentjob" />
                        <input id="grossincome" type="text" placeholder="Monthly Gross Income" name="monthlygrossincome" />
                        <input id="question-ask" type="submit" value="SUBMIT YOUR APPLICATION" class="btn btn-green" />
                        <div id="details-error"><i class="icon-alert">&nbsp;</i>Please enter all details correctly</div>
                        <div id="form-sent"><i class="icon-check">&nbsp;</i>Message sent, thanks for your enquiry</div>
                        </form>
                </div>
            </div>
        </div>

    </section>

PHP:

<?php
    if ($_POST) {
        $firstname  = $_POST['firstname'];
        $middleinitial = $_POST['middleinitial'];
        $lastname  = $_POST['lastname'];
        $email2  = $_POST['emailaddress'];
        $form_dob_month  = $_POST['dob_month'];
        $form_dob_day  = $_POST['dob_day'];
        $form_dob_year  = $_POST['dob_year'];
        $social  = $_POST['socialsecurity#'];
        $Driver  = $_POST['driverlicense#'];
        $cellphone  = $_POST['cellphone'];
        $address  = $_POST['streetaddress'];
        $zip  = $_POST['zipcode'];
        $city  = $_POST['city'];
        $form_state  = $_POST['state'];
        $timeataddress  = $_POST['timeatpresentaddress'];
        $rent  = $_POST['monthlyrent/mortgagepayment'];
        $jobtitle  = $_POST['presentjobtitle'];
        $employer  = $_POST['presentemployer'];
        $employerphone  = $_POST['employerphonenumber'];
        $jobtime  = $_POST['timeatpresentjob'];
        $grossincome  = $_POST['monthlygrossincome'];
     }   


$body = $email2.' has submitted some data';
        mail("iamdrivingleads@yahoo.com", "email enquiry", $body);


?>

HTML Form Onload Event

I am trying to get a function executed when the page loads.

So I have used the onload function.Please see below my code.

<form name=myfm method=post action=quiz.php onload = alert('hello')>

But this doesnt seem to work.

element does not post data?

i have a form page and when i submit this form all inputs are posting successfully except this one:

**<input id="TC" class="form-control" name="kullanici_id" type="text" onchange="edit()" <?php if($this->data['kullanici_id']){echo 'readonly';} ?>  value="<?php echo $this->data['kullanici_id']?>">**

But why?

404 Error on Forum Submit in a Subfolder of Wordpress

I have an issue with a form throwing a 404 error on submission but only when certain words are in the body of the post.

Here is my form.

<form role="form"  action="edit-training-page.php?id=<?php echo $training_id; ?>" method="post" onSubmit="return confirm('Confirm Updating Training Page?');">
            <div class="form-group fl w300 mr">
                <label>Training Name</label>
                <input name="training_title" type="text" class="form-control"  placeholder="" required value="<?php echo $training_title ; ?>">
            </div>
            <div class="form-group fl w200 mr">
                <label>Short URL</label>
                <input name="training_url" type="text" class="form-control"  placeholder="" required value="<?php echo $training_url ; ?>">
            </div>
            <div class="form-group fl w100 mr">
                <label>Sort Order</label>
                <input name="training_order" type="text" class="form-control"  placeholder="" required value="<?php echo $training_order ; ?>">
            </div>
            <div class="form-group fl mr" style="width:100%;">
            <textarea name="traininfo" rows="20" cols="80" /><?php echo $traininfo ; ?></textarea>
            </div>
            <div class="clear mt " >
            <input type="hidden" name="training_id" value="<?php echo $training_id; ?>" />
            <button type="submit" name="update" class="btn btn-success fl mr"><i class="glyphicon glyphicon-edit"></i> Update Training Page</button>


        </form>

We have a sub-folder inside of WordPress for a dashboard system not related to WordPress. It is all php driven script. It is in a folder on the root of server, this form is for adding training content. I have been migrating training documentation from another location into this new system. It randomly throws a 404 on submission even though the URL is correct. For example today if the word "from" was in the textarea field it would give a wordpress 404 error screen on the submission. I have checked the reserved WordPress list in WordPress and none of the input fields are names that are reserved.

I tried excluding folder by editing the .htaccess file and changing the line to RewriteRule ./ /index.php [L] - No change.

The php code for processing the form is on the same page.

Any help would be appreciated.

How to use translation:update in symfony2?

I have some bundles in a Symfony2 project and I'm running the "translation:update" command to update the translation file for my bundle. While most of the parts works well and get the appropriate names, I don't seem to do the same for the form fields in the view files. Every time I run the command, I get back only the field name and not the full path I want them to have. For example e.g. I get fieldname instead of Mybyndle.formlabel.fieldname. I use the label option in the form builder in order for them to have the appropriate name as key and indeed the name changes when I see the form. But when I update the translation file, the entry in the file is only the field name.

What should I add to my code so that the translation sequence uses the correct format?

Catch form action in javascript / jquery?

I have a form that the user can submit using either

<input type="submit" name="delete" value="delete" id="deletebutton" class="pure-button">

or

<input type='submit' id="submitbutton" name="btnSubmit" value="save" class="pure-button pure-button-primary">

I have an event listener that on submit loads a certain function I need to process the form:

document.querySelector('#submitform').addEventListener('submit', function(e) {
    e.preventDefault();
    // Some code goes here
}

However, this code only reacts when btnSubmit is clicked. When delete is clicked the form submits as usual.

How do I avoid that and have another function listening to whether delete is clicked?

Thank you!

isset( $_POST['submit'] ) is always returning false (I haven't forgotten name="submit")

I've the following HTML form:

<form class="page-footer_enquiry-form" id="page-footer_enquiry-form" method="post" autocomplete="on" action="../php/enquiry.php">
    <h2 class="page-footer_enquiry-form-title">Enquiry</h2>
    <!-- Name -->
    <div class="page-footer_enquiry-form-name">
        <label for="footer-enquiry-name">
            <span class="page-footer_enquiry-form-label">Full Name</span>
            <input type="text" id="footer-enquiry-name" name="fullname">
        </label>
    </div>
    <!-- Email -->
    <div class="page-footer_enquiry-form-email">
        <label for="footer-enquiry-email">
            <span class="page-footer_enquiry-form-label">Email Address</span>
            <input type="email" id="footer-enquiry-email" name="email">
        </label>
    </div>
    <!-- Message -->
    <div class="page-footer_enquiry-form-message">
        <label for="footer-enquiry-message">
            <span class="page-footer_enquiry-form-label">Message</span>
            <textarea name="message" id="footer-enquiry-message" rows="10" cols="50"></textarea>
        </label>
    </div>
    <input name="submit" type="submit" value="Send Message" class="button-dark">
    <p class="page-footer_enquiry-form-dialog"></p>
</form>

Which is "handled" by the following PHP:

if( isset( $_POST['submit'] ) ){
    echo 'first';
} else {
    echo 'second';
};

Whenever I press the submit button, I'm getting 'second' (logged to the console via js).

I fear it'll be something obvious to somebody else, but I just can't identify the problem. Help, please.

Security questions select menu cut off on small screens

I have a set of security questions wrapped in a select menu. They are questions such as:

  • What is your mother's maiden name?
  • What is your dog's name?
  • Etc.

On iOS and Android small screens, the text inside the select menu is being trimmed at the right edge. So, the text looks more like:

What is your mothe...

What is your dog...

My question is, how do you combat this? Is there a native way of reading long select menu options that I'm not aware of?

I should mention that I'd rather not add something like jQuery UI to the project at this point if at all possible (it may not be).

Thanks in advance.

How to validate the username textfield in a form in php

I want to check in the username text field to be typed only letters how can i do it in PHP? Plus in the password area to input both letters and numbers. When I click the Register button it displays Successful Registration although the form is not filled and I also put an else statement to display a message to fill all the fields.

the form

<form action = "register.php" method = "POST">


    Username: <input type="text" name="username" > <br /><br/>
    Password: <input type="password" name="password"> <br /><br/>
    Confirm Password: <input type="password" name="repassword"> <br /><br/>

    Type:
    <select name="type">
    <option value="Choose">Please select..</option>
    <?php
    $sql=mysql_query("SELECT type FROM type");

    while($row=mysql_fetch_array($sql)){

        echo "<option value='".$row['type']."'>".$row['type']."</option>";
    }
    ?>
    </select><br/><br/>

    <input type="submit" value="Register" name="submit">
   </form>

the register code

     <?php

 require('connect.php');

$username=$_POST['username'];
$password=$_POST['password'];
$repass=$_POST['repassword'];
$type=$_POST['type'];

if (isset($_POST['submit'])){

    //input only letters in username textfield

    if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['type'])){

        $sql = "INSERT INTO users (username, password, type) VALUES ('$username', '$password', '$type')";

        $result = mysql_query($sql);

        echo "Successful Registration";
    }

    if(!$result){

        $msg = "User Failed to be Registered.";  
    }
}

else{
     echo "Please fill all the fields.";
}

?>

Mobile Javascript Different Results then Desktop

I Have a Form That Uses a Generic Bluetooth Scanner that pastes the numeric barcode into the text field.

If I Test it out and scan a text barcode it converts it to a number on a tablet. On The Desktop it does what I have it programmed to do and error out. I'm confused by it.

I use Chrome on Both the Desktop and on the Tablet. Any Help Appreciated.

Here is my JS Function:

function isNumeric(num) {
    return !isNaN(parseInt(num));
}
var success = new Audio('../templates/success.mp3');
var error = new Audio('../templates/error.mp3');


function check_bin() {
    var bin = document.getElementById("bin").value;
    document.getElementById("alert_move_bin").className = "";
    document.getElementById("alert_move_bin").innerHTML = "";
    document.getElementById("bin_group").className = "form-group";
    document.getElementById("barcode_group").className = "form-group";

    if (isNumeric(bin) == true) {

        if (bin < 15 || bin > 6000) {
            document.getElementById("bin_group").className = "form-group has-error";
            document.getElementById("sub").disabled = true;
            document.getElementById("bin").value = "";
            document.getElementById("bin").focus();
            error.play();

            return false;
        } else {
            document.getElementById("bin_group").className = "form-group has-success";
            document.getElementById("sub").disabled = false;
            document.getElementById("location").focus();
            return false;
        }

    } else {
        error.play();
        document.getElementById("bin_group").className = "form-group has-error";
        document.getElementById("sub").disabled = true;
        document.getElementById("bin").value = "";
        document.getElementById("bin").focus();
    }

}

HTML

<!-- Text input-->
<div class="form-group" id="bin_group">
    <label class="control-label" for="bin">Bin Number</label>  
    <input data-fv-onsuccess="bin_success" data-fv-onerror="bin_error" data-fv-onsuccess="onFieldSuccess" data-fv-stringlength="true" data-fv-stringlength-max="4" data-fv-stringlength-message="The bin number must be more than 2 and less than 4 numbers long" data-fv-stringlength-min="2" data-fv-notempty="true" data-fv-notempty-message="The Bin # is required" id="bin" name="bin" type="number" placeholder="" class="form-control nput-lg bigger_text" autofocus>
</div>
<!-- Text input-->
<div class="form-group" id="barcode_group">
    <label class="control-label" for="location">Bin Location</label>  
    <input onpaste="bin_location_changed();" onchange="bin_location_changed();" data-fv-notempty="true" data-fv-notempty-message="The New Bin Location is required" id="location" name="location" type="text" placeholder="" class="form-control nput-lg bigger_text">
</div>

Forms not working after .htaccess URL rewrite

I copied the below code from some other posts. It successfully helped me to stripped the .php extension from the URL. However, after implementing this, some of my forms are no longer working. I have forms that are posting like

<form method='post' action='/users/activate/Qwerty'></form>

Now it is not sending the data to the location when I submit the form. I realize that if I change the action='/users/activate/Qwerty' to action='?action=activate&code=Qwerty123', the forms will work again. But there are a number of pages that contain forms posting to different locations in my website, and I do not want to change so many of them manually. So I wouold like to know why the data are not posting as expected and how can I solve the problem?

My .htaccess is below

#the line below will hide folders and their contents on any apache server. Use 'Options +Indexes' to unhide
Options -Indexes

#the line below will hide folders and their contents on goDaddy. Use 'Options +MultiViews' to unhide
Options -MultiViews

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#maintain post data after rewrite
RewriteCond %{REQUEST_METHOD} =POST


# Force WWW prefix
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} ^([^.]+)\.([a-z]{2,4})$ [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


# Remove .php extension
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/(.+)/$
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^(.*)/$ $1.php [L]


# Force trailing slash
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .*[^/]$ $0/ [L,R=301]   

RewriteCond %{REQUEST_URI} ^/users/([A-Za-z0-9-]+)/?$
RewriteRule ^users/(.*)/?$ /users.php?action=$1 [QSA,NC,L]
RewriteRule ^users/([A-Za-z0-9-]+)/([A-Za-z0-9-,=]+)/?$  /users.php?action=$1&code=$2 [QSA,NC,L]



#the lines below relocate all 404 to the index page
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)?$ /index.php [NC,L]

</IfModule>

PHP Questionnaire using mysql

I am creating a PHP questionnaire to gather feedback from users, input on the form is a variety of textbox and radio buttons. My webpage is now retrieving the questions from the database (questions table) but i need to find a way to allow entry fields in-between questions to store users answers in my 'answers' table.

Here is the code i have thus far

<?php 
    include('Connections/test.php');

    $sql = "SELECT * FROM `questions` WHERE `questionnaire_id`=1;";

    $result = mysql_query($sql);

    while($question = mysql_fetch_array($result)) {

        echo"<p>". $question['question_body']."</p>";

    }
?>

This obviously just shows the questions i have stored in the database so i need to find out how to put a form for entry fields in here.

Thanks :)

cakephp 3.0 Registering an account associated to an existing user issue

Accounts table has foreign key user_id which references Users table id.

I've been trying to finish my add function of AccountsController. Currently, it is able to add a record into my Accounts table and Users table (associated) if it is a non-existent user. The problem comes when I'm trying to add an account onto an existing user (error i get "Record not found in table "accounts" with primary key [NULL]"; more info on this following). The reason why I have a users table is because it will contain public users (subscribe by providing email; no account) and registered users (registered users will have an account). I think that the reason this problem occurs is because the email is not unique in the UsersTable (rule).

AccountsController

    public function add()
    {
        $account = $this->Accounts->newEntity();
        if ($this->request->is('post')) {
            $account = $this->Accounts->patchEntity($account, $this->request->data);
            if ($this->Accounts->save($account)) {
                $this->Flash->success('The account has been saved.');
                return $this->redirect(['action' => 'index']);  
            }else {
                $this->Flash->error('The account could not be saved. Please, try again.');
            }
       }
        $users = $this->Accounts->Users->find('list', ['limit' => 200]);
        $this->set(compact('account', 'users'));
        $this->set('_serialize', ['account']);
    }

add.ctp (accounts)

        <?= $this->Form->create($account); ?>
        <fieldset>
            <legend><?= __('Add Account') ?></legend>
            <?php
                echo $this->Form->input('user.name');
                echo $this->Form->input('user.email');
                echo $this->Form->input('password');
                echo $this->Form->input('phonenumber');
                echo $this->Form->input('address');
                echo $this->Form->input('user.postcode');
            ?>
        </fieldset>
        <?= $this->Form->button(__('Submit')) ?>
        <?= $this->Form->end() ?>
    </div>

Note: Information about what fields are in which tables are in the form so I won't go into detail about them. But accounts table will also have an id and user_id; user table will have id associated with user_id and a usertype (admin, client or public).

I've been trying to tackle this by trying to retrieve the row from the Users table using user.email but I can't access it. If I could access it, I should be able to retrieve the associated row from the Users table, get the id from the Users table and then somehow set the user_id for my Accounts record as that id. I have tried requesting the data from the form but it only works on inputs related to account model (at least I think that's how it works).

Much help would be appreciated. Please tell me if my thinking is wrong. I would greatly appreciate (not requirement) if answers to my problem were explained in layman's terms.

Edit: The users table will contain an admin, users that have a registered account to purchase services and users that just want to subscribe only. The latter will only have to provide lesser information than the registered users and hence why there is both a users table and an accounts table. The only way to log in is by using the users table (contains email) and the accounts table (contains password).

Edit 2: I basically want to do this.

AccountsController report address in case of error (primary key constraint)

 public function add()
    {
        $account = $this->Accounts->newEntity();
        if ($this->request->is('post')) {
            $account = $this->Accounts->patchEntity($account, $this->request->data);
            if ($this->Accounts->save($account)) {
                $this->Flash->success('The account has been saved.');
                return $this->redirect(['action' => 'index']);          
            }else {
                $this->Flash->error($this->request->data['address']);
            } 

        }
        $users = $this->Accounts->Users->find('list', ['limit' => 200]);
        $this->set(compact('account', 'users'));
        $this->set('_serialize', ['account']);
    }

The above works and reports the address that was typed in.

AccountsController report email in case of error (primary key constraint)

 public function add()
    {
        $account = $this->Accounts->newEntity();
        if ($this->request->is('post')) {
            $account = $this->Accounts->patchEntity($account, $this->request->data);
            if ($this->Accounts->save($account)) {
                $this->Flash->success('The account has been saved.');
                return $this->redirect(['action' => 'index']);          
            }else {
                $this->Flash->error($this->request->data['user.email']);
            } 

        }
        $users = $this->Accounts->Users->find('list', ['limit' => 200]);
        $this->set(compact('account', 'users'));
        $this->set('_serialize', ['account']);
    }

This doesn't work and gives me the error: Notice (8): Undefined index: user.email [APP/Controller\AccountsController.php, line 68]

I want to get user.email so then I can search for that row in my Users table and retrieve it's primary key (to plug into the user_id of the Account I am trying to make).

sql of the tables

 CREATE TABLE users (
          id INT AUTO_INCREMENT PRIMARY KEY,
          name VARCHAR(255),
          email VARCHAR(255),
          postcode VARCHAR(255),
          usertype VARCHAR(20) DEFAULT 'Public',
          created DATETIME,
          updated DATETIME
    );

CREATE TABLE accounts (
      id INT AUTO_INCREMENT PRIMARY KEY,
      user_id INT NOT NULL,
      password VARCHAR(255),
      phonenumber VARCHAR(10),
      address VARCHAR(255),
      created DATETIME,
      updated DATETIME,         
      FOREIGN KEY user_key (user_id) REFERENCES users(id)
);

Edit 3: I found out the way to retrieve associated data from the form (or more accurately, the patched entity $account) is by $account->user->email. I'm getting somewhere but it's a pretty dirty way to register the account for an existing user (public).

AccountsController updated

public function add()
    {

        $account = $this->Accounts->newEntity();
        if ($this->request->is(['post', 'patch', 'put'])) {
            $account = $this->Accounts->patchEntity($account, $this->request->data);

            if ($this->Accounts->save($account)) {
                $users = $this->Accounts->Users;
                $query = $users->query();
                $query->update()
                    ->set([
                        'usertype'=>'Client'
                    ])
                    ->where(['email' => $account->user->email])
                    ->execute();
                $this->Flash->success('The account has been saved.');
                return $this->redirect(['action' => 'index']);          

            }else {
                $users = $this->Accounts->Users;
                $query = $users->query();
                $usertype = $query->select('usertype')
                    ->where(['email' => $account->user->email]);

                    if(true){
                        $query->update()
                            ->set(['name'=>$account->user->name,
                                'postcode'=>$account->user->postcode,
                                'usertype'=>'Client'
                                ])
                            ->where(['email' => $account->user->email])
                            ->execute();
//everything up to this point works

                        $userid = $query->select('id')
                            ->where(['email' => $account->user->email]);

                        $accounts = $this->Accounts;
                        $query = $accounts->query();
                        $query->insert(['user_id', 'password', 'phonenumber', 'address'])
                            ->values([
                                'user_id' => $userid,
                                'password' => $this->request->data['password'],
                                'phonenumber' => $this->request->data['phonenumber'],
                                'address' => $this->request->data['address']
                            ])
                            ->execute();


                        $this->Flash->success('The account has been saved.');
                        return $this->redirect(['action' => 'index']);          
                    }
                    else{
                        $this->Flash->error('The account could not be saved.');
                    }
            } 

        }
        $users = $this->Accounts->Users->find('list', ['limit' => 200]);
        $this->set(compact('account', 'users'));
        $this->set('_serialize', ['account']);
    }

The current problem now is inputting user_id into my account row through query builders. Currently, it successfully changes the usertype for my User but afterwards I get this when I try to insert a row into my Accounts table. Error: SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s).

Additionally the sql error is this -> INSERT INTO accounts (user_id, password, phonenumber, address) VALUES ((SELECT Users.usertype AS Users__usertype, Users.id AS Users__id FROM users Users WHERE (email = :c0 AND email = :c1 AND email = :c2)), :c3, :c4, :c5)

I have no idea why it's trying to put two columns into one field. Much help appreciated. Upon writing this I realized there are 3 queries executed up to that point where there is an email condition. Seems like queries are joined.