Issue
I am trying to make a post request code -
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.data = {};
$scope.reqCalling = function () {
let settings = {
"async": true,
"crossDomain": true,
"url": "myUrl",
"method": "POST",
"headers": {
"content-type": "application/json",
},
"data": JSON.stringify($scope.data),
}
$.ajax(settings).done(function (response) {
console.log("Success",response);
$scope.data = {};
$scope.$apply()
return false;
}).fail(function (error) {
console.log("Failed",error);
// location.reload();
});
}
});
Code of input one field
<input type="email" class="form-control" maxlength="255" placeholder="Email..." ng-model="data.email" name="email">
I have created five fields just like above (firstname, lastname, email, phone, response) these are my input fields.
While making a request I am getting 502 status code.
When I made request from Postman it worked fine... My api is accepting JSON. from postman I passed the body as json
body passed from Postman-
{
"firstname" : "firstname",
"lastname" : "lastname",
"phone" : "0000000000",
"email" : "abc@pqr.com",
"response" : "Testing"
}
I am new to AngularJs Ajax and JQuery I must have did some mistake in the code, Please help me with this.
Solution
I'm not sure about the 502 error, but on the off chance that this advice helps, why use jQuery with angular? Kind of defeats the purpose. They can be used together but there isn't really a point. They do things in completely different ways and angular has a solution for everything you might want JQ to do, like ajax calls for instance. Here is your same code, angularized (including injection protection if you ever decide to minimize your script)
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', '$http', function($scope, $http) {
$scope.data = {};
$scope.reqCalling = function() {
let settings = {
"url": "myUrl",
"method": "post",
"headers": {
"content-type": "application/json",
},
"data": $scope.data // you don't have to stringify the post vars
}
$http(settings).then(
// success!
function(response) {
// success data: response.data
},
// error
function(response) {
if (!angular.isObject(response.data) ||
!response.data.message) {
// error: unknown error
} else {
// error : response.data.message
}
}
)
}
}]);
Answered By - Kinglish
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.