How to Submit Form using JQuery from a Click Link

Posted on

This is an article written where the main point is described in the title of this article. It is about how to submit form using JQuery from the click event of a link. If there is a certain need of getting the content of the form where that content itself is going to be submitted further using HTTP Request POST but the trigger event is a click on a link, it is going to be quite tricky. Furthermore, if the content submitted is actually from any other file like HTML or even server-side script like JSP or PHP file page.

Below is the actual solution for the above situation mentioned by giving the link first for triggering the click event as an example :

<a id="my_link" href="target_file_for_further_processing"></a>

The next one is an example of a form which consists of just a form declaration defined in any of web page format. It can be only HTML or even a server-side script like PHP, or JSP file page as shown below :

<form id="my_form" action="target_file_for_further_processing" method="POST">
      ...
      ...
      ...
</form>

The sample of checkboxes can be anything from the manual definition or using a script either server-side script or client-side script to render the checkboxes definition. So, how is the solution for the above script in JQuery ?. First of all, let’s just check whether the JQuery has already been loaded or not. The article in this link which has the title of ‘How to check whether JQuery has been loaded or not’ can give a help.

If the JQuery library file has been loaded, try to define the following script inside the script tag :

$('#my_link').click(function () {
      $('#my_form').submit();
});

The above script is going to detect the click event which is triggered by an HTML Element with the id of ‘my_link’. After successfully detecting the click event on the link, it will then trigger a submit action on the form which is represented with the id of ‘my_form’.

I have tried using another method for submitting the form for an example in the above script, it will be replaced as follows :

$('#my_link').click(function () {
      $.post('target_file_for_further_processing',{"variable_name_passed":variable_name_in_form);
});

I have tried the above format but it seems it cannot done the submit process properly. The one which is working definitely is the one which is actually referring to the form defined and execute a submit function on it.  But remember to define the form first with the complete action and the method value which is  “POST”.

Leave a Reply