http web api get from html form

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
LVL 1
ITsolutionWizardAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
You can give all those 20 elements/items a common class and when you are ready to process them just execute a jquery selector for the class that you chose --ex:
<input id='name' class="for-api">
<input id='email'>
<input id='phone' class="for-api>

let data={};

// this will select only id="name" and id="phone".  id="email" will be skipped because it does not have the "for-api" class.
$(".for-api").each(function(){
  data[$(this).attr("id")] = $(this).val();
});
console.log( data );//should reveal something like {"name":"...", "phone":"..."} which you can send in an ajax request

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Zakaria AcharkiAnalyst DeveloperCommented:
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
Julian HansenCommented:
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
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

ITsolutionWizardAuthor Commented:
Zakaria Acharki: how to download the codes. I tried fiddle and it does not allow me to download everything.
ITsolutionWizardAuthor 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 DeveloperCommented:
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?
ITsolutionWizardAuthor 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 DeveloperCommented:
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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.