AngularJS - $http post gets executed after second click - http

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)

Related

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/

calling function containing `$http.get()` on button press

calling function containing $http.get()
$scope.storeDb = function() {
$scope.url = '/some';
$http({method: 'GET', url: $scope.url}).
success(function(data, status, headers, config) {
console.log(data);
alert(status);
}).
error(function(data, status, headers, config) {
alert('error is ' + status);
});
}
I'm calling function from ng-click
<input type="submit", value='ask', ng-click='storeDb()'/>
The alert message is error is 0
as much as i believe that jkschneider is right and it seems you do have an error and debugging it should help you find the problem, may i point 2 mistakes please :)
1st is the misuse of th $http.get, it should look like this
$http({
method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
can be also like $http.get().success().error();
see here http://docs.angularjs.org/api/ng.$http
second of all you should use the MVVM/MVC way to get/update data in your app (i.e. you need to have a model), otherwise you might get into some other problems. i wrote a short tutorial about it with full code examples http://bresleveloper.blogspot.co.il/2013/08/breslevelopers-angularjs-tutorial.html
Add another function to the then handler to handle the error condition, and debug into or log the output.

$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.

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

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.

XHR statusText not being set

What would cause the XHR to get overriden? I'm assuming that's what's happening here.
I am setting the status and code, show here, with a helper class:
if (program.Name == programName)
{
ServiceHelper.SetHttpError(501, "'Program Name' Already Exists.'");
return;
}
class:
public static void SetHttpError(int statusCode, string message)
{
HttpContext.Current.Response.StatusCode = statusCode;
HttpContext.Current.Response.StatusDescription = message;
}
handling the xhr:
function CallService(method, jsonParameters, successCallback, errorCallback)
{
if (errorCallback == undefined)
{
errorCallback = function(xhr) {
if (xhr.status == 501) {
alert(xhr.statusText);
}
else {
alert("Unexpected Error");
}
}
}
$.ajax({
type: "POST",
url: method,
data: jsonParameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successCallback,
error: errorCallback
});
}
At one time this was working.. now all that the alert shows is "error" not the message I'm providing..
Any idea?
What version of jQuery are you using? The latest docs say that the signature of the error callback is:
error(jqXHR, textStatus, errorThrown)
Your message might be in the textStatus argument.
Have you tried using FireBug to break on the error function and look at the properties of the xhr object?
I came just accross a similar issue where this statusText was not set, but only when using HTTPS on IIS, whereas it would work on on plain HTTP. I eventually found that IIS only supports HTTP2 on TLS, and in HTTP2 there is no status code description anymore.
When I used Fiddler to troubleshoot, it worked in both http and https, probably because of this !
In ASP.NET MVC you just can't use HttpStatusCode(code,description) anymore because the description will go nowhere. You have to pass the description e.g. into the response body instead. Or disable HTTP2 for the time being.

Resources