Sanjeev Singh
Sanjeev Singh

Reputation: 4066

How to get values from posted html form using javascript

I have two html forms and I am posting input data from one html form to another html form.I want to retrieve values of variables that was posted using form 1 on the form 2.

<form name ="form1" id ="form1" method ="post" action = "form2.html>
   <input id ="sendToForm2" type ="hidden" value ="send this to form2"/>
</form>

My question is how to get the value of the hidden variable sendToForm2 on form 2 once it is posted from form 1 to form 2 using javascript.

Upvotes: 3

Views: 4057

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67080

You can't use POST method because with a plain HTML page you do not have HTTP headers but HTML page code itself and URL (with query string).

What you can do is to use GET instead of POST then parse query string to extract them:

<form name ="form1" id ="form1" method ="GET" action = "form2.html>
   <input id ="sendToForm2" type ="hidden" value ="send this to form2"/>
</form>

Then in your form2.html you can use this function (from this post on SO) to parse query string:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Now (let me use jQuery) you can access them with this:

<form ...>
   <input id ="sentFromForm1" type ="hidden" value =""/>
</form>

</script>
    $("#sentFromForm1").val(getParameterByName("sendToForm2"));
</script>

Upvotes: 2

Related Questions