How to load remote data into grid? - javascript

I have a grid initially loaded with some data from the Store. I have search field in the form through which I can filter data. After the entering search criteria in the search field... I am calling an ajax request and getting data into the app, but unable to load this data into the store and update the grid.
var myStore = Ext.data.StoreManager.get("driveScheduleStore");
var tempStore = Ext.data.StoreManager.get("tempDSStore");
var strSearch = Ext.getCmp('VoiceDIDSearch').getValue();
Ext.Ajax.request({
url: '.../TEST/GetDriveScheduleDataFilter.php',
method: 'POST',
params: {
VDID:strSearch
},
success: function(result, request) {
var json = result.responseText;
var temp = JSON.parse(json);
myStore.load(temp.SCHEDULE);
Ext.Msg.alert('Message',myStore.getTotalCount());
},
failure: function(result, request) {
Ext.Msg.alert('Error', 'An Error occured...');
}
});
Please help.
Thanks in advance.

You can try with store.loadRawData(data, [append]).

The load function loads the store using the configured proxy, you need to use loadData to load custom json data.
http://docs.sencha.com/extjs/4.1.3/#!/api/Ext.data.Store-method-loadData

Related

How to get Google maps URL with a 'placeid' with AJAX?

I have a URL which I can open on browser and view the JSON data. The URL looks something like this:
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE
Now when I try to access this with jQuery AJAX, I fail to get any results, instead I get an error.
My AJAX call looks some like this:
$.ajax({
url: https://maps.googleapis.com/maps/api/place/details/json,
data: {
'placeid': 'ChIJZeH1eyl344kRA3v52Jl3kHo',
'key': 'API_KEY_HERE'
},
dataType: 'json',
success: function(response) {
alert(JSON.stringify(response));
},
error: function(error) {
alert(JSON.stringify(error));
}
});
var API_KEY = api_key;
var placeid = placeid;
var API_URL = `https://maps.googleapis.com/maps/api/place/details/json?placeid=${placeid}&key=${API_KEY}`
$.getJSON(API_URL, {
tags: placeid,
tagmode: "any",
format: "json"
},
function(data) {
alert(data);
});
If I build it up correctly, this should be the way to send the data correctly to the api, using the placeid inside the url string together with the api_key.
Then you use a getJSON instead of json because I assume you want to get the place data? Assuming to what you're doing in the ajax you made.
Maybe explain further what you mean with how to get google maps url with place id? Hope it helps you out :)

how to handle ajax parsererror nicely?

I have a google ad project which requires me to get multiple "setTargeting('', '');" from an object array on json file (via url) --> {"country": "Netherlands", "city": "Amsterdam" }. So far everything works; however, suppose the network fails, or requested JSON parse failed, etc - I'd like to pass an empty array to make sure that the slot will still show ads with no targeting.
What would be a good practise for it?
Advertisements.cachedCategoriesByUrl = {};
Advertisements.getCategories = function(categoriesUrl) {
var cachedCategories = Advertisements.cachedCategoriesByUrl[categoriesUrl];
if(cachedCategories){
return cachedCategories;
} else {
var getCategories = $.ajax({
url: categoriesUrl,
data: { format: 'json' },
error: function(jqXHR, status, thrownError) {
=> I'd like to pass an empty array so the slot will show
ads with no targetting set.
However this doesn't seem to be working.
Do I need to do callback?
}
});
Advertisements.cachedCategoriesByUrl[categoriesUrl] = getCategories;
return getCategories;
}
}
Note:
return getCategories runs before the ajax call finishes. How do I make sure that return getCategories gets my error update(I want to pass an empty array if JSON request fails or invalid). Sorry I am in the learning process.
Solved it with this:
$.ajax({
url: ad.categoriesUrl
}).then(function(data){
Advertisements.advertisementSlot(ad, data);
}, function(data){
data = {};
Advertisements.advertisementSlot(ad, data);
});

Angular, sending json to an API

I am trying to post json to an api and its giving me the following error...
http://www.website.com/getPriceNoAuth?json=[object%20Object] 405 (Method Not Allowed)
This is the json object I am trying to send and its http resuest...
var productAttributes = {
"CostRequirements":[
{
"OriginPostcode":"BR60ND",
"BearerSize":100,
"BandwidthRequired":10,
"ProductCode":"CON-ELA",
"Term":36,
"Quantity":1
},
{
"ProductCode":"CON-ADD-IP4",
"Term":36,
"Quantity":0
},
{
"ProductCode":"CON-ADD-INT",
"Term":36,
"Quantity":0
}
]
}
this.getPrices1 = function () {
return $http.post('http://www.website.com/getPriceNoAuth?json=' + productAttributes ).
success(function(resp){
//log something here.
});
};
Does anyone see what I'm doing wrong? thank you.
$http({
url:'http://myurl.com'
method:'POST',
data:{
'json':productAttributes
}
});
ORRR if you really need to pass the data from the url stringify your json and decode it on server side
$http.post('http://myurl.com?json=' + JSON.stringify(myJson));
You're trying to post the data, but you're putting it in the url like a get parameter. Post data like this:
this.getPrices1 = function () {
return $http.post('http://www.website.com/getPriceNoAuth', {json: productAttributes} ).
success(function(resp){
//log something here.
});
};
The http header are not defined in there.. but by defaults it considers json as the content type:
$http.post('/someUrl', data).success(successCallback);
here you have to call an api, in which we have to sent data using get
method. Just use the following code and that's it. It works for me, hope it
will work for you also.
var dataObject = {
json : productAttributes
};
var responsePromise = $http.get("http://www.website.com/getPriceNoAuth", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config) {
var outputDate=angular.fromJson(dataFromServer);
if(outputDate.status==1)
{
angular.forEach(outputDate.storelist, function(value, key) {
$scope.userstores.push({name:value.StoreName,id:value.StoreID});
});
}
});
responsePromise.error(function(data, status, headers, config) {
console.log("Error in fetching user store call!");
});

Backbone.js default path (subdomain)

I am using CORS so all the API happens in api.mywebsite.com but the website is served via website.com.
I am wondering if there's a way I can set the setting of either jQuery or Backbone to always make AJAX requests to my api.mywebsite.com ?
In otherwords, I want to do this in my backbone collections:
url: '/books'
and have it automatically infer api.mywebsite.com/v1/books
For the collection you can specify the full URL:
YourApp.Collections.Books = Backbone.Collection.extend({
model: YourApp.Models.Book,
url: 'http://api.mywebsite.com/v1/books/'
});
And for individual resources you can use a function to generate the url:
YourApp.Models.Book = Backbone.Model.extend({
url: function() {
return 'http://api.mywebsite.com/v1/books/' + this.get('id')
}
});
Backbone has the urlRoot method that sets the root of all requests.
From the Backbone site:
var Book = Backbone.Model.extend({urlRoot : '/books'});
var solaris = new Book({id: "1083-lem-solaris"});
alert(solaris.url());
alerts "/books/1083-lem-solaris"
Of-course you can change that relative path to something else: put a dot in front to send it to the site root, or your specific site root, or give it an absolute path.
Documentation
Of course in jQuery you can build the URL to whatever you like in an AJAX request. Including to an absolute url as long as it's not another domain:
$.ajax({
type: "GET",
url: "http://api.mywebsite.com + "anything_you_want_to_add"
}).done(function(response) {
console.log(response);
receiveResponseMethodSomewhereElse(response);
});
And a quick Backbone example of using the url parameter of the Model or the Collection:
The showing the scripts I used:
<title>Backbone Test</title>
<meta charset="UTF-8">
<script src="jquery.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
And then I specifically pointed this backbone example at my localhost. You'd want to point it to your domain. I included all of the console logs and available responses for your debugging pleasure. Both options here are building urls from the book id as that's normall what your creating, Reading, Updating or Deleting from the server. I put this script directly within the body of the page and watched the console logs. Note: Backbone is expecting a JSON response.
<script>
var Book = Backbone.Model.extend({urlRoot: 'http://localhost/url_test'});
var BookCollection = Backbone.Collection.extend({
model: Book,
url: 'http://localhost/url_test'
});
var myExcellentBook = new Book({id: "book"});
var MyBooks = new BookCollection();
// getting it directly from the model
solaris.fetch({
success: function(model, response, options) {
console.log("SUCCESS");
console.log(model);
console.log(response);
console.log(options);
},
error: function(model, response, options) {
console.log("ERROR");
console.log(model);
console.log(response);
console.log(options);
},
complete: function(xhr, textStatus) {
console.log(textStatus);
}
});
// or fetch directly from the collection and
// normally you'd loop through the response or
// when creating new models, you can let backbone
// intialize them through the response
MyBooks.fetch({
success: function(model, response, options) {
console.log("SUCCESS");
console.log(model);
console.log(response);
console.log(options);
},
error: function(model, response, options) {
console.log("ERROR");
console.log(model);
console.log(response);
console.log(options);
},
complete: function(xhr, textStatus) {
console.log(textStatus);
}
});
</script>
And the php script at url_test is simply returning a JSON object.
<?php
echo '[{"id": "MyNewBook"}]';

AngularJS 1.2.0 $resource PUT/POST/DELETE do not send whole object

I'm using angularjs 1.2.0 with $resource. I would like to have some PUT/POST instance actions that doesn't send the whole object to the server but only some fields and in some cases totally no data.
Is it possible? I searched everywhere but couldn't find anything
UPDATE:
It also happens with DELETE requests:
Given this code:
group.$deleteChatMessage({messageId: message.id}, function(){
var i = _.indexOf(group.chat, message);
if(i !== -1) group.chat.splice(i, 1);
});
The request is this:
See how the whole model is sent (under "Request Payload").
This is the resource:
var Group = $resource(API_URL + '/api/v1/groups/:gid',
{gid:'#_id', messageId: '#_messageId'},
{
deleteChatMessage: {method: "DELETE", url: API_URL + '/api/v1/groups/:gid/chat/:messageId'},
});
This works for me:
$resource(SERVER_URL + 'profile.json',
{},
{
changePassword :
{
method : 'POST',
url : SERVER_URL + 'profile/changePassword.json',
// Don't sent request body
transformRequest : function(data, headersGetter)
{
return '';
}
}
});
You could customise exaclty what is sent to the server by implementing your own code in the transformRequest function. In my example I was adding a new function to the REST client, but you can also overwrite existing functions. Note that 'transformRequest' is only available in version 1.1+
You can use $http for that specifically. However, I have one case I use for a project that might help. Also my example is returning an array from the server but you can change that.
In my service:
app.factory('mySearch', ['$resource', function($resource) {
return $resource('/api/items/:action', {}, {
search: { method: 'POST', isArray: true,
params: { action: 'search' }
}
});
}
]);
In my Controller:
I can build up custom params to post to server or if its only two fields I need from a table row the user selects.
var one = "field_one";
var two = "field_two";
$scope.search({one: one, two: two});
Then I can post those through an event and pass the custom params
$scope.search = function(customParams) {
mySearch.search({query: customParams}, function(data) {
$scope.items = data;
}, function(response) {
console.log("Error: " + response.status);
})
};
Hopefully this was some help. Let me know if this is close to what your looking for and I can help more.
POST
DELETE

Categories

Resources