I cannot send data from Angular to Django using $http - ajax

I'm trying to set up a form which add a new object to db but first I want to check something and set up the server side for new record, but I'm frozen :(
Here is my code, please give it a try:
ctrl
subtitlesApp.controller('AddSubtitleController',
function($scope, addSubtitle) {
$scope.saveSubtitle = function(subtitle, addSubtitleForm) {
if (addSubtitleForm.$valid) {
var x = addSubtitle.getTitle(subtitle.imdb_id);
}
};
});
service
subtitlesApp.factory('addSubtitle', ['$http', function ($http) {
return {
getTitle: function(imdb_id) {
$http({
method: 'POST',
url:'add_subtitle/',
data: imdb_id,
})
.success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log(imdb_id+'eror')
});
}
}
}]);
And here's what I'm getting when I print request.POST:
<QueryDict: {}>

You should let the service return a promise
subtitlesApp.factory('addSubtitle', ['$http', function ($http) {
return {
getTitle: function(imdb_id) {
var promise = $http({
method: 'POST',
url:'add_subtitle/',
data: imdb_id,
})
.success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log(imdb_id+'eror')
});
return promise;
}
}
}]);
When consume the service
var x;
if (addSubtitleForm.$valid) {
addSubtitle.getTitle(subtitle.imdb_id).then(function(data){
x = data;
});
}

Related

OnDelete Handler always trigger a bad request

Trying to be more consistent with HTTP verbs, I'm trying to call a delete Handler on a Razor Page via AJAX;
Here's my AJAX code, followed by the C# code on my page :
return new Promise(function (resolve: any, reject: any) {
let ajaxConfig: JQuery.UrlAjaxSettings =
{
type: "DELETE",
url: url,
data: JSON.stringify(myData),
dataType: "json",
contentType: "application/json",
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
});
my handler on my cshtml page :
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
which never reaches ... getting a bad request instead !
When I switch to a 'GET' - both the type of the ajax request and the name of my handler function ( OnGetSupprimerEntite ) - it does work like a charm.
Any ideas ? Thanks !
Short answer: The 400 bad request indicates the request doesn't fulfill the server side's needs.
Firstly, your server is expecting a form by;
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
However, you're sending the payload in application/json format.
Secondly, when you sending a form data, don't forget to add a csrf token:
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
<script>
function deleteSupprimerEntite(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: myData ,
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
__RequestVerificationToken: "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
};
deleteSupprimerEntite(myData);
});
</script>
A Working Demo:
Finally, in case you want to send in json format, you could change the server side Handler to:
public class MyModel {
public int idEntite {get;set;}
public string infoCmpl{get;set;}
}
public IActionResult OnDeleteSupprimerEntite([FromBody]MyModel xmodel)
{
return new JsonResult(xmodel);
}
And the js code should be :
function deleteSupprimerEntiteInJson(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: JSON.stringify(myData) ,
contentType:"application/json",
headers:{
"RequestVerificationToken": "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
},
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
};
deleteSupprimerEntiteInJson(myData);
});

how to send serialized form to webapi Method

im trying to send my from with ajax( $.post ) to a webApi . ajax request run succesfull but when i send data to method in web api form collection get null then my method return "false"
please help me
My WebApi Method
[System.Web.Http.HttpPost]
public string AddRecord([FromBody]FormCollection form)
{
try
{
PersonBLL personbll = new PersonBLL();
var person = new tbl_persons();
person.firstname = form["txt_namePartial"];
person.lastname = form["txt_lastnamePartial"];
person.age = byte.Parse(form["txt_agePartial"]);
var result = personbll.AddRecord(person);
return result;
}
catch (Exception)
{
return "false";
}
}
my Ajax function
function AddRecordWithFormCollection(url, callback) {
$.post("/api/Person/AddRecord",JSON.stringify(url) , function (data, status) {
if (status == "success") {
hidePreloader();
unloadDiv("div_operation");
BindTable();
//AddRowTable(data, obj.name, obj.lastname, obj.age);
return callback(data);
} else {
alert("Error in Method [AddRecord]");
hidePreloader();
}
});
}
I often use that :
var form = $("#body").find("form").serialize();
$.ajax({
type: 'POST'
url: "/api/Person/AddRecord",
data: form,
dataType: 'json',
success: function (data) {
// Do something
},
error: function (data) {
// Do something
}
});
Get a try because I never used the FormCollection object type but just a model class.
This should be:
url=$("#form").serialize();
function AddRecordWithFormCollection(url, callback) {
$.post("/api/Person/AddRecord",url , function (data, status) {
if (status == "success") {
hidePreloader();
unloadDiv("div_operation");
BindTable();
//AddRowTable(data, obj.name, obj.lastname, obj.age);
return callback(data);
} else {
alert("Error in Method [AddRecord]");
hidePreloader();
}
});
}

Parse.Com - HTTP method in cloud code, how do I wait for the response

In my parse cloud code, the HttpRequest in beforeSave is getting executed successfully but the code blows through before I have had time to parse the response and determine whether I want to return a response.success() or a response.error().
I know I am missing something here, any input, ideas from the community here would be appreciated. Thanks
Parse.Cloud.beforeSave(Parse.User, function (request, response) {
   var user = request.object;
    var key = user.get("recaptcha"); 
Parse.Cloud.httpRequest({
url: 'https://www.google.com/recaptcha/api/siteverify?secret=<ITS A SECRET>&response=' + key,
success: function (httpResponse) {
var status = JSON.parse(httpResponse.text).success;
console.log(status);
if (status === false) {
response.error();
} else {
response.success();
}
}
});
});
I got it working...Parse.Cloud.httpRequest() is asynchronous, here is the solution that worked for me, hope it helps someone else.
Parse.Cloud.beforeSave(Parse.User, function (request, response) {
var user = request.object;
var key = user.get("recaptcha");
if (!request.object.existed()) {
return Parse.Cloud.httpRequest({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: 'https://www.google.com/recaptcha/api/siteverify?secret=<ITS A SECRET>&response=' + key,
body: request,
success: function(httpResponse) {
var status = JSON.parse(httpResponse.text).success;
if (status === false) {
response.error();
} else {
response.success();
}
},
error: function(httpResponse) {
response.error(httpResponse);
}
});
}
});

How to work with $resource in angularjs

I am trying to get data form this url http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo
through $resource below is my resource code
angular.module('myApp.services', ['ngResource']).
value('version', '0.1').factory('recipes1',['$resource', '$http', '$log', function ($resource, $http, $log) {
return $resource('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo',{ },{ locate: {method: 'GET', isArray: true, transformResponse: $http.defaults.transformResponse.concat(function(data, headersGetter) {
// probably be better if you examined the results in here
alert(data);
})}
});
}]);
but i am not getting response. i am getting out put from my controller as
function Resource(value){
"use strict";
copy(value || {}, this);
}
Use $http with promise factory:
See working Demo in fiddle
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function ($scope, Data) {
$scope.runMe = function () {
Data.query($scope.url)
.then(function (result) {
$scope.data = result;
}, function (result) {
alert("Error: No data returned");
});
}
});
fessmodule.$inject = ['$scope', 'Data'];
fessmodule.factory('Data', ['$http','$q', function($http, $q) {
var data = $http({method: 'GET', url: 'http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'});
var factory = {
query: function (address) {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);

Angular get request within rails app not working

I'm trying to make (my first) angular get request within a rails app to one of my routes. I'm not sure why this is returning nothing, not even an error.
function accomplishmentController($scope, $http) {
$scope.$apply(function() {
$http({method: 'GET', url: '/api/users'}).
success(function(data, status, headers, config) {
console.log("hell0");
}).
error(function(data, status, headers, config) {
console.log("error");
});
});
$scope.accomplishments = [];
$scope.submit = function() {
$scope.accomplishments.unshift({ name: $scope.newAccomp, count: 0 });
$scope.newAccomp = '';
}
$scope.addToCount = function() {
var currentcount = this.accomp.count;
this.accomp.count = currentcount + 1;
}
$scope.delete = function() {
index = this.$index;
$scope.accomplishments.splice(index, 1)
}
}

Resources