Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send html form via post to webservice

Tags:

html

post

forms

I'm very very new on HTML5 development and this question could be very silly but I've found an answer for it (or I've searched very well).

I want to send a form to a web service via post (I don't want to show all fields in URL).

I have two question:

  1. How must I named forms fields? If I trying to send an userName I think I have to put this test as ID to the field which will held that value.
  2. And this is because I'm so curious. Which is the post message content which is sent to web service?

This is an example that I've found searching Internet:

 <FORM action="http://somesite.com/prog/adduser" method="post">
    <P>
    <LABEL for="firstname">First name: </LABEL>
              <INPUT type="text" id="firstname"><BR>
    <LABEL for="lastname">Last name: </LABEL>
              <INPUT type="text" id="lastname"><BR>
    <LABEL for="email">email: </LABEL>
              <INPUT type="text" id="email"><BR>
    <INPUT type="radio" name="sex" value="Male"> Male<BR>
    <INPUT type="radio" name="sex" value="Female"> Female<BR>
    <INPUT type="submit" value="Send"> <INPUT type="reset">
    </P>
 </FORM

I think I will need those ids to get those values while processing them on web service, isn't it?

like image 340
VansFannel Avatar asked Oct 14 '25 18:10

VansFannel


1 Answers

It depends, you could do a post to a page with a redirect (in .NET you would handle it this way):

<form action="http://myurl/postpage.ashx" method="post">
    <input name="forename" />
    <input name="surname" />
    <input type="submit" value="Submit" />
</form>

And then pick this up in the server side script at postpage.ashx using:

string forename = Request["forename"];
string surname = Request["surname"];

You could also use jQuery to make an ajax call to the same page using the following:

var forename = $("input[name=\"forename\"]").val();
var surname = $("input[name=\"surname\"]").val();

$.ajax({
    url: "http://myurl/postpage.ashx",
    type: "POST",
    async: true, // set to false if you don't mind the page pausing while waiting for response
    cache: false,
    dataType: "json",
    data: "{ 'forename': '" + forename + "', 'surname': '" + surname + "' }",
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        // handle your successful response here
    },
    error: function(xhr, ajaxOptions, thrownError) {
        // handle your fail response here
    }
});

You would handle the post in the server side code the same way. The key thing to note here is that whatever you enter as the name attribute of your input element is what will get POSTed as a key/value pair to your receiving URL.

like image 122
Paul Aldred-Bann Avatar answered Oct 17 '25 11:10

Paul Aldred-Bann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!