AngularJS: HTTP request is not responding after page is fully loaded - javascript

I have an invoice page all values are based on AngularJS ng-models (variables) so they are dynamic.
When I change text field DISCOUNT, all values change according to discount value (also call function abc repeatedly). This was working fine.
But now I have created a new function loadadditionalvalues inside function abc and request an HTTP call. First time this function work properly. However, when I type something in discount field, it requests, but never responds and gets hanged at my new function loadadditionalvalues.
function abc(){
$scope.loadadditionalvalues = function (n,o,scope)
{
arr=[];
$scope.isAppInitialized = false;
var requestUrl = 'page_test.php?do=action_netvalues&action=ID' ;
$http({
url: requestUrl,
method: 'GET'
}).then(function(response){
if(typeof response.data.ERROR_MSG !== 'undefined' || typeof response.data !== 'object' || typeof response.data.message !== 'undefined' || (typeof response.data.success !== 'undefined' && !response.data.success))
{
console.log("error ");
}
else
{
$scope.staffel_liste =response["data"];
}
});
};
$scope.loadadditionalvalues(null,null,scope);
}

Related

Two ajax calls and only one is running

I have the following http variable which returns an object:
var http = (function(){
var success = null;
var error = null;
var requestInfo = {content: '', status: 0};
var core = {
request: function(options){
var $http = Object.create(http);
sendRequest(options).then(function(){
if(typeof(success) == 'function'){
success(requestInfo.content);
}
}, function(){
if(typeof(error) == 'function'){
error(requestInfo.content);
}
});
return $http;
},
success: function(callback){
success = callback;
return this;
},
error: function(callback){
error = callback;
return this;
}
};
function sendRequest(options){
return new Promise(function(resolve, reject){
var xhttp = new XMLHttpRequest();
var method = options.method.toUpperCase();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4){
requestInfo.content = JSON.parse(xhttp.responseText) || xhttp.responseText;
requestInfo.status = xhttp.status;
}
if (xhttp.readyState == 4 && xhttp.status == 200) {
resolve(requestInfo);
}else if(xhttp.readyState == 4 && xhttp.status != 200){
reject(requestInfo);
}else if(xhttp.status >= 400){
reject(requestInfo);
}
};
xhttp.open((method || 'GET'), options.url, true);
var data = options.data || '';
xhttp.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').getAttribute('content'));
if((typeof(data) == 'object' && (Object.keys(data).length > 0) || data.length > 0)){
xhttp.send(JSON.stringify(data));
}else{
xhttp.send();
}
});
}
return core;
})();
If I call it more than once simultaneously, like so:
http.request({url: '/path1'}).success(function(){
alert('success');
});
http.request({url: '/path2'}).success(function(){
alert('success');
});
only one of the items gets passed via ajax the other one does not. What is causing this? I thought that doing Object.create(this) would make each one unique from each other but it doesn't seem to be doing that...
The Object.create() method creates a new object with the specified prototype object and properties.
So you're creating 2 objects with the same prototype, and the data is in the prototype itself. Since the prototype is an object, and it is the same, both resulting objects have the same references for their data objects and functions.
You need to specify the data not in the prototype object, but for each instance instead.
So after you create var $this = Object.create(this);, you must add the data to $this, such as successFunc, otherwise the next call will override this data.
The sucessand error variable used to store your callback functions must be created within your request function to be truly unique per request. However, if you're going to use Promises, I'd suggest simplifying the whole deal using load and error event listeners available to the XMLHttpRequest object (a nice example can be found on MDN's XMLHttpRequest article) and simply passing in your success and failure functions the then method of your Promise instance.
Here's a simplified JSFiddle example using a timeout to simulate a 500 millisecond HTTP request.
The issue was with this line:
var method = options.method.toUpperCase();
I was not setting the method property in the options and it wasn't erroring saying that it couldn't send, it basically just exited the method without warning...
I changed it to this:
var method = (options.method || 'GET').toUpperCase();
and it started to work.

Why HttpRequest callbacks not working without alert

I have a issue in getting response in Kony application. this is the code
function getServerResponceOption(url){
alert(url);
var httpclient2 = new kony.net.HttpRequest();
var requestMethod = constants.HTTP_METHOD_GET;
var async = true;
httpclient2.open(requestMethod, url,async);
if(getAccessToken() != null && getAccessToken() != ""){
httpclient2.setRequestHeader("AuthToken",getAccessToken());
}
httpclient2.send();
httpclient2.onReadyStateChange = HandleResponce(httpclient2);
}
function HandleResponce(obj)
{
alert("Getting data "+obj.readyState+" Status "+obj.status+" Response "+obj.response );
if(obj.readyState == 4 )
{
if (obj.response != null && obj.response != "")
{
var jsonObj = obj.response;
handleResponseOption(0,jsonObj);
return;
}
else
{
}
}else{
var state = obj.status;
alert("Readystate "+obj.readyState+" Status = "+state);
}
if (obj.response != null && obj.response != "")
{
var jsonObj = obj.response;
handleResponseOption(1,jsonObj);
}
}
Here i got server response if i put the alert message in HandleResponce(obj) without the alert i didn't get any response. the ready state is 1 and status is 0. What is the problem occurred if i remove the alert message?
Note: URL and getAccessToken() is getting values.
You are calling function in line, When you use HandleResponce(httpclient2) function is immediately executed.
httpclient2.onReadyStateChange = HandleResponce(httpclient2);
Change your code as
httpclient2.onReadyStateChange = function(){ HandleResponce(httpclient2) };

jquery check json data

I am using the google news search api and get back data in json format. I am using ajax to get the data and parse through it.
This is my code:
function doAjax(query){
alert(query);
var target = "https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q="+query+"&rsz=large";
$.ajax({
url: target,
cache: false,
dataType:'jsonp',
success: function(data) {
//alert(data.responseData.results);
for(var x = 0; x < 8; x++){
var title = data.responseData.results[x].titleNoFormatting;
//var content = data.responseData.results[x].content;
//var image = data.responseData.results[x].image.url;
$("#home").append(x+"---"+title+'<hr>');
}
},
error: function(jxhr,e){
alert(jxhr.status+" --- "+e.responseText);
}
});
}
When I run the code this way I get 8 titles. but when I uncomment this line var image = data.responseData.results[x].image.url; I get 3 or 4 results only. I investigated the data being retrieved from google I found that some results has no images. How can I check the json result if it has an image. I still want to display the title of the article even if there was no image.
you should check the image exists before get it's url
if(typeof(data.responseData.results[x].image) == "undefined"){
alert('no image');
}else{
var image = data.responseData.results[x].image.url;
}
What does the response look like? Most browsers have developer tools that will let you see the requests and response. Likely, your loop is choking because data.responseData.results[x].image is undefined so data.responseData.result[x].image.url throws a type error (undefined doesn't have a url property).
To guard against this, just check for it like this:
if(data.responseData.result[x].image) {
var image = data.responseData.result[x].image.url;
}
If data.responseData.result[x].image is undefined then it will evaluate as falsey and the body of the if won't be executed (and won't throw an error that breaks you out of the function).
You can check for image like
if (typeof data.responseData.image != 'undefined' && typeof data.responseData.image.url != 'undefined' ) {
// set the image here
}
Typeof can be used to determine if a variable is defined or not.
Example
var var_one = "";
alert(typeof var_one); // alerts "string"
alert(typeof var_two); // alerts "undefined"
alert(typeof var_two == "undefined"); // alerts "true"
So you can specify:
if (typeof var_two != "undefined")
{
alert("variable is undefined!");
}
else
{
alert("variable is defined... use it!");
}
Taking the above into account, you could do:
var image = "";
if (typeof data.responseData.results[x].image.url != "undefined")
{
image = data.responseData.results[x].image.url;
// You can then specify where the image url will go.
}

Javascript global variable not being set from ajax call [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return Value from inside of $.ajax() function
I'm working on a CakePHP app that makes use of widespread AJAX calls to controllers. I'm stuck with one particular AJAX call in which I'm trying to assign the response from the controller to a JS global variable. Here is the code:
window.errors = "";
function setErrors(err) {
window.errors = err;
}
function ajaxCall(u, t, d, dt) {
var type = typeof t !== 'undefined' ? t : "post";
var dataType = typeof dt !== 'undefined' ? dt : "json";
var success = false;
var err = "";
$.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
success: function(d){
if(d.hasOwnProperty('success') === false) { //json response
for(var i in d) { //fetch validation errors from object
for(var j in i) {
if(typeof d[i][j] === "undefined") {
continue;
}
err += d[i][j] + "<br/>";
}
}
console.log(err); //<=== displays correct value
setErrors(err); //<=== but somehow this seems to be failing??
}
else {
if(d.success === "1") {
success = true;
}
}
}
});
return success; //<=== I suspect this might be the culprit
}
And this is how ajaxCall() is used:
function register() {
var data = {};
var $inputs = $("#regForm :input");
$inputs.each(function(){
data[this.name] = $(this).val();
});
data = {"User" : data }; //CakePHP compatible object
data = JSON.stringify(data);
//Here's the AJAX call
if(ajaxCall('https://localhost/users/add', 'post', data, 'json')) {
alert("Registered!");
}
else {
alert(window.errors); // <=== empty string
console.log("window.errors is: " + window.errors); // <=== empty string
}
}
But on the Chrome JS console, window.errors returns the correct value (non-empty, validation error string).
I found a similar question that possibly might be addressing my issue (the return success immediately following the $.ajax() is being executed before the success: callback). How can I fix this without drastically changing the code (also, I don't want to make this a synchronous call)?
Yes, you are right that the return statement runs before the success callback. You can't return the result from the function, as the function has to return before the success event can be handled.
Add a callback to the ajaxCall function, and call that instead of setting the success variable:
function ajaxCall(u, t, d, dt, callback) {
var type = typeof t !== 'undefined' ? t : "post";
var dataType = typeof dt !== 'undefined' ? dt : "json";
$.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
success: function(d){
if(d.hasOwnProperty('success') === false) { //json response
for(var i in d) { //fetch validation errors from object
for(var j in i) {
if(typeof d[i][j] === "undefined") {
continue;
}
err += d[i][j] + "<br/>";
}
}
callback(false, err);
} else {
callback(d.success === "1", "");
}
}
});
}
Send the code for handling the result into the ajaxCall function:
ajaxCall('https://localhost/users/add', 'post', data, 'json', function(success, err){
if (success) {
alert("Registered!");
} else {
alert(err);
}
});

jQuery and Ajax request data issue

I have a problem with this code:
setInterval(function() {
var timed = $("#chMsgCont").find(".chatMsg:last-child");
var timee = timed.attr("data");
$.ajax({
url: "./ajax/checknew.php",
data: {timestamp: timee},
success: function(data) {
$("#chMsgCont").append(data);
if(data != null) {
var div = $('#chMsgCont');
var o = div.offset().top;
div.scrollTop( o + 12302012 );
}
}
});
},1000);
Even if data is null, $("#chMsgCont) scrolls down, why?
Try it this way:
if(data)
Or this way:
if(data != null && data != "")
Basically, if(data) is considered as data is false in these cases:
data is "" or '' => empty string
data is false
data is null
data is undefined
data is just empty and not null (undefined) so it will pass, try returning something extra in your PHP file.
I prefer doing the following at PHP side:
/* suppose that i am evaluating an insert to my DB */
print(1); //if success
print(0); //if error
then at javascript side, do this:
if(data == 1) //means success
or just do the following if you are not evaluating something at PHP side:
if(data != null && data != '')

Categories

Resources