how pass a property from initialize event to an Ajax.Request object inside the same class - Prototype - prototypejs

On the code below, i'm trying to use this.loadingImage1 from initialize event in another method's ajax.request object but it just displays 'undefined'.
var ActivityJS = Class.create({
initialize : function(options)
{
this.options = {
school : options.school,
htaccessPage : options.htaccessPage
};
this.loadingImage1 = (options.pageId == ''?"img1":"img2");
}, deleteTask: function(taskId)
{
var params = "id="+taskId;
var ajax = new Ajax.Request(this.widgetUrl,{
method: 'POST',
parameters: params,
evalJS: true,
onLoading: function()
{
$(dvId).innerHTML = "<img src='"+this.loadingImage1+"' />";
},
onComplete: function(response)
{
$(dvId).update(response.responseText);
setTimeout(function() {
Lightview.hide();
window.location.reload();
}, 2000);
}
});
}
});
Any suggestions? Thanks in advance.

What if you use bind() (http://www.prototypejs.org/api/function/bind) on onLoading
onLoading: function() {...}.bind(this),

Related

How can I handle a ajax request response in the Flux Architecture?

Looking at the Flux Documentation I can't figure out how the code to a ajax update, and a ajax fetch would fit into the dispatcher, store, component architecture.
Can anyone provide a simple, dummy example, of how an entity of data would be fetched from the server AFTER page load, and how this entity would be pushed to the server at a later date. How would the "complete" or "error" status of request be translated and treated by the views/components? How would a store wait for the ajax request to wait? :-?
Is this what you are looking for?
http://facebook.github.io/react/tips/initial-ajax.html
you can also implement a fetch in the store in order to manage the information.
Here is an example (it is a concept, not actually working code):
'use strict';
var React = require('react');
var Constants = require('constants');
var merge = require('react/lib/merge'); //This must be replaced for assign
var EventEmitter = require('events').EventEmitter;
var Dispatcher = require('dispatcher');
var CHANGE_EVENT = "change";
var data = {};
var message = "";
function _fetch () {
message = "Fetching data";
$.ajax({
type: 'GET',
url: 'Url',
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = error;
MyStore.emitChange();
}
});
};
function _post (myData) {
//Make post
$.ajax({
type: 'POST',
url: 'Url',
// post payload:
data: JSON.stringify(myData),
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = "update failed";
MyStore.emitChange();
}
});
};
var MyStore = merge(EventEmitter.prototype, {
emitChange: function () {
this.emit(CHANGE_EVENT);
},
addChangeListener: function (callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function (callback) {
this.removeListener(CHANGE_EVENT, callback);
},
getData: function (){
if(!data){
_fetch();
}
return data;
},
getMessage: function (){
return message;
},
dispatcherIndex: Dispatcher.register( function(payload) {
var action = payload.action; // this is our action from handleViewAction
switch(action.actionType){
case Constants.UPDATE:
message = "updating...";
_post(payload.action.data);
break;
}
MyStore.emitChange();
return true;
})
});
module.exports = MyStore;
Then you need to subscribe your component to the store change events
var React = require('react');
var MyStore = require('my-store');
function getComments (){
return {
message: null,
data: MyStore.getData()
}
};
var AlbumComments = module.exports = React.createClass({
getInitialState: function() {
return getData();
},
componentWillMount: function(){
MyStore.addChangeListener(this._onChange);
},
componentWillUnmount: function(){
MyStore.removeChangeListener(this._onChange);
},
_onChange: function(){
var msg = MyStore.getMessage();
if (!message){
this.setState(getData());
} else {
this.setState({
message: msg,
data: null
});
}
},
render: function() {
console.log('render');
return (
<div>
{ this.state.message }
{this.state.data.map(function(item){
return <div>{ item }</div>
})}
</div>
);
}
});
I hope it is clear enough.

Kendo UI reload treeview

I load a complex treeview with kendo ui via ajax because I need to load the tree with one request (works fine):
$(document).ready(function() {
buildTree();
});
function buildTree(){
$.getJSON("admin_get_treedata.php", function (data) {
$("#treeview").kendoTreeView({
select: function(item) { editTreeElement(item,'tree'); },
dataSource: data
});
})
}
If I try to reload the complete tree after changing some data via ajax the new build tree does not work correct and does not update the text.
$.ajax({
type: 'POST',
url: 'ajax/ajax_update_layer.php',
data: {
layerid:id,
...
},
success: function(data){
buildTree();
}
});
What can Ido?
Thanks
Sven
try this on ajax success callback
var data = $("#treeView").data('kendoTreeView');
data.dataSource.read();
I got mine to work.
This is what I did:
Function that creates the tree view:
function CreateNotificationTree(userId)
{
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + userId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var $item = this.dataItem(e.node);
window.open($item.NotificationLink, "_self");
}
}
Modification & data source refresh:
$('#btnDelete').on('click', function()
{
var treeView = $("#treeview").data("kendoTreeView");
var userId = $('#user_id').val();
$('#treeview').find('input:checkbox:checked').each(function()
{
var li = $(this).closest(".k-item")[0];
var notificationId = treeView.dataSource.getByUid(li.getAttribute('data-uid')).ID;
if (notificationId == "undefined")
{
alert('No ID was found for one or more notifications selected. These notifications will not be deleted. Please contact IT about this issue.');
}
else
{
$.ajax(
{
url: '../api/notifications/deleteNotification?userId=' + userId + '&notificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
treeView.remove($(this).closest('.k-item'));
}
});
});
Hope that helps.

ember ajax calls with promisses access result in templates and controller

I'm making a call to the server to get some data via an ajax request and I use a promise. While my template automatically updates as soon as the data is returned, I'm unlucky accessing the data in the controller, as I don't know exactly when it's there.
To resolve I can make an additional ajax call in the controller to get the same data but that feels ugly. Is there a nicer way to know when to access the data in the controller? As a work around I tried to call the function that needs the data on the didInsertElement but that didn't solve it.
App.ActiveDataSet = Ember.Object.extend({
progress: 0
});
App.ActiveDataSet.reopenClass({
findAll: function(project_id) {
var result = [];
$.ajax({
url: '/active_data_sets.json',
type: 'GET',
data: {'project_id': project_id}
}).then(function(response) {
response.active_data_sets.forEach(function(newset) {
result.addObject(App.ActiveDataSet.create(newset));
});
});
return result;
}
});
App.MapviewShowRoute = Ember.Route.extend({
setupController: function(controller, model) {
this.controllerFor('activedatasetIndex').set('content', App.ActiveDataSet.findAll(model.id));
}
});
App.MapviewShowController = Ember.ObjectController.extend({
needs: ['activedatasetIndex'],
content: null,
dataSets: [],
createDataSets: function() {
// create the datasets
for (var counter = 0; counter < this.get('controllers.activedatasetIndex.content').length; counter++) {
alert(dataSets[counter].ds.name);
}
}
});
App.MapviewShowView = Ember.View.extend({
map: null,
didInsertElement: function() {
var map = null;
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(52.368892, 4.875183),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(this.$('#map_canvas').get(0), myOptions);
this.set('map', map); //save for future updations
var h = $(window).height(),
offsetTop = 60; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
// get the datasets
this.controller.createDataSets();
}
});
Have you tried continuing the promises chain:
App.ActiveDataSet.reopenClass({
findAll: function(project_id) {
return $.ajax({
url: '/active_data_sets.json',
type: 'GET',
data: {'project_id': project_id}
}).then(function(response) {
var result = [];
response.active_data_sets.forEach(function(newset) {
result.addObject(App.ActiveDataSet.create(newset));
});
return result;
});
}
});
App.MapviewShowRoute = Ember.Route.extend({
setupController: function(controller, model) {
App.ActiveDataSet.findAll(model.id).then(function(content) {
this.controllerFor('activedatasetIndex').set('content', content);
});
}
});

MVC3 and Twitter Bootstrap TypeAhead without plugin

I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

Mootools calling class method onSuccess Ajax

I'm trying to achieve the following:
User clicks on an element and the cmove function is invoked (works)
cmove passes an JS object to the ajax method (works)
ajax method submits the object to the move/test controller (PHP/CodeIgniter) (works)
controller returns some JSON Data (works)
onSucces calls the move method to do some stuff (no chance calling that method)
So, how can I call the move method out of the onSuccess? And is there a better way of pushing the moveObj around?
var Plane = new Class({
Implements: Options,
options: {
action: null
},
initialize: function(options) {
this.setOptions(options);
$('somelement').addEvent('click', this.cmove.bind(this));
},
cmove: function(event, action) {
moveObj = new Object();
moveObj.x = 123;
this.ajax('cmove', moveObj);
},
move: function(moveObj) {
console.log("Yippe!"); // not getting here :(
},
ajax: function(action, obj) {
resp = $('resp');
var myRequest = new Request.JSON({
url: '<?php echo site_url('move/test'); ?>',
method: 'get',
onRequest: function(){
resp.set('text', 'wait...');
},
onSuccess: function(responseText){
switch(action)
{
case 'cmove':
test3.move(responseText); // not working
this.move(responseText); // not working
parent.move(responseText); // not working
resp.set('text', responseText.x);
break;
},
onFailure: function(){
resp.set('text', 'Sorry, your request failed :(');
}
}).send('coords='+ JSON.encode(obj));
}
});
window.addEvent('domready', function(){
var test3= new Plane({});
});
you need to bind the callback function for the Request instance to the scope of your class or save a reference of your class' instance (self = this) and call via that instead:
ajax: function(action, obj) {
var self = this; // save a refrence
var resp = document.id("resp");
new Request.JSON({
url: '<?php echo site_url('move/test'); ?>',
method: 'get',
onRequest: function(){
resp.set('text', 'wait...');
},
onSuccess: function(responseText){
switch(action) {
case 'cmove':
self.move(responseText); // will work
this.move(responseText); // will also work
break;
}
}.bind(this), // binding callback to instance so this.method works
onFailure: function(){
resp.set('text', 'Sorry, your request failed :(');
}
}).send('coords='+ JSON.encode(obj));
}

Resources