Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nabilunfarhanun's avatar

How to dry up this part of my code?

I am submitting two forms from same page with ajax. One is to create and another is to update. As they look very similar, my gut says their should be a way to dry up this form. But I am not quite getting it. can you please give me tips on how I can dry this up?

This is the first form,

<script type="text/javascript">
        $("#createForm").submit(function(e) {
            e.preventDefault();
            var form = $(this);
            var url = form.attr('action');
            $.ajax({
                    type: "POST",
                    url: url,
                    data: $('#createForm').serialize(),
                    success: function(data)
                    {
                        if(data=="success")
                        {
                            location.reload();
                        }
                        else
                        {
                            var html = "<ul>";
                            for(var dat in data)
                            {
                                for (var x in data[dat])
                                {
                                    html = html+"<li>"+data[dat][x]+"</li>";
                                }
                            }
                            html = html+"</ul>";
                            $("#createErrors").attr("class","alert alert-danger");
                            $("#createErrors").html(html);
                        }
                    }
                });
        });
    </script>

This is the second form,

<script type="text/javascript">
        $("#updateForm").submit(function(e) {
            e.preventDefault();
            var form = $(this);
            var url = form.attr('action');
            $.ajax({
                    type: "POST",
                    url: url,
                    data: $('#updateForm').serialize(),
                    success: function(data)
                    {
                        if(data=="success")
                        {
                            location.reload();
                        }
                        else
                        {
                            var html = "<ul>";
                            for(var dat in data)
                            {
                                for (var x in data[dat])
                                {
                                    html = html+"<li>"+data[dat][x]+"</li>";
                                }
                            }
                            html = html+"</ul>";
                            $("#updateErrors").attr("class","alert alert-danger");
                            $("#updateErrors").html(html);
                        }
                    }
                });
        });
    </script>
0 likes
4 replies
RomainB's avatar

Well.

As I see all your code is exactly the same except the ID in your html page.

Just set the same ID #myForm instead of #createForm and #updateForm and #errors instead of #createErrors and #updateErrors and you can call the same Ajax function with two forms.

Then you can create a submit-form.js and include it in your two html pages.

<script type="text/javascript">
    $("#myForm").submit(function(e) {
        e.preventDefault();
        var form = $(this);
        var url = form.attr('action');
        $.ajax({
            type: "POST",
            url: url,
            data: $('#myForm').serialize(),
            success: function(data)
            {
                if(data=="success")
                {
                    location.reload();
                }
                else
                {
                    var html = "<ul>";
                    for(var dat in data)
                    {
                        for (var x in data[dat])
                        {
                            html = html+"<li>"+data[dat][x]+"</li>";
                        }
                    }
                    html = html+"</ul>";
                    $("#errors").attr("class","alert alert-danger");
                    $("#errors").html(html);
                }
            }
        });
    });
</script>
erikverbeek's avatar
Level 9

@RomainB Giving the forms the same ID won't work as they are both on the same page. jQuery would always just pick the first form as ID's are supposed to be unique per page.

@nabilunfarhanun You could wrap the submit in a function, with the action name as it's parameter. That way you could add it to both forms dynamically.

Two other small cleanups:

  • The form and url variables are only used once, so they can be inlined as url: $(this).attr('action')
  • You can use html += "<ul>" to add strings to your html variable instead of html = html + "<ul>"
function submitForm(action){
    var form = "#" + action + "Form";
    var errors = "#" + action + "Errors";

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

              $.ajax({
                      type: "POST",
                      url: $(this).attr('action'),
                      data: $(form).serialize(),
                      success: function(data)
                      {
                          if(data=="success")
                          {
                              location.reload();
                          }
                          else
                          {
                              var html = "<ul>";

                              for(var dat in data)
                              {
                                  for (var x in data[dat])
                                  {
                                      html += "<li>" + data[dat][x] + "</li>";
                                  }
                              }

                              html += "</ul>";

                              $(errors).attr("class","alert alert-danger");
                              $(errors).html(html);
                          }
                      }
                  });
          });
    }

    submitForm('create');
    submitForm('update');
1 like
clevonnoel's avatar

Move away from JQuery. This will save you a ton using Vue/React

1 like
RomainB's avatar

@erikverbeek > Woops. Miss that part.

@clevonnoel > Agree with you but everybody makes with his capabilities.

@nabilunfarhanun > What I would do in this case. Filter "accepted forms" with a simple class .thisFormCanCallAjax on forms, and errors in class instead of unique id. And then just retrieve the ID of form which is submitted with form.attr('id')

$("form.thisFormCanCallAjax ").submit(function(e) {
    e.preventDefault();
    var form = $(this);
    var formId = form.attr('id');
    var url = form.attr('action');
    $.ajax({
        type: "POST",
        url: url,
        data: $(formId).serialize(),
        success: function(data)
        {
            if(data=="success")
            {
                location.reload();
            }
            else
            {
                var html = "<ul>";
                for(var dat in data)
                {
                    for (var x in data[dat])
                    {
                        html = html+"<li>"+data[dat][x]+"</li>";
                    }
                }
                html = html+"</ul>";
                $(formId +" .errors").attr("class","alert alert-danger");
                $(formId +" .errors").html(html);
            }
        }
    });
});

Please or to participate in this conversation.