14

To reduce duplicated script, I created the following plugin, and it works as long as data is left as is.

$.fn.myValid = function(rules, options) {
    this.validate({
        rules: rules.rules,
        messages: rules.messages,
        submitHandler: function(form) {
            var o = Object.assign({},{
                type:'POST',
                url:null,
                data: $(form).serializeArray(),
                dataType: 'json',
                success: function (rsp){
                    //Instead of reloading page, do dynamicly
                    $.unblockUI();
                    alert('record submitted')
                    location.reload();
                },
                error: function (xhr) {
                    $.unblockUI();
                    alert(xhr.responseJSON.message);
                }
                }, options);
            //if (typeof o.data === "function") o.data=o.data(form);
            $.blockUI();
            $.ajax(o);
        }
    });
};

If data needs to be changed, I cannot simply return something like $(form).serializeArray().concat($('#common-inputs').serializeArray(form)) because form is not yet defined, so instead I thought returning a function would work. When ajax is fired, however, data is a function, and not a string, array, or plain object, so data is not sent to the server.

$('#help-form').myValid(validObj.common, {url:'ajax.php','data': function(form){
    console.log('this is never executed);
    return $(form).serializeArray().concat($('#common-inputs').serializeArray(form))
}});

As a workaround, I included o.data=o.data(form); (is commented out in above script) to execute the function to return results, and it works as desired. I expect, however, it is more of a hack, and there is a correct way to do this.

What is the proper way to use a function as data with jQuery ajax?

Will the solution be different for other properties such as url, success, etc?

2
  • 1
    As a solution for me I've done the following: I have a custom ajax wrapper and at the callback an object with functions to execute but I don't send the function, I have the functions defined in the App object and just send them as strings and evaluate them in the success event using the apply function. I have a github with the wrapper, It's a little outdated but I think you can see the ideea. Maybe you can apply the logic to your plugin github.com/sabbin/JQPS-Framework Commented Mar 26, 2018 at 8:44
  • @Sabbin Thanks for your suggestion. Yes, I see how this could work, but feel there should be a more appropriate solution. Commented Mar 26, 2018 at 22:37

3 Answers 3

5
+25

You can use beforeSend callback to set the data value:

beforeSend: function( xhr, settings ) {
    this.data = $(form).serialize(); // or settings.data = $(form).serialize();
}, 

Same way you can modify url and success callbacks:

this.url = 'new-url';
this.success = newSuccessCallback;

Similar question

Note this does not work for GET requests, but POST should work just fine.

Sign up to request clarification or add additional context in comments.

Comments

2

Your first question: What is the proper way to use a function as data with jQuery ajax?

Function can be used to create any type of data as long as you are going to return the data in the function call. As with jquery ajax, this would be a callback function and you call it whenever you need it.

# Example

function formData( form ) {
    // do anything
    return form.serialize();
}

var request = $.ajax({
    // set properties
    data: formData.call( context, form );
});

Will the solution be different for other properties such as url, success, etc?

For the success callback, use the .done() method or .fail() method for error

And url:

function getFormURL( form ) {
    return form.attr('action');
}

url: getFormURL.call( context, .form );

Comments

0

If you are to want to pass a dynamic parameters to remote api , the code as follows

$.ajax({
    uri: '/foo',
    ...,
    data: function() {
        param1: function() {
            return 'foo';
        },
        param2: function() {
            return $('input[name='bar']').val();
        }
    }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.