0

i just programming an contact form with angular js and php.

Its working but i need your help for one feature.

you will find a runable version on plunker: https://plnkr.co/edit/4zeDV3sCVXIbVShGkVFe?p=preview

I implemented a toggle button with angular js. Its still working fine, but i want to close it when i get "success = true" back from the php script, not when i click on it. Thus it close automatically when the message was send successful. I tried it with ng-click and a function, but i don't know how to trigger the angular function with another value.

Controller.js

app.controller('ToggleCtrl', function ($scope) {
  $scope.sichtbar = false;
  $scope.toggle = function() {
    $scope.sichtbar = !$scope.sichtbar;
  };
}); app.controller('ContactController', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.resultMessage1;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
    $scope.submitted = true;
    $scope.submitButtonDisabled = true;
    if (contactform.$valid) {
        $http({
            method  : 'POST',
            url     : 'contact-form.php',
            data    : $.param($scope.formData),  //param method from jQuery
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  //set the headers so angular passing info as form data (not request payload)
        }).success(function(data){
            console.log(data);
            if (data.success) { //success comes from the return json object
                $scope.submitButtonDisabled = true;
                $scope.resultMessage = data.message;

                $scope.result='bg-success';
            } else {
                $scope.submitButtonDisabled = false;
                $scope.resultMessage = data.message;
                $scope.resultMessage1 = data.message;
                $scope.errorName = data.errors.name;
                $scope.result='bg-danger';
            }
        });
    } else {
        $scope.submitButtonDisabled = false;
        $scope.resultMessage = 'Bitte alles ausfuellen (rot makiert)';
        $scope.result='bg-danger';
    }
}`

Index.html

<div ng-controller="ToggleCtrl">
    <button class="btn btn-primary btn-sm" ng-click="toggle()">Want to contact us directly????</button>
    <div ng-show="sichtbar"><div class="container" ng-controller="ContactController">
    <div class="col-md-6 col-md-offset-3">
        <form ng-submit="submit(contactform)" name="contactform" method="post" action="" role="form">
            <div class="form-group" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
                <label for="inputName" >Name</label>
                    <input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="Your Name" required>
            </div><div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
                <label for="inputEmail" >Email</label>
                <input ng-model="formData.inputEmail" autocomplete="on" type="email" class="form-control" id="inputEmail" autofocus name="inputEmail" placeholder="Your Email" required>
            </div>
            <div class="form-group" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
                <label for="inputSubject" >Subject</label>
                    <input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
            </div>
            <div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
                <label for="inputMessage" >Message</label>
                    <textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
            </div>
            <button type="submit" class="btn btn-success btn-lg btn-block" ng-disabled="submitButtonDisabled">
                Send Message?
            </button>
        </form>

contact-form.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'phpmailer/PHPMailerAutoload.php';

    //check if any of the inputs are empty
    if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
        $data = array('success' => false, 'message' => 'Bitte alles ausfuellen');
        echo json_encode($data);
        exit;
    }

    //create an instance of PHPMailer
    $mail = new PHPMailer();


    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPAuth = true; // au<a href="contact-form.php">No Title</a>thentication enabled
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 465; // or 587
    $mail->IsHTML(true);


    $mail->From = $_POST['inputEmail'];
    //$mail->FromName = $_POST['inputName'];
    $$mail->Subject = $_POST['inputSubject'];
    $mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);

    if (isset($_POST['ref'])) {
        $mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
    }

    if(!$mail->send()) {
        $data = array('success' => false, 'message' => 'Fehler: Mailer Error: ' . $mail->ErrorInfo);
        echo json_encode($data);
        exit;
    }
    $data = array('success' => true, 'message' => 'Thanks ');
    echo json_encode($data);

Any ideas? Thank you very much.

2
  • You can use [ng-hide/ng-show] or [ng-if] to conditionally show/hide a DOM element. You can set a flag variable to true once you get a success response and use ng-hide to hide the form when the flag is set to true. Commented Feb 1, 2016 at 15:02
  • never used any flag variable. sorry iam not get in. Its my understanding about trigger. I want to set the toggleCrtl true in the if clause (data.sucess) Commented Feb 1, 2016 at 16:10

2 Answers 2

0

Thanks for your help, i fixed it: i added the code below to trigger the button automatically.

$timeout(function() {
    var el = document.getElementById('btn123');
    angular.element(el).triggerHandler('click');
}, 0);
Sign up to request clarification or add additional context in comments.

Comments

0

A couple things:

  1. Your html is invalid, it's missing two closing </div> tags.
  2. You need to handle the http error (for example, in the plunkr the request fails to go through so you need an "error" callback).
  3. To close the form on success, simply put $scope.toggle(); in your success callback. You can do this because the ContactController inherits from the ToggleController, so the toggle function will be available in both controllers.

2 Comments

sorry i copied it to fast on plunker. Problem is, that i want to trigger the click task in the controller in the if clause (data.sucess) true. So i have to trigger there the other controller which toggle the button, that is my main problem i tried with: angular.element('#btn123').trigger('click'); ob something like that
You don't need to use the dom at all. Because scopes are inherited, you can just call $scope.toggle(); in the second controller, since it's within the scope of the first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.