I have a program written in angularjs. I'm receiving json data from server when online. I'm developing offline mode now..
I have the problem here but i dont know why i cant fix.
I saved json info to localStorage when program to offline get this json string.
service.js - For webservicecall
webServiceCallPost: function(data, action) {
console.log("data "+JSON.stringify(data));
console.log("action "+JSON.stringify(action));
var deferred = $q.defer();
if (navigator.connection.type != "none") {
return $.ajax({
type: "POST",
url: appConst.serviceUrl.service + action,
crossDomain: true,
dataType: "json",
data: data,
timeout: 2000000,
async: true,
success: function(response) {
localStorage.setItem(data + action, JSON.stringify(response));
deferred.resolve();
},
error: function(xhr, ajaxOptions, thrownError) {
$ionicLoading.hide();
if (xhr.status == 0) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else if (xhr.status == 404) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
}
},
beforeSend: function() {},
complete: function() {}
});
} else {
window.plugins.toast.showShortBottom($translate.instant("checkNetWorkConnection"));
$ionicLoading.hide();
var response1 = JSON.parse(JSON.stringify(localStorage.getItem(data + action)));
return $http.get('').then(function(response) {
return response1;
});
}
}
Controller.js - Retriveing response.
Services.webServiceCallPost('', appConst.services.get_menu_card).then(function(response) {
$ionicLoading.hide();
console.log("Response: " + JSON.stringify(response));
if (response[1].response.status == 1) {
if (response[0].data.menu.length > 0) {
var categoryResponse = [];
angular.forEach(response[0].data.menu, function(value, key) {
if (value.menu_image_name != '') {
var extraData = {
imageUrl: appConst.serviceUrl.menu_image_url + value.menu_image_name
}
}
else {
var extraData = {
imageUrl: 'img/screen.png'
};
}
angular.extend(value, extraData);
categoryResponse.push(value);
});
$rootScope.categories = globalMethods.getDashboardGridView(categoryResponse, 2);
}
if (response[0].data.addons.length > 0) {
$rootScope.totalAddons = [];
angular.forEach(response[0].data.addons, function(value, key) {
var extraData = {
"finalCost": value.price,
"quantity": 1,
imageUrl: appConst.serviceUrl.addon_image_url + value.addon_image
};
angular.extend(value, extraData);
$rootScope.totalAddons.push(value);
});
}
$scope.getSiteSettings();
}
$rootScope.dashboardHistoryId = $ionicHistory.currentHistoryId();
});
Console Output :
When i check from json pretty print its looking same.
Online Response : https://codepaste.net/op0boq
Cached Response : https://codepaste.net/y3bkd6
Problem:
TypeError: Cannot read property 'status' of undefined
When i want to get response1.response.status ok is getting.
But when i'm offline and i get cachedResponse1.response.status its retriving status is undefined. But exactly same data, why ?
if this code
var cachedResponse = JSON.parse(JSON.stringify(localStorage.getItem('' + appConst.services.get_menu_card)));
uses an asynchronous call
console.log("Cached Response: " + cachedResponse);
won't wait for it to finish and would print undefined
Thanks for answer to #PatrickEvans
Then you might have not returned the right thing... but also you shouldn't be doing JSON.parse(JSON.stringify(localStorage.getItem()) it should just be JSON.parse(localStorage.getItem()) localStorage items are already strings, stringifying it is going to mess up what you are trying to do
and
return $q.when(response1);
Related
I have a ajax post that I need to redirect to redirect url on success.
In the browser debugger I do c the correct url but I'm always getting "MYURL/undefined".
$.ajax({
type: 'POST',
url: "/NewsLetter/Create",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function(result) { //debug >result={urlOne:'https://localhost:7077'}
// alert('Successfully received Data ');
if (result.UrlOne !== undefined) {
window.location.replace(result.UrlOne);
} else {
window.location.replace(result.UrlTwo);
}
console.log(result);
},
error: function(error) {
alert('Failed to receive the Data');
console.log(JSON.stringify(error));
console.log('Failed ');
}
});
In my controller:
if (ModelState.IsValid && isNewUser == null)
{
//remove for clear code
return Json(new { UrlOne = Url.ActionLink("Index","Home")});
}
TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") });
Pass the JsonSerializerOptions as a parameter when creating the Json object to make property's name case-sensitive during deserialization. The JsonSerializerOptions has PropertyNameCaseInsensitive property that by default set to false. This will prevent the Json serializer to change names to be camel-cased.
var options = new System.Text.Json.JsonSerializerOptions();
if (ModelState.IsValid && isNewUser == null)
{
//remove for clear code
return Json(new { UrlOne = Url.ActionLink("Index","Home")}, options);
}
TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") }, options);
JsonSerializerOptions Class
Please check the return json from controller:
You will find that the key is urlOne instead of UrlOne.
Javascript is case sensitive, So you need to change your code like:
if (result.urlOne !== undefined) {
window.location.replace(result.urlOne);
} else {
window.location.replace(result.urlTwo);
}
We are trying to migrate from pure ext.js to a model that uses ext.js in the controller, but front end is pure html, bootstrap.
As we migrate, I am trying to make a ajax on a login request. I have a ajax call which is returning a empty requestPayload.
loginSubmit : function(param){
var me = this,
params = {
url: 'login/login',
method: "POST",
jsonData: Ext.JSON.encode(param.formValues) ,
success: function (response) {
var data = Ext.JSON.decode(response.responseText);
Insights.view.common.util.StorageUtil.setAppData(response.responseText);
me.getView().destroy();
Ext.create({
xtype: 'mainviewport'
});
},
failure: function (response) {
var errorMessage = "Network connect timeout error"
if (response.status == 401 || response.status == 500) {
var data = Ext.JSON.decode(response.responseText);
errorMessage = data.message;
}
if(param.loginButton){
var errMsg = form.queryById('login-error-msg');
errMsg.setText(errorMessage);
errMsg.setVisible(true);
param.loginButton && params.loginButton.enable();
}
}
};
Insights.view.common.util.RequestUtil.request(params, 'false');
},
I did a debug on Chrome and the requestPayload does not exist.
The pure ext.js project returns the following on debug on Chrome.
As you notice, this has the requestPayload with the username and password. Also failure: function (response) returns response.status=0. What am I missing in the pure javascript way of sending the request.
EDIT, adding RequestUtil Code
Ext.define('Insights.view.common.util.RequestUtil', {
singleton: true,
config: {
baseUrl: ''
},
request: function (params, component) {
var me = this,
headers = {
'ACCEPT': 'application/json'
};
var appData = Insights.view.common.util.StorageUtil.getAppData();
if (appData) {
headers.authToken = appData.token;
} else if (params.authToken) {
headers.authToken = params.authToken;
}
if(params.headers) {
Ext.Object.merge(headers, params.headers)
}
this.loadMask(component);
Ext.Ajax.request({
url: this.getBaseUrl() + params.url,
timeout: 60000,
headers: headers,
disableCaching: false,
method: params.method,
jsonData: params.jsonData,
params: params.extraParams,
binary: !params.binary ? false : params.binary,
success: function (response, opts) {
if (params.success) {
params.success(response, opts);
me.unLoadMask(component);
}
},
failure: function (response, opts) {
if (params.failure) {
params.failure(response, opts);
}
if (!Ext.isString(component)) {
me.unLoadMask(component);
if (params.url == "authenticate" || params.url == "userInfo") {
return;
}
var responseText = response.responseText && Ext.JSON.decode(response.responseText);
if (responseText && responseText.status === 'Failure') {
Ext.Msg.alert(i18nLabels.warning, responseText.message);
} else if (response.status == 401) {
me.handleSessionTimeout();
} else if (response.status == 404 || response.status == 500) {
me.errorHandler(responseText.message);
} else if (response.status == 405) {
} else {
me.errorHandler(i18nLabels.serverNotAvailable);
}
}
}
});
},
I debugged and checked, jsonData does have the username,password string. This ajax fails and enters failure segment.
The OPTIONS request in the first screen suggests that there is a CORS related problem. This problem can be solved by enabling CORS.
Author's solution (from comments): open -a Google\ Chrome --args --disable-web-security --user-data-dir="tmp/tmpChrome
Is that possible to send JSON data over 2000 chars?
My url length is 5260, and I get error GET 404().
Is there any solution to send this data in json?
update: {
url: ServiceBase + "Coating/updateTestResult",
dataType: "json",
complete: function (jqXHR, textStatus) {
if (jqXHR.status == "200") {
showNotification("Alert", "Records updated.", "upload-success");
} else {
showNotification("Error", "Couldn't update records.", "info");
}
}
}
if (operation === "update") {
$.each(dataSource._data, function () {
var row = $("#grid tbody").find("tr[data-uid='" + this.uid + "']");
if (row.hasClass("blur")) {
row.removeClass("blur");
}
this.dirty = false;
});
return { models: kendo.stringify(options.models) };
}
Try to perform a POST request instead. Max. URL length is 2000 chars (SO answer) that's why you get an error 404.
If i access the link http://localhost/cgi-bin/superCategory.pl?action=GET
I will get this data:
[{"name":"Baby Care","id":"2","image":"/images/categories/baby-care.png"},{"name":" Bread, Bakery & Dairy Products","id":"5","image":"/images/categories/dairy-products.png"},{"name":"Beverages","id":"6","image":"/images/categories/beverages.png"},{"name":"Others","id":"9","image":"/images/categories/others.png"}]
But when i try to get the same data using AngularJS service and controller, I m not getting the data. This is my controller and service code.
sampleApp.factory('SuperCategoryService', ['$http', function ($http){
var req = {
method: 'POST',
url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: { action: 'GET' }
};
return {
GetSuperCategories: function () {
return $http(req).then(
function(response)
{
if (typeof response === 'object')
{
return response;
}
else
{
alert ('wrong');
}
},
function(response) {
alert ('again worng');
// something went wrong
//return $q.reject(response.data);
});
}
};
}]);
sampleApp.controller('SuperCategoryController', function ($scope,SuperCategoryService) {
$scope.SuperCategories = [];
$scope.GetSuperCategories = function() {
SuperCategoryService.GetSuperCategories().then(
function(d) {
alert (d);
if (d !== undefined) {
alert ('in');
console.log(d);
$scope.SuperCategories = d;
}
else {
alert ('undefined data');
}
},
function(response) {
alert ('error worng');
// something went wrong
//return $q.reject(response.data);
});
};
$scope.GetSuperCategories();
});
though code is reaching to alert ('in'), but nothing is getting assigned to variable $scope.SuperCategories;
Can some one help me what i m doing wrong in assignment.
Your service function is doing $http using .then which is nothing but resolving using chain promise you should get explicit data from object you service will return response.data instead of response
GetSuperCategories: function () {
return $http(req).then(
function(response)
{
var data = response.data;
if (typeof data === 'object')
{
return data ;
}
else
{
alert ('wrong');
}
},
function(response) {
alert ('again worng');
// something went wrong
//return $q.reject(response.data);
});
}
};
I am trying to get a Twitter access token from their oauth api. The plugin I am using is this https://code.google.com/p/oauth/source/browse/#svn%2Fcode%2Fjavascript. So far I only get "401 failed to validate signature and token".
Strange thing is that my ajax call becomes 'GET' request even though I set type:'POST'. Seems like jquery is changing the type from POST to GET. I don't know why it does that. I am running it on my Mac. I appreciate your help/hints/suggestions/advises. Thanks!
$(function() {
function myCallback(resp) {
console.log(resp);
}
var TwitterAPI;
TwitterAPI = (function() {
var consumer_key = null;
var consumer_secret = null;
function TwitterAPI(cons_key, cons_secret) {
this.consumer_key = cons_key;
this.consumer_secret = cons_secret;
}
TwitterAPI.prototype._url = function (data) {
if (typeof data == 'array') {
return array_map([ // TODO
this, '_url'], data);
} else if ((/boolean|number|string/).test(typeof data)) {
return encodeURIComponent(data).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
} else {
return '';
}
}
TwitterAPI.prototype.myCallback = function(resp) {
console.log(resp);
}
TwitterAPI.prototype.getRequestToken = function() {
var accessor = {
consumerSecret: this.consumer_secret, //this.consumer.consumerSecret,
tokenSecret: ''
};
var message = {
method: "POST",
action: "https://api.twitter.com/oauth/request_token",
parameters: {
oauth_signature_method: "HMAC-SHA1",
oauth_consumer_key: this.consumer_key, //this.consumer.consumerKey
oauth_callback: this._url("http://127.0.0.1/foobar/libs/oauth/wtf.html"),
}
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var target = OAuth.addToURL(message.action, message.parameters);
message.parameters.oauth_signature = this._url(message.parameters.oauth_signature);
console.log(message.parameters);
$.ajax("https://api.twitter.com/oauth/request_token",
{ url: "https://api.twitter.com/oauth/request_token",
type: 'POST',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: "myCallback",
data: message.parameters,
success: function(data, textResp, xhr) {
console.log(data);
},
error: function(xhr, text, err) {
console.log(text);
}
});
};
return TwitterAPI;
})();
api = new TwitterAPI(key, secret);
$('button#request').on('click', function(e) {
e.stopPropagation();
api.getRequestToken();
});