1

From this earlier thread I thought I learned that form data could be sent by POST method using javascript submit() command. But I can't get it to work. This demo doesn't make obvious sense with respect to purpose but bear with me. I just wanted to test this specific command which doesn't seem to work for me. Can you please help me? Clicking the regular submit button sends the post data ok but activating the javascript via the link does not.

<html><body>

<?php
$self = $_SERVER['PHP_SELF'];
$posttext = file_get_contents('php://input');
echo "Received input: ".chr(34).$posttext.chr(34)."<br><br>";
echo "<form id='test' action='{$self}' method='post'>";
?>
Please fill in the fields with any text:<br><br>
foo: <input type="text" name="foofield"><br><br>
bar: <input type="text" name="barfield"><br><br>
<input type="submit" value="Submit button works"><br><br>
<a href="" id="submitlink">Submitting by JS not working – why?</a>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
$(document).ready(function(){
$("a#submitlink").click(function(){
alert("Yes, the link has been clicked. It is not that.");
$("form#test").submit();
});
});
});
</script>
</body></html>
danbae
  • 319
  • 1
  • 5
  • 18

1 Answers1

3

You need to: event.preventDefault(); the default behaviour from the <a>. The problem is if you don't do that, the page reloads cause that is what the <a> tag does. So even you submit the data you also refresh the page where the submitted data gets lost.

$("a#submitlink").click(function(event){
    event.preventDefault();
    $("form#test").submit();
});

The other solution is to add # in the href of the <a> tag like:

<a href="#" id="submitlink">Submitting by JS not working – why?</a>

this will also prevent the <a> tag from doing a refresh.

caramba
  • 19,727
  • 15
  • 78
  • 118
  • 1
    Yes that worked. Thank you very much. How typical that all my efforts were focused on the submit() command and its syntax which was not the problem here at all. – danbae Sep 30 '17 at 09:58