Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a function as data with jQuery ajax

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?

like image 907
user1032531 Avatar asked Mar 25 '18 20:03

user1032531


People also ask

Can we call function in AJAX?

Even with async: false , your function needs to return the return value of the $. ajax() call. Consider returning the actual observable object that you get from an async $. ajax() call and working with that, instead of running synchronous AJAX requests.

How can a function return a value in AJAX?

ajax({ async: true, contentType: 'application/json; charset=utf-8', type: "POST", dataType: 'json', data: JSON. stringify(arrays), url: "MyHandler. ashx", success: function (result) { b = true; }, error: function () { alert('Error occurred'); } });

How do you call a method in AJAX?

I will use the jQuery. ajax() or $. ajax() method to call the C# method (WebMethod).

What is Ajax() function in jQuery?

In the root of jQuery Ajax is ajax () function. This function is used to perform HTTP requests which are by default asynchronous. The syntax for using this function is: $.ajax ({name:value, name:value,...

How to load data using Ajax in jQuery?

JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application. This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load () method to do the job − URL − The URL of the server-side resource to which the request is sent.

How to make Ajax request using jQuery?

In the root of jQuery Ajax is ajax () function. This function is used to perform HTTP requests which are by default asynchronous. The syntax for using this function is: $.ajax ( {name:value, name:value, ... }) The parameters specifies one or more name/value pairs for the AJAX request. Possible names/values in the table below:

Which method do all jQuery Ajax methods use?

All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.


1 Answers

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.

like image 79
Jannes Botis Avatar answered Sep 19 '22 15:09

Jannes Botis