skip to Main Content

I am using AJAX to process my form data. I have to write multiple functions for multiple form. But I was thinking if I could use a single ajax function for multiple forms from different pages. For example, currently I am using it like this:

// Update Password
$('#updPass').click(function() {
  var form = document.updPass;
  var dataString = $(form).serialize();
  $.ajax({
    type: 'POST',
    url: 'processes/settings.php',
    data: dataString,
    cache: true,
    beforeSend: function(){
      $('.message').hide();
      $("#updPass").val('Please wait...');
    },
    success: function(html){
      $("#updPass").val('Save');
      $('.message').html(html).fadeIn();
    }
  });
  return false;
});

// Add New Room
$('#addRoom').click(function() {
  var form = document.addRoom;
  var dataString = $(form).serialize();
  $.ajax({
    type: 'POST',
    url: 'processes/rooms.php',
    data: dataString,
    cache: true,
    beforeSend: function(){
      $('.message').hide();
      $("#addRoom").val('Please wait...');
    },
    success: function(html){
      $("#addRoom").val('Save');
      $('.message').html(html).fadeIn();
    }
  });
  return false;
});

But I want to use it like this:

// Perform action
$('#addNew').click(function() {
  var form = document.addNew;
  var dataString = $(form).serialize();
  var formFieldToIdentify = "Take input from 1 hidden form field and store here";
  $.ajax({
    type: 'POST',
    if(formFieldToIdentify == 'password'){
      url: 'processes/settings.php',
    }else{
      url: 'processes/rooms.php',
    }
    data: dataString,
    cache: true,
    beforeSend: function(){
      $('.message').hide();
      $("#addNew").val('Please wait...');
    },
    success: function(html){
      $("#addNew").val('Save');
      $('.message').html(html).fadeIn();
    }
  });
  return false;
});

How to obtain that formFieldToIdentify variable from the form here? If I am able to get it I can use it easily. If I collected the form values separately the job would have been done. But here, I am using the serialize method and hence unable to separately get this form field value.

3

Answers


  1. As an option you can create an object where you store your urls and then select required url by key:

    var urls = {
        addNew: 'processes/rooms.php',
        someUrl: 'processes/file1.php',
        //...
    };
    
    $('#addNew').click(function() {
      var form = document.addNew;
      var dataString = $(form).serialize();
      $.ajax({
        type: 'POST',
        url: urls.addNew,
        data: dataString,
        cache: true,
        beforeSend: function(){
          $('.message').hide();
          $("#addNew").val('Please wait...');
        },
        success: function(html){
          $("#addNew").val('Save');
          $('.message').html(html).fadeIn();
        }
      });
      return false;
    });
    

    Another option: you can define urls in form‘s action attribute:

    <form action="/file.php" method="POST">
    

    In your script:

    $('#addNew').click(function() {
      var form = document.addNew;
      var dataString = $(form).serialize();
      $.ajax({
        type: 'POST',
        url: $(form).attr("action"),
        data: dataString,
        cache: true,
        beforeSend: function(){
          $('.message').hide();
          $("#addNew").val('Please wait...');
        },
        success: function(html){
          $("#addNew").val('Save');
          $('.message').html(html).fadeIn();
        }
      });
      return false;
    });
    
    Login or Signup to reply.
  2. Previus answer is good too, I just wanted to clear that you cant send data to multiple urls with one function.

    For sending data to multiple pages you need to created nested functions in ajax, which will start all functions with same button clicked.

    But you can get values from multiple forms in same page or in different pages without changing function each time like following example.

    $('#updPass').click(function(e){
        e.preventDefault();
        var url = $(this).attr('action'); //auto detect action url
        var results = [];
        $('form').each(function(){
            results.push($(this).serialize());
            // serializeArray(); is much more suitable
            //results.push($(this).serializeArray());
        });
        $.ajax({
            'url': url,
            'type': 'POST', // type not method
            'data': {data: JSON.stringify(results)},
            'dataType': 'html',
            'success': function (data) {
                console.log(data);
            }
        });
    });
    

    Note you need to specify url in form action

    Server side in php part,

    var_dump(json_decode($_POST));
    var_dump($_POST);
    
    Login or Signup to reply.
  3. So you told me that you didn’t get my idea that I was told you.
    So this is the brief answer of my idea.
    Suppose you have three forms in different pages or in a same page like this –

    <form id='registration_form'>
        form fields like input, radio buttons, checkboxes, textareas etc
        <input type='submit' class='form_btn'>
    </form>
    
    //***************************
    <form id='login_form'>
        form fields like input, radio buttons, checkboxes, textareas etc
        <input type='submit' class='form_btn'>
    </form>
    //***************************
    <form id='update_form'>
        add form fields like input, radio buttons, checkboxes, textareas etc
        <input type='submit' class='form_btn'>
    </form>
    //****************************  
    

    Each form has unique id attribute and a common class for button.

    <script>
        // create variables
        let process_url, method, form, dataString;
        // for submit button.
        let form_btn = document.getElementsByClassName('form_btn');
    
        // AJAX code to process the form data.
        function your_ajax_function(){
           $.ajax({
        type: method,
        url: process_url,
        data: dataString,
        cache: true,
        beforeSend: function(){
          // fetch those ID's and classes in function set_dynamic_variables()
          // and then use here.
        },
        success: function(html){
          // fetch those ID's and classes in function set_dynamic_variables()
          // and then use here.
        }
      });
    
        }
    
        function set_dynamic_variables(e){
            form = //write your own code to fetch the form-ID in which e is present.
    
            switch (form) {
    
                case 'registration_form':
                    process_url = './process/registration_form.process.php';
                    method = 'POST';
                    dataString = $('#' + form).serialize();    
                    break;
    
                case 'login_form':
                    process_url = './process/login_form.process.php';
                    method = 'POST';
                    dataString = $('#' + form).serialize();               
                    break;
    
                case 'update_form':
                    process_url = './process/update_form.process.php';
                    method = 'POST';
                    dataString = $('#' + form).serialize();                
                    break;
    
                    default:
                    // statements_def
                    break;
            } // switch()
            } // if
    
    // adding the event-listener for all the submit button of forms
    for(let i=0; i< submit_btn.length; i++){
        submit_btn[i].addEventListener('click', function(e) {
            e.preventDefault();
            set_dynamic_variables(e);
            your_ajax_function();
        }, false);
    
    
    </script>
    

    @Golden Friendship Site So, This is what I told you in discussion.
    and my code will be able to work correctly even if you put all form in a same page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search