Extjs getting fields values from extended FormPanel - forms

The submit button for my formPanel works by using scope:this as it is an extended formPanela nd ext.getCmp(formid) doesn't work.
In my submit function, it successfully works using this.getForm().submit(....). However when trying to get the field values, this.getForm().getFields() doesn't work, flagging that it is not a function.
the buttons & handler function is nested within the formPanel setup.
Can anyone shed light on how to get the values in this manner?
Submit function:
{
text: 'Submit',
id: "submitBtn",
handler: this.submit,
scope: this
}
....
,submit : function(url, waitMsg) {
//this.getForm.getFields()
this.getForm().submit({
url: url
,scope: this
,waitMsg: 'Please wait'
,success: this.onSuccess
//,failure: this.onFailure
});
}

submit : function(url, waitMsg) {
//this.getForm.getFields() -- should work now
this.getForm().submit({
url: url
,scope: this
,waitMsg: 'Please wait'
,success: this.onSuccess
//,failure: this.onFailure
});
}.createDelegate(this)

I've resolved this by not using the submit action but by using a simple Ext.Ajax.request:
,submit : function() {
var data = this.getForm().getValues();
Ext.Ajax.request({
url: '...',
method: 'GET',
timeout:180000,
params: {
param1: Ext.encode(this.getForm().getValues())
}
.
})

Related

Ext.Direct File Upload - Form submit of type application/json

I am trying to upload a file through a form submit using Ext.Direct, however Ext.direct is sending my request as type 'application/json' instead of 'multipart/form-data'
Here is my form.
{
xtype: 'form',
api: {
submit: 'App.api.RemoteModel.Site_Supplicant_readCSV'
},
items: [
{
xtype: 'filefield',
buttonOnly: false,
allowBlank: true,
buttonText: 'Import CSV'
}
],
buttons:
[
{
text: 'Upload',
handler: function(){
var form = this.up('form').getForm();
if(form.isValid()){
form.submit({
waitMsg: 'Uploading...',
success: function(form, action){
console.log(action.result);
}
});
}
}
}
]
},
On the HTTP request, it checks to see if the request options is a form upload.
if (me.isFormUpload(options)) {
which arrives here
isFormUpload: function(options) {
var form = this.getForm(options);
if (form) {
return (options.isUpload || (/multipart\/form-data/i).test(form.getAttribute('enctype')));
}
return false;
},
getForm: function(options) {
var form = options.form || null;
if (form) {
form = Ext.getDom(form);
}
return form;
},
However, options looks like this
{
callback: function (options, success, response) {
jsonData: Object
action: "RemoteModel"
data: Array[1]
0: form
length: 1
__proto__: Array[0]
method: "Site_Supplicant_readCSV"
tid: 36
type: "rpc"
__proto__: Object
scope: constructor
timeout: undefined
transaction: constructor
}
And there is no direct form config, but it exists in jsonData.data[0]. So it doesn't set it as type multipart/form-data and it gets sent off as type application/json.
What am I doing wrong? Why isn't the form getting submitted properly?
Edit - I am seeing a lot of discussion about a 'formHandler' config for Ext.Direct? I am being led to assume this config could solve my issue. However I don't know where this should exist. I'll update my post if I can find the solution.
Solution - Simply adding /formHandler/ to the end of the params set the flag and solved my issue. Baffled.
Supplicant.prototype.readCSV = function(params,callback, request, response, sessionID/*formHandler*/)
{
var files = request.files;
console.log(files);
};
The method that handles file upload requests should be marked as formHandler in the
Ext.Direct API provided by the server side.
EDIT: You are using App.api.RemoteModel.Site_Supplicant_readCSV method to upload files; this method needs to be a formHandler.
I'm not very familiar with Node.js stack but looking at this example suggests that you may need to add /*formHandler*/ descriptor to the function's declaration on the server side.

Nette - {link!} macro can't handle already existing GET params in URL

I Use Nette 2 in my project and I also use .latte template system with AJAX.
Now I have jquery function (in template) that should generate GET request on the same destination but it should add some GET parameters after it.
This destination is initially rendered using one GET parameter, then some actions are made and during some of them AJAX loads some information from the same destination (just adds a couple of GET parameters).
Now I generate AJAX URL using .latte {link!} macro (exclamation mark stands for signal). This is now able to generate new URL with GET params appended to original one. But append is badly parsed, because there is &amp%3B in the URL instead of just &.
I have this code in my template:
{block content}
<h1 n:block=title>New Rule</h1>
{snippet rulesForm}
{form newRuleForm}
{$form}
<script type="text/javascript">
{foreach $form['rule']->containers as $i => $rule}
{include #jsCallback, id => $i, input => $rule['table']->name, link => tableChange}
{include #jsCallback, id => $i, input => $rule['column']->name, link => tableChange}
{/foreach}
</script>
{/form}
{/snippet}
{/block}
{define #jsCallback}
$('#{$control["newRuleForm"]['rule'][$id][$input]->htmlId}').on('change', function(){
alert('{$link}');
$.nette.ajax({
type: 'GET',
url: '{link {$link}!}',
data: {
'value': $(this).val(),
}
});
});
{/define}
How can I fix this problem so I can generate link which appends GET parameters correctly?
Thanks.
Best approach is to avoid generating inline Javascript. You can mark all those form controls by CSS class (eg. special-input), then you don't have to generate Javascript code in Latte iteration.
{snippet rulesForm}
<div data-link-table="{link tableChange!}"></div>
...
{/snippet}
$('.special-input').on('change', function () {
$.nette.ajax({
type: 'GET',
url: $('[data-link-table]').data('linkTable'),
data: {
value: $(this).val()
}
});
});
Maybe noescape modifier?
$.nette.ajax({
type: 'GET',
url: '{link {$link|noescape}!}',
data: {
'value': $(this).val(),
}
});

How to cancel likes on other site

When you click the Like button https://graph.facebook.com/object_id/likes calls.
To cancel the Like what should I do?
I tried the following:
<code>
<script>
function doLike(objectId) {
$.ajax({
url: 'https://graph.facebook.com/'+objectId+'/likes',
type: 'post',
data: {
access_token: '....'
}
});
}
function doCancel(objectId) {
$.ajax({
url: '???',
type: 'post',
data: {
access_token: '....'
}
});
}
</script>
<input onclick="doLike('...')">Like</button>
<input onclick="doCancel('...')">Cancel</button>
</code>
This drove me nuts. Firefox/Chrome and probably everything else apparently won't allow HTTP DELETE ajax calls unless the host has previously communicated during the current request. So $.ajax{(type: 'delete', ... )} works for YOUR server url host but not anything else.
The workaround is something like:
$.ajax({
url: "https://graph.facebook.com/" + FB_ACTION_ID,
type: 'post',
data: { access_token: ACCESS_TOKEN,
'method': 'delete',
'_method' : 'delete' }
})
If you're looking for an API which allows you to remove a Like of a Facebook page, this is not possible.
If you're looking for an API to remove a Like of an object (via URL) - you can make a HTTP DELETE request to /LIKE_INSTANCE_ID which is the ID returned to your app when you posted the Open Graph like - otherwise it's not possible
You should be able to "unlike" an object ID simply by doing a HTTP DELETE. Using your code, it'd look something like this:
function doCancel(objectId) {
$.ajax({
url: 'https://graph.facebook.com/'+objectId+'/likes',
type: 'delete',
data: {
access_token: '....'
}
});
}
Alternatively, use the Facebook Javascript SDK, in which you can simply do:
FB.api("/" + objectId + "/likes", 'delete', callback);
where callback is the function to call when the unlike operation is complete.

How to submit a form using JsonP in Sencha Touch 2?

I'm writing an application using Sencha Touch 2, it works just fine when accessed from web. The problem came when I built it for iPhone and changed the url from a local url (../services/myservice.php) to a remote url (http://remoteurl.com/services/myservice.php)
I started getting a crossdomain error:
**XMLHttpRequest cannot load http://example.com/services/userRegister.php?_dc=1336972603884. Origin http://localhost is not allowed by Access-Control-Allow-Origin.**
And I'd like to ask you if there is a way to submit a form using jsonp, so I don't have this problem anymore.
Here is my code for the form:
Ext.define('RegistroMovil.view.Register',{
extend: 'Ext.form.Panel',
xtype: 'register',
requires:[
'Ext.form.FieldSet',
'Ext.form.Email'
],
config: {
title: 'Register',
iconCls: 'user',
url: 'http://example.com/proys/congreso/services/userRegister.php',
items: [
...
And the code of the button that submits the form:
{
xtype: 'button',
text: 'Register',
handler: function(){
this.up('register').submit({
success: function(f, a){
alert('Your id: ' + a.id);
f.reset();
}
});
}
},
Thank you very much!
You are getting the above error because of cross-origin resource sharing policy.
On the tap event handler of submit button, you could use an Ext.Ajax.request(); but I feel that would also land up you getting the same error.
E.g
Ext.Ajax.request({
values : paramValues // values from form fields..
url: '.../test.php',
success: function(response) {
console.log(response.responseText);
}
failure: function(response) {
console.log(response.responseText);
}
});
So, it's better to write an Ext.util.JSONP.request() to handle a form submit.
Note that if you are retrieving data from a page that is in a domain
that is NOT the same as the originating domain of the running page,
you must use this class, because of the same origin policy.
E.g
Ext.util.JSONP.request({
params: paramValues // values from form fields..
url: '.../test.php',
callbackKey: 'callback',
scope: 'this',
success: function(response) {
console.log(response.responseText);
}
failure: function(response) {
console.log(response.responseText);
}
});

JSON object parsing error using jQuery Form Plugin

Environment: JQuery Form Plugin, jQuery 1.7.1, Zend Framework 1.11.11.
Cannot figure out why jQuery won't parse my json object if I specify an url other than a php file.
The form is as follows:
<form id="imageform" enctype="multipart/form-data">
Upload your image <input type="file" name="photoimg" id="photoimg" />
<input type="submit" id ="button" value="Send" />
</form>
The javascript triggering the ajax request is:
<script type="text/javascript" >
$(document).ready(function() {
var options = {
type: "POST",
url: "<?php $this->baseURL();?>/contact/upload",
dataType: 'json',
success: function(result) {
console.log(result);
},
error: function(ob,errStr) {
console.log(ob);
alert('There was an error processing your request. Please try again. '+errStr);
}
};
$("#imageform").ajaxForm(options);
});
</script>
The code in my zend controller is:
class ContactController extends BaseController {
public function init() {
/* Initialize action controller here */
}
public function indexAction() {
}
public function uploadAction() {
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = $_FILES['photoimg']['tmp_name'];
$im = new imagick($image);
$im->pingImage($image);
$im->readImage($image);
$im->thumbnailImage(75, null);
$im->writeImage('userImages/test/test_thumb.jpg');
$im->destroy();
echo json_encode(array("status" => "success", "message" => "posted successfully"));
}
else
echo json_encode(array("status" => "fail", "message" => "not posted successfully"));
}
}
When I create an upload.php file with the above code, and modify the url from the ajax request to
url: "upload.php",
i don't run into that parsing error, and the json object is properly returned. Any help to figure out what I'm doing wrong would be greatly appreciated! Thanks.
You need either to disable layouts, or using an action helper such as ContextSwitch or AjaxContext (even better).
First option:
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
And for the second option, using AjaxContext, you should add in your _init() method:
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('upload', 'json')
->initContext();
This will disable automatically disable layouts and send a json header response.
So, instead of your two json_encode lines, you should write:
$this->status = "success";
$this->message = "posted successfully";
and
$this->status = "fail";
$this->message = "not posted successfully";
In order to set what to send back to the client, you simply have to assign whatever content you want into view variables, and these variables will be automatically convert to json (through Zend_Json).
Also, in order to tell your controller which action should be triggered, you need to add /format/json at the end of your URL in your jQuery script as follow:
url: "<?php $this->baseURL();?>/contact/upload/format/json",
More information about AjaxContext in the manual.
Is the Content-type header being properly set as "application/json" when returning your JSON?