0

I have a form that I'm adding to with jquery .attr values and then call submit:

$form.attr("method", "POST");
$form.attr("action", "test.jsp");
$form.attr("target", "blank");
$form.submit();

I was wondering if there is a way for me to get the response back from the jsp file that I call?

something like

$form.submit().response?

Thanks

Jack_Frost
  • 169
  • 2
  • 8
  • Only if you submit using ajax, otherwise current page and it's code is gone when whatever server action returns a new page or reloads current one. What exactly are you wanting to accomplish? Code in the new page can be used to do things also in current one since it appears you are opening a new tab also – charlietfl Aug 10 '20 at 00:00
  • In [this](https://stackoverflow.com/a/4113258/10606400) answer check section `"Ajaxifying an existing form"` that will work for you. – Swati Aug 10 '20 at 08:04

1 Answers1

0

If you are looking to obtain a response without refreshing the page, you need to perform an AJAX request. This can be performed by doing:

$(function(){
    $( "form" ).on( "submit", function( event ) {
        event.preventDefault();

        // If you want to serialze the form, you can use $(this).serialize() or $("form").serialize();
        $.post(
            '/test.jsp',
            $(this).serialize(),
            function(response) { console.log('response was:',response); }
        );

        // OR if you want to specify each form element
        $.post(
            '/test.jsp',
            {
                name: $('#name').val(),
                email: $('#email').val(),
            },
            function(response) { console.log('response was:',response); }
        );

    });
});

forloops
  • 329
  • 1
  • 9
  • Sorry, am pretty new to javascript and jquery in general. How could I add the form to the body of the post request? – Jack_Frost Aug 10 '20 at 01:29
  • I've updated the answer to show you 2 different ways (only use 1 of them, not both). – forloops Aug 10 '20 at 16:43
  • You'll find the first version using $(this).serialize(). That will take your form and add the form (serialize has some limitations. check the docs at: https://api.jquery.com/serialize/). In the second version, you would manually put in the form data you want to pass. In this example, I assumed you had 2 fields; one with an ID of 'name', and another with an ID of 'email'. Both options are equally correct – forloops Aug 10 '20 at 16:50