Empty form is getting sumitted in php/jquery
I have written the following code using jquery and php to submit the form when user clicks on save button, the form is getting submitted successfully but the forma data is empty (post data)
This is what i am doing :
I am checking whether the save button is clicked, if so then i am sending a mail and setting the form action then submitting the form.
<form id= "contactform" method='POST'>
.......
<input type='submit' name='submit_details' value=Save />
</form>
<script type="text/javascript">
function submit_form()
{
$("#contactform").attr("action","https://functions.php");
$("#contactform").submit()
}
<?php
if(isset($_POST['submit_details']))
{
mail("myself@gmail.com", $subject, $mailbody, $headers);
echo "<script> submit_form(); </script>";
}
?>
but when i call the the javascript function directly, the form data will pass
开发者_开发知识库<form id= "contactform" onsubmit='javascript:submit_form();' method='POST'>
So, what is the problem here.
Damien is correct...the below works though.
http://jsfiddle.net/D5Ldn/
<form id="contactform" method='POST'>
<input type='submit' name='submit_details' value=Save />
</form>
$('input[type="submit"]').click(function(event)
{
event.preventDefault();
$("#contactform").attr("action","https://functions.php");
$("#contactform").submit();
});
Maybe I got what you need, basically you want:
- a button that when is clicked sends an e-mail;
- after this e-mail you want the whole form (which one I don't know. I assumed is the same and you just didn't write your input fields) to be submitted; you might want to move this logic inside your PHP, since you're already doing the processing.
So, if the workflow is this one, you could try with:
HTML:
<form id="contactform" method="post" action="">
<!-- your other inputs go here? -->
<input type="text" name="input1" value="" />
<!-- I'm just guessing this ones.. -->
<input type="submit" name="submit_details" value="Salve" />
</form>
JS:
$('#contactform').submit(function({
var dataString = $(this).serialize();
$.ajax({
url: 'functions.php',
type: 'POST',
data: dataString,
success:function(response){
alert(response);
}
});
return false;
});
PHP functions.php
if($_POST['submit_details'])
{
//now send email:
if(mail("myself@gmail.com", $subject, $mailbody, $headers))
{
//mail sent: do the rest
$input1 = isset($_POST['input1']) ? $_POST['input1'] : '';
// and so on for the rest of the inputs.
// do whatever you need to.
return 'Mail sent and data saved!';
}
else
{
return 'Couldn\'t send mail!';
}
}
just change the button type to "button"
<input type='button' name='submit_details' value=Save onclick="submit_form()" />
精彩评论