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 ?