submit form using mootools - mootools

I have made a class that handles load and submit of a html form. See code below
ND.Form = new Class({
//--- Implements options og events.
Implements: [Options, Events],
//--- Options.
options: {
url: '',
injectTo: ''
},
//--- Initialize the class.
initialize: function (panel, options) {
//--- Set options
this.setOptions(options);
this.panel = panel;
this.loadForm();
},
loadForm: function () {
var req = new Request.HTML({
url: this.options.url,
method: 'get',
onSuccess: function (html) {
$(this.options.injectTo).empty();
$(this.options.injectTo).adopt(html);
var formId = $(this.options.injectTo).getFirst('form').get('id');
$(formId).addEvent('submit', function (e) {
e.stop();
this.submitForm(formId);
} .bind(this));
} .bind(this)
}).send();
},
submitForm: function (formId) {
$(formId).set('send', {
onSuccess: function (resp) {
this.panel.loadContent();
if (resp != null) {
$('lbl_error').empty();
$('lbl_error').setStyles({ 'display': 'block', 'color': 'red' }).set('html', resp);
}
}.bind(this),
onFailure: function (resp) {
if (resp != null) {
$('lbl_error').empty();
$('lbl_error').setStyles({ 'display': 'block', 'color': 'red' }).set('html', resp);
}
}
});
$(formId).send();
}
});
And it all works just fine, exept that when i push the save button more than ones the "this.panel.loadContent();" in the "submitForm: function (formId)" fires the same x amount of times I have pushed the button, how can i prevent this ?
/Martin

Starting from mootools 1.3 "set('send')" adds another one event.
So You need to write:
$('myForm').set('send', {
onSuccess: function (html) {},
onFailure: function(xhr){}
}).addEvent('submit', function(e){
e.stop();
this.send();
});
instead of:
$('myForm').addEvent('submit', function(e){
e.stop();
this.set('send', {
onSuccess: function (html) {},
onFailure: function(xhr){}
});
}).send();
Then Request will be sent only once each time when You handle form.

Basically we need to do three things:
Listen for the ‘click’ event on the submit button.
Stop the event from submitting the form.
Send the form using $(formElement).send()
A solution could look something like this:
$('submit').addEvent( 'click', function(evt){
// Stops the submission of the form.
new Event(evt).stop();
// Sends the form to the action path,
// which is 'script.php'
$('myForm').send();
} );

I have used the request.send() method but googled trying to find a way to just replicate the action of a user hitting a form submit button, but with also allowing some javascript logic being performed beforehand. I did not find anything in discussions specifically addressing this. The answer I found is to use the form.submit() method.

Related

DEBOUNCE JS NOT WORKING with event onclick was added at HTML Tag

I am learning about debounce js, and know its simple syntax as follows.
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
fn();
}, delay);
}
I create a button to test it as follow
<button id="test-debounce" onclick="testDebounce()">Click me</button>
function testDebounce().
function testDebounce() {
debounce(() => {
console.log('test debounce')
}, 500)
}
But it not work.
I try again with
document.getElementById("test-debounce").addEventListener('click', debounce(() => {
console.log('test debounce');
}, 500))
It's oke. I don't undetstand. Can anyone explain for me ?
Thanks.
debounce is designed to create a debounced function.
Every time you click you create a debounced function which you never call.
Create the function once:
const testDebounce = debounce(() => {
console.log('test debounce')
}, 500);
… and then use that as the event listener.

Custom Polymer Element refresh data when visible?

In the element script I have:
Polymer({
is: 'projects-page',
attached: function () {
this.async(function () {
// access sibling or parent elements here
var model = this;
$.ajax({
url: "/api/projects",
headers: { "Authorization": "Bearer " + sessionStorage.getItem("accessToken") }
})
.done(function (data) {
console.log(data);
model.projects = data;
model.notifyPath('projects', model.projects);
})
.fail(function (jqXHR, textStatus) {
})
.always(function () {
});
});
}
});
I am needing to refresh this data when the route changes or when it becomes visible to the user.
I am still finding the Polymer docs lacking and any help would be appreciated.
UPDATE:
This is a partial answer.
How can I refresh/reload Polymer element, when page changes?
you could listen to the window url or any other variable that reflects the state of your application with a change-event listener and reload your ajax then. The model should be turned into a properity of your projects-page and the ajax-done event listener should use the Polymer-set function. So the view gets repopulated without any big hazzle.
https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#set-path
https://www.polymer-project.org/1.0/docs/devguide/properties.html#change-callbacks

Persistent store load callback in ExtJS 4.1.1

I need a way to catch the JSON response every time my datastore has loaded. My first try was to use the autoLoad property but the callback fires only on first load :
autoLoad: {
callback: function (records, operation) {
// do something with operation.response.responseText
}
}
So, I have decided to extend the load method :
load: function (options) {
var callback = options && options.callback;
return this.callParent([Ext.apply(options || {}, {
callback: function (records, operation) {
// do something with operation.response.responseText
if (callback) {
return callback.apply(this, arguments);
}
}
})]);
}
It works, but I wonder if the framework already provides a more elegant solution.
You can add a load listener to the store and grab the current request from it's proxy when the load event is fired.
var myStore = Ext.create("Ext.data.store", {
...whatever here
listeners: {
load: function(store){
store.getProxy().activeRequest.options.operation.response.responseText;
}
}
});
Thats if you want the response text specifically. If you want the response as a JSON object, you can use store.getProxy().reader.rawData; which is a little simpler

Firing a javascript function from a dynamically created button

Updated code and issue:
I am creating a test harness for my RPC server. Currently it consists of a page which immeadiately fires off an AJAX request to retrieve all functions on the server. Once that is returned it creates a list of buttons so I can click to test. Eventually I will add dialog boxes to test parameter passing to the functions but currently I want to just fire off the basic request when I click the button. The issue I am seeing is that the onclick function is always firing the last function in the list presumably because when the click is fired key is set to the last value in the array. I thought to pass button.innerHTML value but that too suffers that the last button.innerHTML is that of the final key.
What do I need to do to fire off the action correctly?
Here is the business end of the code:
$(document).ready(function() {
$.jsonRPC.setup({
endPoint: '//api.localhost/index.php'
});
$.jsonRPC.request('getExampleData', {
params: [],
success: function(result) {
for (var key in result.result) {
console.log(key+' => '+result.result[key]);
var button = document.createElement('button');
button.innerHTML = result.result[key];
button.onclick = function() { callRPCFunction(result.result[key]); return false; }
var foo = document.getElementById("page");
foo.appendChild(button);
}
},
error: function(result) {
console.log(result);
}
});
});
function callRPCFunction(target) {
$.jsonRPC.request(target, {
params: [],
success: function(result) {
console.log(result);
},
error: function(result) {
console.log(result);
}
});
}
Assignment to element.onClick will not work until the element is added to the DOM. You may call element.onClick(callRPCFunction(result.result[key])); after foo.appendChild(element);. That might work!
You may use jQuery's live() here, it was created for these purposes:
$(element).live('click', callRPCFunction(result.result[key])

How to handle multiple submit buttons using mootools?

In prototype you can use the following code.
var form = control.form;
new Ajax.Updater('result', form.action,
{ method: 'post',
parameters: form.serialize({submit: control.name})
}
);
return false;
Is there something like this in mootools? Simple but elegant ?
Yes, there is Form.Request
i.e.
(function($){
new Form.Request($('formID'), $('responseID'), {
onSuccess : function() {
//form submitted correctly
}
});
})(document.id);
where $('formID') is your form, and $('responseID') is the element that will hold the response (i.e. a response message)