We help IT Professionals succeed at work.

http web api get from html form

ITsolutionWizard
on
95 Views
1 Endorsement
Last Modified: 2019-01-28
i have very simple web api that have get method, and it will accept 20 parameters.
On the consuming side, I will have html form and each <input id='name'> is actually the web api parameter name.

My question is: using javascript, how to post all 20 html input value in one shot, i assume there is a way to get the entire input value by looping all items inside of html form.
because each html id name is same as api parameter name.

Thanks
Comment
Watch Question

CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Zakaria AcharkiAnalyst Developer
CERTIFIED EXPERT
Distinguished Expert 2018

Commented:
how to post all 20 html input value in one shot,

Hi, you're searching for the jQuery built-in function "serialize()" that encode a set of form elements as a string for submission, it will do all the job for you no need for any loop, all you need is to put your inputs inside a form then call it like :


var form = $('#my_awesome_form');
$.get('api_url', form.serialize(), function(response){
    //Success Callback
});

Open in new window


Working sample
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
There are two main ways for sending data to an API

URL encoded
field1=value1&field2=value2&field3=value3...

Open in new window


JSON
{
   "field1":"value1",
   "field2":"value2",
   "field3":"value3",
...
}

Open in new window


i have very simple web api that have get method
This is not advisable for a number of reasons (rather use POST)
1. If you use GET the request is no longer idempotent
2. You can run into size limitations using GET
Rather send the data in the body of a POST
For URL encoded you can retrieve the values using this function

function getPOST($fields, $force = true)
{
  $data = [];
  foreach($fields as $f) {
    if (isset($_POST[$f])) {
      $data[$f] = $_POST[$f];
    }
    else {
      if ($force) return false;
    }
  }
  return $data;
}

Open in new window

and you call it like this

$data = getPOST(['field1','field2','field3'], false);

Open in new window

Or like this
$data = getPOST(['field1','field2','field3']);

Open in new window

The second invocation is used when you want to ensure that all the fields in the specified array are present in the $_POST - in the first it will extract the ones it finds but won't return a false value if a value is missing. The second version is more commonly used.
For JSON
function getJSON($fields, $force = true)
{
  $data = [];
  $json = file_get_contents('php://input');
  $post = json_decode($json);
 
  if (!$post && !is_array($post) && !is_object($post)) return false;

  if ($force) {
    foreach($fields as $f) {
      if (is_array($post) && empty($post[$f])) return false;
      if (empty($post->{$f})) return false;
    }
  }
  
  return $post;
}

Open in new window

And you would use it in the same way as the getPOST();

Sample here shows the above functions in action here

Author

Commented:
Zakaria Acharki: how to download the codes. I tried fiddle and it does not allow me to download everything.

Author

Commented:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>

    <script>
        $("#call-api").click(function () {
            var form = $('#my_awesome_form');

            //Just to demonstrate
            alert(form.serialize());

            $.get('api_url', form.serialize(), function (response) {
                //Success Callback
            })
        });
    </script>
</head>
<body>
    <form  id="my_awesome_form" runat="server">
       
  <label for="ch1">First name :</label>
  <input type="text" name="first_name" />
  <br>
  <label for="ch1">Last name :</label>
  <input type="text" name="first_name" />
  <br>
  <label for="ch1">Email :</label>
  <input type="text" name="email" />
 
<br /><br />    
  <button type='button' id='call-api'>Call API</button>
    </form>
</body>
</html>
Zakaria AcharkiAnalyst Developer
CERTIFIED EXPERT
Distinguished Expert 2018

Commented:
There's no much code it was just a basic sample with jQuery.

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
	<form id="my_awesome_form">
	  <label for="ch1">First name :</label>
	  <input type="text" name="first_name">
	  <br>
	  <label for="ch1">Last name :</label>
	  <input type="text" name="first_name">
	  <br>
	  <label for="ch1">Email :</label>
	  <input type="text" name="email">
	 
	  <br><br>
	  <button type='button' id='call-api'>Call API</button>
	</form>
	<script type="text/javascript">
		$(function(){
			$("#call-api").click(function(){
				var form = $('#my_awesome_form');
			  
			  //Just to demonstrate
			  alert( form.serialize() );
			  
			  $.get('api_url', form.serialize(), function(response){
			    //Success Callback
			  })
			});
		});
	</script>
</body>
</html>

Open in new window


If not that what you want then want exactly to download?

Author

Commented:
It works but I prefer to use Id inside of <input> if possible.

 <input type="text" name="first_name" id="first_name">
Zakaria AcharkiAnalyst Developer
CERTIFIED EXPERT
Distinguished Expert 2018

Commented:
Not sure what you mean? but if you want to replace the name with the id then you could use :

var data = {};
$('input', form).each(function(){
    data[this.id] = this.value;
});

Open in new window


And passe the "data" object to the ajax request.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.