Save form values from submit ajax call and use in another ajax call?

Hi,

I have a form that filters via ajax on submit. I also have a select outside the form for sorting. The select currently sends current form values + it’s value. However, if someone checks a box in the filter form without submitting, the sorting select still uses this value in the sorting. I would like to save the last from the form SUBMITTED values, not the current checked values and use them when sorting. How could I do that?

Code:

	form.submit(function(e){
		e.preventDefault();

		$.ajax({
			type: "POST",
			url: url,
			data: form.serialize(),
			dataType: "html",
			success: function(response){
				feed.empty().html(response);
			}
		});

	});

	$(document).on('change', 'select', function(){

		var self = $(this),
		    time = self.val();

		$.ajax({
			type: "POST",
			url: url,
			data: form.serialize() + time,
			dataType: "html",
			success: function(response){
				feed.empty().html(response);
			}
		});

	});

Hi,

You’ll need to save the submitted data in a variable to use in the second function.
Rather than using jquery’s serialize which returns a string, POST data is meant to be submitted as an object. You can add a serializeObject plugin to make this possible.

$.fn.serializeObject = function() {
  var o = {};
  var a = this.serializeArray();
  $.each(a, function() {
    if (o[this.name] !== undefined) {
      if (!o[this.name].push) {
        o[this.name] = [o[this.name]];
      }
      o[this.name].push(this.value || '');
    } else {
      o[this.name] = this.value || '';
    }
  });
  return o;
};

var lastSubmittedData = {};

form.submit(function(e){
  e.preventDefault();

  lastSubmittedData = form.serializeObject();

});

$(document).on('change', 'select', function(){
  lastSubmittedData['sort'] = $(this).val();
  
  // submit lastSubmittedData
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.