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 () {

}   

  }]);
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Smith
  • 31
  • 1
  • 1
  • 6
  • 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. – ischenkodv Jul 31 '18 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](https://stackoverflow.com/q/37367992). 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](https://stackoverflow.com/q/33540195). – Heretic Monkey Jul 31 '18 at 15:13
  • I'd like to suggest you take the time to skim through the [AngularJS tutorial](https://docs.angularjs.org/tutorial). For your question specifically, [step 12](https://docs.angularjs.org/tutorial/step_12) would help understand event handling and [step 7](https://docs.angularjs.org/tutorial/step_07) for XHR requests. – alphapilgrim Jul 31 '18 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. – Smith Jul 31 '18 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 () { } – Smith Jul 31 '18 at 15:19
  • @HereticMonkey I need to know what should be coded in $scope.save = function () { } – Smith Jul 31 '18 at 15:20
  • Sure, and my point is that you can find that out with very little research, rather than asking volunteers to write the code for you. Did you happen to look at the second question I linked to? Every answer has information about what to put in that function... – Heretic Monkey Jul 31 '18 at 15:24
  • I am not asking to write code, I know little about $http request but don't know how to retrieve data from grid on the click – Smith Jul 31 '18 at 15:28
  • I have expertise on PHP and MYsql but I have just started working on AngularJs today. – Smith Jul 31 '18 at 15:29
  • Read [AngularJS ` – georgeawg Aug 01 '18 at 04:45

2 Answers2

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

er-sho
  • 9,581
  • 2
  • 13
  • 26
  • main issue with me is I don't know how to capture form submitted – Smith Aug 01 '18 at 06:37
  • 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? – Smith Aug 01 '18 at 06:39
  • is you have to send all 3 countries to db with single click on submit button? – er-sho Aug 01 '18 at 06:41
  • Yes, exactly, send all 3 countries to db, – Smith Aug 01 '18 at 06:42
  • @Smith, view edited section in solution might be it help you – er-sho Aug 01 '18 at 09:06
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>