0

I have 10 AJAX queries with the same parameters.

$.ajax({
    global: false,
    type: 'POST',
    url: value,
    dataType: 'html',
    data: {
        firstname: $("#firstname").val(),
        lastname: $("#lastname").val(),
        surname: $("#surname").val(),
        age: $("#age").val(),
        ...
        sex: $("#sex").val()
    },
    success: function(result) {
        console.log(result);
    },
    error: function (request, status, error) {
        serviceError();
    }
});

How I can unify these parameters not to write them 10 times because I have 76 parameters?

diank
  • 628
  • 2
  • 11
  • 19
  • You can do it before your ajax call. – IsraGab Apr 10 '16 at 06:57
  • @IsraGab okay, but how. Can you show me? – diank Apr 10 '16 at 06:58
  • You want to pass all fields within a form, you can use `data: $('#form').serialize();` If not, you can prepare a string with all parameters in the form of `data : $('#form').serialize() + "&par1=1&par2=2&par3=232"` just loop through the available params and preare a string – jeetaz Apr 10 '16 at 07:01
  • How looks your html code of your params? – IsraGab Apr 10 '16 at 07:01
  • The field names are all very uniform so you could easily use a one-line loop to add all 76 properties to an object before the $.ajax() call. – nnnnnn Apr 10 '16 at 07:03
  • @nnnnnn for example I gave them numbers, they have different names. – diank Apr 10 '16 at 07:17
  • @jeetaz I update my code, did you think your idea will do that I want ? – diank Apr 10 '16 at 07:44
  • @diank better to post entire html if the answer provided in the post by XtraSimplicity don't work for you. Yes, to your question. – jeetaz Apr 10 '16 at 08:07
  • `$(this).serialize()` if you're using `$('form').submit(function(){...});` – Yash Karanke Dec 24 '19 at 04:32

2 Answers2

1

First of all, create a single class for each of your param in your html something like:

<input type="text" id="param1" class="params"/>
<input type="text" id="param2" class="params"/>
<input type="text" id="param3" class="params"/>

Then in your JS:

 var callAjax = function(){    
    data = {};
    for(var i = 0; i < $('.params').length; i++){
        data[$('.params')[i].id] = $('.params')[i].val(); 
    }
    $.ajax({
            global: false,
            type: 'POST',
            url: value,
            dataType: 'html',
            data: data,
            success: function(result) {
                console.log(result);
            },
            error: function (request, status, error) {
                serviceError();
            }
        });
        }
IsraGab
  • 4,819
  • 3
  • 27
  • 46
-1

Add your value in array variable then pass to data

lakhvir kumar
  • 255
  • 2
  • 10