Avatar of ITsolutionWizard
ITsolutionWizard
Flag for United States of America asked on

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
HTMLJavaScriptjQuery

Avatar of undefined
Last Comment
Zakaria Acharki

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
hielo

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Zakaria Acharki

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 Hansen

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
ITsolutionWizard

ASKER
Zakaria Acharki: how to download the codes. I tried fiddle and it does not allow me to download everything.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ITsolutionWizard

ASKER
<!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 Acharki

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?
ITsolutionWizard

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

 <input type="text" name="first_name" id="first_name">
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Zakaria Acharki

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.