Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

211
Vistas
How to call same ajax function on multiple pages with different url?

Hı gusy! I am trying to drop ajax post function to one and use it on whole site with different url on each page.

This is my original function and how it works :

<button type="button"class="submit">send</button>

$(document).ready(function (){
   $('.submit').on("click", function(e){
        e.preventDefault();
      var form = $(this).closest('form');
        $.ajax({
            type:'POST',
            url:'ActionPage.php',
            data:form.serialize(),
            success:function(vardata){
             var json = JSON.parse(vardata);
              if(json.status == 101){
               alert(json.msg);
                window.location.replace("/");
                } else {
                 alert(json.msg);
                 console.log(json.msg);
                }
            }
        });
    });
});

Exp: I have multiple forms in some pages, so I need to use $(this).closest('form'); to post each form.

This is what I want to do, original function will be in scripts and included in page :

  function ajaxLoader(url) {
    var form = $(this).closest("form");
        $.ajax({
        type:"POST",
        "url" : url, 
        data:form.serialize(),
          success:function(vardata){
            var json = JSON.parse(vardata);
            if(json.status == 101){
              alert(json.msg);
              window.location.replace("/");
            } else {
              alert(json.msg);
              console.log(json.msg);
            }
        }
    });
}

And on the page I want to call it like this :

$(document).ready(function (){
  $('.submit').on("click", function(e){
      e.preventDefault(); 
      ajaxLoader("ActionPage.php", true);
  });
});

I getting undefined message on all cases when I click send button, when I move $(this).closest("form"); to second function then I get undefined form error.

I have searched on site there are similar question but none of them has usefull answer. example : this one

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

$(this).closest("form"); does not resolve to the closest form element of the clicked button when inside your function `ajaxLoader'. Do a 'console.log( this )' in that function.

You can either inject the form directly into your function:

$(document).ready(function (){
  $('.submit').on("click", function(e){
      e.preventDefault(); 
      let form = $(this).closest("form");
      ajaxLoader("ActionPage.php", form);
  });
});

function ajaxLoader(url, form) {
  ...
}

Or you could use the action attribute of your form and hook to the submit event of the form directly:

$('form').on('submit', function( e ) {
    e.preventDefault();
  const $form = $(this);
  const url = $form.attr('action');
  const data = $form.serialize();
  const method = $form.attr('method');
  $.ajax({
    url: url,
    data: data,
    success: function(response) {
        
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="actionpage.php" method="POST">
  <button type="submit">
    submit
  </button>
</form>

about 4 years ago · Juan Pablo Isaza Denunciar

0

How this is scoped is based on the context of how it is called. You can change what this is with call/apply/bind. Basic example below.

function ajaxLoader(url) {
  console.log(this, url)
  var form = $(this).closest("form");
  console.log(form[0]);
}


$(document).ready(function (){
  $('.submit').on("click", function(e){
      e.preventDefault(); 
      ajaxLoader.call(this, "ActionPage.php");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="foo">
  <button class="submit">Click</button>
</form>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda