Andrew Kevich Andrew Kevich -4 years ago 548
Javascript Question

ExtJS 4 Form.submit() without sucess:true in answer

I have a form, which submitted like this:

form.submit({
url: '/postme',
waitMsg: 'Loading...',
method: 'POST',
success: function (form, action) {
console.log(action.response.responseText);
}
});


But! The main thing that in answer I don't have property
success: true
and cannot manage to add it. Is there is a way to make something like
callback
parameter in Ext.Ajax.request
instead of
success
? Or maybe there is a way to tell form.submit() that it must detect success in other responce parameter?

BTW: a cannot use Ext.Ajax.request because I have to pass multipart data from form (file upload).

Thanks in advance.

Answer Source

The API explains that you have to pass success: true for the success handler to be called. This is the doc for the submit method

@param {Object} options The options to pass to the action (see Ext.form.Basic.submit and Ext.form.Basic.doAction for details)

if (form.isValid()) {
    // Submit the Ajax request and handle the response
    form.submit({
        success: function(form, action) {
            Ext.Msg.alert('Success', action.result.message);
        },

        // If you don't pass success:true, it will always go here
        failure: function(form, action) {
            Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');
        }
    });
}

If you want to use a different property to indicate an error, you should look into http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.form.Basic-cfg-errorReader, you can configure the errorReader to read your property as you would like.

You can also route both your success and failure handlers to the same place and do determine it from the handler

Be sure to set standardSubmit:true so it doesn't get submitted with AJAX

Sample solution that will make your code feel a little bit less dirty

Ext.define('ns.my.CustomReader', {
    extend: 'Ext.data.reader.Reader', 
    alias: 'reader.ns-customreader',
    read: function(xhr) 
         var resp = Ext.JSON.decode(response.responseText, true);
         // Handle the case where response is not JSON too (unhandled server errror?)
         return {success: resp ? !!resp.id : false};
    }
});

Then, when you create the form, you can just use

 form : {
     errorReader: 'ns-customreader'
 }

I also noticed that you're not returning the record, which a reader should do according to the documentation, it may be that you just don't need it, but it'd be nice to satisfy the interface to keep your code in line with Ext-JS

The errorReader does not have to be a full-blown implementation of a Reader. It simply needs to implement a read(xhr) function which returns an Array of Records in an object with the following structure:

{ records: recordArray } // I think it needs success: boolean also.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download