0

I am a newbie in AngularJS, I am trying to figure out how to save record on button click.

Here is a code:

 <div ng-controller="appController">   
    <table class="table">
<thead>
  <tr>
    <th>Country</th>
    <th>Phone Number</th>
    <th>Display in country</th>

  </tr>
</thead>
<tbody>


  <tr ng-repeat="num in nums">

          <td>{{num.country}}</td>
          <td>{{num.phone}}</td>
         <td>
          <select name="display_country[]">
              <option value="US">United State of America</option>
              <option value="AU">Australia</option>
          </select>

          </td>

  </tr>
 <tr>
   <td colspan="3">
    <button type="button" class="btn btn-success">Submit</button>
   </td>
 </tr>

</tbody>

It will give output show in attachment Please see this screenshot of output

I need to save country, phone, and selected country from drop-down box into my MySQL database when user click on the button

Controller code

          var fetch = angular.module('dinapp', ['ui.select2']);

          fetch.controller('appController', ['$scope', '$http', function           ($scope, $http) {
          $scope.list_of_string = ['tag1', 'tag2']
          $scope.select2Options = {
          'multiple': true,
          'simple_tags': true,
          'tags': ['tag1', 'tag2', 'tag3', 'tag4']  // Can be empty list.
     };
getNumbers();
function getNumbers(){

    $http({
    method: 'GET',
        url: 'server/index.php?type=fetchrecord',
        data: { 'type' : 'fetchrecord' },
        //headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).then(function successCallback(response) {
    // Store response data

        $scope.nums = response.data;
    });

},
$scope.save = function () {

}   

  }]);
10
  • When clicking on the Submit button you need to send an XHR request to the backend that will have to save that data to MySQL. Use $http service of Angular 1 to send XHR request. Commented Jul 31, 2018 at 15:12
  • Well, first thing you'll need to do is write some PHP code, I expect, but I'm no expert there. If I were you, I'd do some research into this subject, perhaps searching for "php add posted data to mysql". Such a search might point you to PHP: Inserting Values from the Form into MySQL. Then you'll need to do some research into how to post to PHP from AngularJS, information on which is on their site, and in several places here, including AngularJS HTTP Post to PHP. Commented Jul 31, 2018 at 15:13
  • I'd like to suggest you take the time to skim through the AngularJS tutorial. For your question specifically, step 12 would help understand event handling and step 7 for XHR requests. Commented Jul 31, 2018 at 15:14
  • @ischenkodv, I know how to do in mysql and php but I dont know how to do in angular js, I don't know angular js coding. Commented Jul 31, 2018 at 15:15
  • @ischenkodv I have edited question and added controller code. please check my controller code, I am not sure what should be coded in $scope.save = function () { } Commented Jul 31, 2018 at 15:19

2 Answers 2

0

Use ng-model instead of name attribute to bind the value of select. Also you could use ng-options instead of option list.

    $scope.countries = [
      {code: 'AU', name: 'Australia'},
      {code: 'UA', name: 'Ukraine'}
      //...
    ];

 $scope.save = function saveRows(){
 $http({
     method: 'POST',
     data: $scope.nums,
     url: '/API/saveNums

  }).then(function(){
          console.log('SAVED')
  });

}



/// PHP

$nums = $_POST['nums'];

$sql = '...';
 <select ng-model="num.countryToShow" ng-options="country.code as country.name for country in countries"></select>
...
<button type="button" class="btn btn-success" ng-click="save()">Submit</button>

Sign up to request clarification or add additional context in comments.

Comments

0

You can save your record to db by using .service or .factory in angularjs like

Try below code may it help you

In below service i wrote 2 addToDB functions. Its your choice which one to use.

var app = angular.module('dinapp', []).config(function () { });

app.service('YourServiceName', ['$http', function ($http) {

    this.addToDB = function (PostData) {
        var promise = $http({
            method: 'POST',
            url: 'Your URL to save api',
            data: PostData

        }).success(function (data, status, header, config) {

            //You can do code here when your records save successfully

            //data – {string|Object} – The response body transformed with the transform functions.
            //status – {number} – HTTP status code of the response.
            //headers – {function([headerName])} – Header getter function.
            //config – {Object} – The configuration object that was used to generate the request.

        }).error(function (data, status, header, config) {

            //You can do code here when your got any error during saving your record

            //data – {string|Object} – The response body transformed with the transform functions.
            //status – {number} – HTTP status code of the response.
            //headers – {function([headerName])} – Header getter function.
            //config – {Object} – The configuration object that was used to generate the request.
        });

        return promise;
    };


    //OR


    this.addToDB = function (PostData) {
        var promise = $http({
            method: 'POST',
            url: 'Your URL to save api',
            data: PostData

        }).then(function onSuccess(response) {

             //You can do code here when your records save successfully

            var data = response.data;
            var status = response.status;
            var statusText = response.statusText;
            var headers = response.headers;
            var config = response.config;
          }).catch(function onError(response) {

            //You can do code here when your got any error during saving your record
            var data = response.data;
            var status = response.status;
            var statusText = response.statusText;
            var headers = response.headers;
            var config = response.config;
          });

        return promise;
    };

}]);


app.controller('appController', ['$scope', 'YourServiceName', function ($scope, YourServiceName) {

    $scope.save  = function () {

        var MyPostData = {
            country: 'YourCountry',
            phone: 'YourPhoneNo',
            selected_country: 'YourSelectedCoutry'
        }

        YourServiceName.addToDB(MyPostData).then(function () {
             //You can do code here when your records save successfully
        });
    };
}]);

A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Any response status code outside of that range is considered an error status and will result in the error callback being called.

Edit:

First of all add one filed selectedCountry to your nums array variable that can act as a ng-model for your <select> element

Here is a mock data that I entered in your nums variable like

$scope.nums = [
        {
            country: 'USA',
            phone: '12345',
            selectedCountry: 'US'
        },
        {
            country: 'India',
            phone: '123456',
            selectedCountry: 'AU'
        },
        {
            country: 'Shrilanka',
            phone: '1234567',
            selectedCountry: 'US'
        }
    ];

Then your $scope.save function in controller look like

$scope.save  = function (nums) {

        YourServiceName.addToDB(nums).then(function () {
             //You can do code here when your records save successfully
        });
    };

And your html will be like this

<table class="table">
        <thead>
          <tr>
            <th>Country</th>
            <th>Phone Number</th>
            <th>Display in country</th>
          </tr>
        </thead>
        <tbody>

          <tr ng-repeat="num in nums">
            <td>{{num.country}}</td>
            <td>{{num.phone}}</td>
            <td>
              <select name="display_country[]" ng-model="num.selectedCountry">
                <option value="US">United State of America</option>
                <option value="AU">Australia</option>
              </select>
            </td>
          </tr>

          <tr>
            <td colspan="3">
              <button ng-click="send(nums)">click to send all user data </button>
            </td>
          </tr>

        </tbody>
      </table>

Here is a jsfiddle that i created for you

In jsfiddle just change your countries from drop down and click button click to send all user data and check in console

You will see the changed countries in console. and then you will be able to pass this console data to you $scope.save function

5 Comments

main issue with me is I don't know how to capture form submitted
actually I know the coding how to send data using $http but my question is: as you can see in my grid have 3 rows when user click on the button I want to capture those data, it could be captured with push function I think?
is you have to send all 3 countries to db with single click on submit button?
Yes, exactly, send all 3 countries to db,
@Smith, view edited section in solution might be it help you

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.