jquery-ajax post values to http-generic-handler don't return anything - asp.net

I have a generic-http-handler and I am calling it from jQuery.
My handler only insert values in database but does not return anything.
I am calling the handler as follow
function InsertAnswerLog(url) {
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: { 'Url': url, 'LogType': "logtype" },
success: function (data) {
},
error: function (Error) {
}
});
}
Everything is working fine for me.
But is it the best way to post the values to the server.
Or can I use it in a better way.

it seems the type of data you are sending is JSON encoded try serializing the data in this form before sending and then on the server side you should encode the data before sending it back.
serializing before sending to server
function InsertAnswerLog(url) {
var DatatoSend = { 'Url': url, 'LogType': "logtype" } ;
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: {Jsondata: JSON.stringify(DatatoSend)},
success: function (data) {
},
error: function (Error) {
}
});
}
now on the sever side scipt
// NB: i use PHP not asp.net but it think it should be something like
Json.decode(Jsondata);
// do what you want to do with the data
// to send response back to page
Json.encode(Resonponse);
// then you could in php echo or equivalent in asp send out the data
It is important that you decode the json data on the server-side script and when a response is to be sent it should be encoded back it JSON form for it to be understood as a returned json data.
I hope this helps.

Related

GET operation status via API not CMD

In Google Cloud vision API documentation for the product search, the method for getting operation status is listed as CMD but there is no C# code example for it in order to check any long-running operation status.
I tried calling this method in postman but it didn't work as I cannot add the service account credentials
GET https://vision.googleapis.com/v1/locations/location-id/operations/operation-id
Would appreciate any guidance on this.
It turns out there are two solutions:
Using Google Cloud Vision REST APIKEY as a query parameter for (you will have to generate your own API key from the cloud console credentials)
GET https://vision.googleapis.com/v1/locations/location_id/operations/operation_id?key=value
Using AJAX with stringify to append the service account JSON key file with the request which is sent to the same URL above.
checkStatus: function() {
if (this.get('stop') || !this.getOperationUrl()) {
return;
}
$.ajax({
url: '/getOperation',
type: 'POST',
data: JSON.stringify({
operation_url: this.getOperationUrl(),
key: this.config_model.get('key'),
}),
cache: false,
contentType: 'application/json',
dataType: 'json',
}).done(function(response) {
const result = response.response;
if (!response.success || !result) {
console.log(response);
this.set('response', response);
} else {
if (result.done) {
this.set('response', response);
} else {
setTimeout(function() {
this.checkStatus();
}.bind(this), 5 * 1000);
}
}
}.bind(this));

Ajax not executing asynchronously

I have this piece of code
function getMesssages(id,c) {
function waitForServerCall(id,c) {
$.get(href("~/polling/" + id), function (response) {
var r = c(response);
if (r) {
return false;
}
waitForServerCall(id);
});
}
waitForServerCall(id,c);
$.post(href("~/batch/export/?batches=3344&pollid=" + id), function (response) {
c(response);
cancelCall = true;
});
}
The $.get inside the waitForServerCall method only get execute when the $.post recive the server response. Why?
This is the ajaxSettings:
accepts: Object
async: true
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
contents: Object
converters: Object
flatOptions: Object
global: true
isLocal: false
jsonp: "callback"
jsonpCallback: ()
processData: true
responseFields: Object
type: "GET"
url: "http://localhost:59161/"
xhr: In()
__proto__: Object
Update.
What i am doing is long polling, the post request is a long running process so i need to know some events that the server will trigger, the waitForServerCall method notify the client about the events that occured. But since the $.get method execute once the $.post response is recive, the notification process don't work.
Update 1:
Im using .NET 4.0 and Jquery 1.9.1.
Yes, the $.get request gets execute first but not response is recive until the $.post get the response. Once the $.post get the response, $.get execute correctly. But I'm expecting the $.get to get the server response even if the $.post has not get any response yet.
So here is the answer of why.
All the credits goes to the author of this article:
http://josefottosson.se/c-sharp-mvc-concurrent-ajax-calls-blocks-server/

How to get post data as json in asp.net?

I am making an ajax request to my API but my API expects raw json data to parse its own objects in C# how do I get the raw Json data in C#? from the "HttpContext.Current.Request"
Here is my request:
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
contentType: "Application/JSON",
data: {
code: "login",
data: {
username: $("#login_username").val(),
password: $("#login_password").val(),
rememberMe: $("#rememberMe").val()
}
},
success: function (result) {
},
error: function (result) {
console.log(result);
}
});
You should be able to get body of the request using property 'HttpRequest.InputStream`. The type of the property is a stream, but you can see an example on MSDN on how to convert it to string.
Depending of what is your underlying framework there can be easier ways to get the body. E.g. MVC of Web API use binding to map incoming requests to objects, so it might be an option to consider.

$http.post not working with JSON data

I am building an application using AngularJS and I have a login form from which I want to send JSON data as request body.
In my controller;
$scope.credentials = {userid: $scope.userid, password: $scope.password};
$scope.login = function () {
$http({
method : 'POST',
url : 'http://localhost/login.json',
data : $scope.credentials,
headers: {'Content-Type': 'application/json'}
}).success(function (data) {
// code
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
console.log($scope.status);
});
};
But when I am submitting the form POST request is not performing and I am getting a message in the console like;
0 function (name) {
"use strict";
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
}
What am I doing wrong here?
If I changed the line
headers: {'Content-Type': 'application/json'}
to
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
the POST request is making. But I don't want to send it as form values instead I want to send the request as JSON.
You should encode javascript object to corresponding mime-type data in order to post data. If you are using jQuery, try to use $.param($scope.credentials) instead of just $scope.credentials.
I think the problem is that you're POSTing to http://localhost/login.json which is not any script that is able to receive POSTrequests with form data.

AngularJS - $http post gets executed after second click

I'm trying to perform AngularJS post request via $http. My code looks like this:
$http({
url: "cgi-bin/post_event.pl",
method: "POST",
data : jsonToSend,
headers : {
'Content-Type' : "application/json",
}
}).success(function(data, status, headers, config) {
if (status === 200) {
console.log(data);
} else {
console.log(data);
}
}).error(function(data, status, headers, config) {
console.log(data);
});
While looking via Firebug I see that this part of code gets executed, but none request is triggered towards server.
Only when I click it again, request hits server and success method is being called.
Anyone knows why's that? Or maybe I'm doing something wrong here...
This code with jQuery works fine:
$.ajax({
url: "cgi-bin/post_event.pl",
type: "POST",
contentType : "application/json",
data : JSON.stringify(jsonToSend),
success : function (data) {
console.log(data);
CurrentEvent.eventname = "";
CurrentEvent.starttime = "";
CurrentEvent.eventLocation.longitude = "";
CurrentEvent.eventLocation.latitude = "";
$window.location.href = "#/host/my_events";
},
error : function (data) {
// add error to $rootScope.errors
}
});
EDIT: Ah, sorry, I should be more detailed. This is called as callback after successful ajax request. Rest of the this code is just constructing jsonToSend.
So first time this part is being called I can see in firebug it constructs $http request but I can't see it triggered on server.
Next time I click on a button that does first time ajax request success method of this one is called (but id doesn't call it via callback from ajax, but it goes directly into success method)

Resources