Search code examples
jqueryangularjsjsonajaxangular-ngmodel

How to post the JSON to the given input location using angularjs?


I have the following json:

var jsondata = {
"id": 1,
"name": "Test Name",
"price": 100,
"city": "XYZ"
};

I would like to post/send this json data to some url location(I have different URL locations, i.e. whatever the url location I enter in the input field, then to that url location I need to post/send this json data) on clicking of Send button. I have tried the following, but I am unable to send to the given entered url.

var app = angular.module('myApp', []);
app.controller('TestCtrl',function($scope, $http) {
$scope.sendToLocation = function(){
var jsondata = {
"id": 1,
"name": "Test Name",
"price": 100,
"city": "XYZ"
};

 $.ajax({
 type: 'POST',
 contentType: 'application/json; charset=utf-8',
 dataType: 'json',
 url: 'My URL HERE',
 data: JSON.stringify(jsondata),
 success: function(data) {
 alert("yes, you have posted the data !");
 }
 });
 //alert(JSON.stringify(jsondata));//gives the above json
 };

});
<script src="https://code.angularjs.org/1.5.8/angular.js"></script>

<div ng-controller="TestCtrl">  
<br>
<input type="url" maxlength="50" size="50" ng-model="sendToLocation.url"><br><br>
 <button id="sendbutton" type="button" ng-click="sendToLocation()" >Send</button>  
</div>

Created Fiddle.

Please let me know what I am doing wrong and how to send the json. Thanks in advance !


Solution

  • You just need to use the angular $http service: https://docs.angularjs.org/api/ng/service/$http

    You have already injected it into the controller i.e. "function ($scope, $http)"

    Here's the code relating to your fiddle.

    var app = angular.module('myApp', []);
    app.controller('TestCtrl', function($scope, $http) {
      $scope.sendToLocation = function() {
        var jsondata = {
          "id": 1,
          "name": "Test Name",
          "price": 100,
          "city": "XYZ"
        };
    
        $http.post($scope.sendToLocation.url, jsondata, {}).then(
          function(response) {
            alert("yes, you have posted the data !");
          },
          function(error) {
    
          });
        //alert(JSON.stringify(jsondata));//gives the above json
      };
    
    });
    <script src="https://code.angularjs.org/1.5.8/angular.js"></script>
    
    <div ng-controller="TestCtrl">
      <br>
      <input type="url" maxlength="50" size="50" ng-model="sendToLocation.url">
      <br>
      <br>
      <button id="sendbutton" type="button" ng-click="sendToLocation()">Send</button>
    </div>

    And here's a fiddle: https://jsfiddle.net/ltfleming/tu2829ef/10/