Uncaught TypeError when loading store in button handler function - extjs6-classic

I got Uncaught TypeError when loading store in button handler function,
is there something wrong with my
Code:
{
xtype: 'button',
text: 'Click me',
handler: function() {
var store = Ext.create('Ext.data.Store', {
autoLoad : true,
proxy: {
type: 'ajax',
url : 'MyUrl'
}
});
}
}
Error Message:
Uncaught TypeError: instance[configPropMap[name].names.get] is not a function
Debugger screenshots:
name is async
but instance has no getAsync function

I've got a solution, use syncajax below instead of proxy.ajax.
Ext.define('MyApp.store.proxy.SyncAjax', {
extend : 'Ext.data.proxy.Ajax',
alias : 'proxy.syncajax',
config : {
async : false
},
buildRequest : function() {
var me = this,
request = me.callParent(arguments);
request.defaultConfig.async = me.getAsync();
request.getAsync = function() {
request.getAsync = null;
return me.getAsync();
};
return request;
}});

Related

Uncaught (in promise) TypeError: Cannot use 'in' operator to search for 'validateStatus' in

I am getting ** Uncaught (in promise) TypeError: Cannot use 'in' operator to search for 'validateStatus' in 5f8425a33a14f026f80133ed** where 5f8425a33a14f026f80133ed is the id passed to the axios url
I want to display the services based on the user id. My url works perfectly in postman but when i access it from the veux store it gives an error.
services.js (store)
import axios from 'axios';
const state = {
services : {},
status: '',
error: null
};
const getters = {
services : state => { return state.services }
};
const actions = {
async fetchServices({commit}, userId) {
let res = await axios.get('http://localhost:5000/api/services/displayUser' , userId)
commit('setProducts', res.data)
return res;
}
};
const mutations = {
setProducts (state, items) {
state.services= items
},
};
export default {
state,
actions,
mutations,
getters
};
This is how I am calling the action :
computed: {
...mapGetters(["services"]),
},
methods: {
...mapActions(["fetchServices"]),
getData(){
this.fetchServices(this.user._id)
},
},
async created() {
await this.getProfile();
await this.getData();
}
The axios route is defined as
router.get('/displayUser', (req,res) => {
const query = user = req.body ;
Services.find(query)
.exec((err, services) => res.json(services))
})
the error screenshot :
Error screenshot
GET request should not have a body. Either use query params, indicate an id in a path, or use POST request.
In case of query params this may look like this:
let res = await axios.get('http://localhost:5000/api/services/displayUser' , { params: { userId })
router.get('/displayUser', (req,res) => {
const query = user = req.query;
Services.find(query)
.exec((err, services) => res.json(services))
})
This worked for me too:
In front end: Vue Js
let res = axios.get("http://localhost:3000/api/v1/role/getRoleByName",
{ params: { roleName: "name of role you want to send as params" },
});
In back end: Node Js
router.get('/getRoleByName', (req,res)=>{
let roleName = req.query.roleName;
roleModule.getRoleByName(roleName).then(data =>{
response.json(res,data)
}
).catch(err=> {
response.badRequest(res, err);
})
});
it's a silly mistake axios.post req.
async addTodo({ commit }, title) {
try {
const res = await axios.post(BASE_URL, { title, complete: false });
commit("newTodo", res.data);
} catch (err) {
console.log(err.message);
}
},

Mapping List with Knockout Mapping

I have created view model
var catalog = ko.observableArray();
$.ajax({
type: "GET",
url: "http://localhost:8080/ticket-service/rest/ticket/list",
success: function(msg) {
catalog.push.apply(catalog, $.map(msg, function(data) {
return new Ticket(data)
}));
return catalog;
},
error: function(msg) {
console.log(msg)
}
});
and the model
function Ticket(data) {
this.ticketId = ko.observable(data.ticketId);
this.ticketNo = ko.observable(data.ticketNo);
this.ticketTitle = ko.observable(data.ticketTitle);
this.longDescription = ko.observable(data.longDescription);
this.createdBy = ko.observable(data.createdBy);
this.createdOn= ko.observable(data.createdOn);
this.assignTo = ko.observable(data.assignTo);
this.priority = ko.observable(data.priority);
this.dueDate = ko.observable(data.dueDate);
this.status = ko.observable(data.status);
this.projectId = ko.observable(data.projectId);
}
with at the end viewmodel like this
return {
ticket: newTicket,
searchTerm: searchTerm,
catalog: filteredCatalog,
newTicket: newTicket,
addTicket: addTicket,
delTicket: delTicket
};
})();
console.log(vm);
ko.applyBindings(vm);
produce list,add, and delete form.The question is how can i use knockout mapping that can list from get methode.
you need to do something like this
Demonstrated taking a single entity from your code .
view:
Output Preview :
<pre data-bind="text:ko.toJSON($data,null,2)"></pre>
viewModel:
function Ticket(data) {
this.ticketId = ko.observable(data.ticketId);
}
var mapping = {
create: function (options) {
return new Ticket(options.data);
}
};
var ViewModel = function () {
var self = this;
self.catalog = ko.observableArray();
var data = [{
'ticketId': 1
}, {
'ticketId': 2
}]
//under ajax call do the same but pass 'msg' in place of data
self.catalog(ko.mapping.fromJS(data, mapping)())
console.log(self.catalog()); // check console for output
};
ko.applyBindings(new ViewModel());
sample working fiddle here

Decoding response error in extjs

I am doing the following stuff when a form is submitted. But I get this error:
Error decoding response: SyntaxError: syntax error
Here is my onSubmit success function:
onSubmit: function() {
var vals = this.form.getValues();
Ext.Ajax.request({
url: 'ticketSession.php',
jsonData: {
"function": "sessionTicket",
"parameters": {
"ticket": vals['ticket']
}
},
success: function( result, request ) {
var obj = Ext.decode( result.responseText );
if( obj.success ) {
//alert ('got here');
th.ticketWindow.hide();
Web.Dashboard.loadDefault();
}
},
Here is my ticketSession.php
<?php
function sessionTicket($ticket) {
if( $_REQUEST['ticket'] ) {
session_start();
$ticket = $_REQUEST['ticket'];
$_SESSION['ticket'] = $ticket;
echo("{'success':'true'}");
}
echo "{'failure':'true', 'Error':'No ticket Number found'}");
}
?>
I also modified my onsubmit function but didnt work:
Ext.Ajax.request({
url: 'ticketSession.php',
method: 'POST',
params: {
ticket: vals['ticket']
},
i am simply echoing this but I still get that error
echo("{'success':'true'}");
Maybe this can help you. It's a working example of an ajax-request which is nested in a handler.
var deleteFoldersUrl = '<?php echo $html->url('/trees/delete/') ?>';
function(){
var n = tree.getSelectionModel().getSelectedNode();
//FolderID
var params = {'folder_id':n['id']};
Ext.Ajax.request({
url:deleteFoldersUrl,
params:params,
success:function(response, request) {
if (response.responseText == '{success:false}'){
request.failure();
} else {
Ext.Msg.alert('Success);
}
},
failure:function() {
Ext.Msg.alert('Error');
}
});
}

Childbrowser plugin not working in Phonegap

I'm using Backbone, Require and Underscore Bundled with Phonegap or Cordova.
I tried using the childbrowser plugin but it wont work. I followed the instructions here.
http://blog.digitalbackcountry.com/2012/03/installing-the-childbrowser-plugin-for-ios-with-phonegapcordova-1-5/
define([
'jquery',
'backbone',
'underscore',
'base64',
'mobile',
'const',
'child',
'text!template/login/login.tpl.html'
],function($, Backbone, _, base64, Mobile, Const, ChildBrowser, template){
var EncodeAuth = function(user,pass)
{
var _tok = user + ':' + pass;
var _hash = Base64.encode(_tok);
return "Basic "+ _hash;
}
var LoginView = Backbone.View.extend({
events:{
"click .login-btn" : "Login",
"click .connection-btn" : "OpenSite"
},
initialize: function(){
},
Login: function(){
Const.USERNAME = $("#username").val();
Const.PASSWORD = $("#password").val();
if(!Const.USERNAME || !Const.PASSWORD)
{
navigator.notification.alert("Invalid Username/Password!");
$("input").val("");
}else{
var auth = EncodeAuth(Const.USERNAME,Const.PASSWORD);
var sendAuthorization = function (xhr) {
xhr.setRequestHeader('Authorization', auth)
};
this.model.save(this.model, {
beforeSend : sendAuthorization,
success: function(model,result){
if(result.ErrorMessage === null)
{
alert(JSON.stringify(result.Message));
$("input").val("");
}
else
{
alert(JSON.stringify(result.ErrorMessage));
$("input").val("");
}
},
error: function(model,result){
alert("Remote server returned an error. Not Found");
$("input").val("");
}
});
}
},
OpenSite: function(){
window.plugins.ChildBrowser.showWebPage("http://www.google.com");
}
});
return LoginView;
});
Any ideas?

KnockoutJS : initial values are not posted to server when using ko.toJSON(this)?

I've this javascript viewmodel defined:
function PersonViewModel() {
// Data members
this.Name = ko.observable();
this.Function_Id = ko.observable();
this.SubFunction_Id = ko.observable();
this.Functions = ko.observableArray();
this.SubFunctions = ko.observableArray();
// Whenever the Function changes, update the SubFunctions selection
this.Function_Id.subscribe(function (id) {
this.GetSubFunctions(id);
}, this);
// Functions to get data from server
this.Init = function () {
this.GetFunctions();
this.Function_Id('#(Model.Function_Id)');
};
this.GetFunctions = function () {
var vm = this;
$.getJSON(
'#Url.Action("GetFunctions", "Function")',
function (data) {
vm.Functions(data);
}
);
};
this.GetSubFunctions = function (Function_Id) {
var vm = this;
if (Function_Id != null) {
$.getJSON(
'#Url.Action("GetSubFunctions", "Function")',
{ Function_Id: Function_Id },
function (data) {
vm.SubFunctions(data);
}
);
}
else {
vm.SubFunction_Id(0);
vm.SubFunctions([]);
}
};
this.Save = function () {
var PostData = ko.toJSON(this);
var d = $.dump(PostData);
alert(d);
$.ajax({
type: 'POST',
url: '/Person/Save',
data: PostData,
contentType: 'application/json',
success: function (data) {
alert(data);
}
});
};
}
$(document).ready(function () {
var personViewModel = new PersonViewModel();
personViewModel.Init();
ko.applyBindings(personViewModel);
});
When the Submit button is clicked, the data from the select lists is posted, but NOT the 'Function_Id'.
When I choose a different value in the Function dropdown list, and the click the Submit button, the value for 'Function_Id' is correctly posted.
How to fix this ?
It's because the scope of the this keyword in javascript
this.Init = function () {
this.GetFunctions(); // this === PersonViewModel.Init
this.Function_Id('#(Model.Function_Id)'); // calls PersonViewModel.Init.Function_Id(...)
};
You should store the refrence to the PersonViewModel instance.
var self = this;
self.Init = function () {
self.GetFunctions();
self.Function_Id('#(Model.Function_Id)'); // calls PersonViewModel.Function_Id(...)
};