I'm coding a form that sends some data into a MySQL database but, at the same time, I don't want the database submit to redirect the user somewhere else. For that reason, I'm passing the submit action through jQuery and AJAX as seen below:
form.submit(function(){
$('.msg').hide();
if(form.valid()==true) {
$('.msg.sharing').fadeIn(200);
var sharecallback = false;
var data = '&to=' + $('#shareto').prop('value') +
'&tomail=' + $('#sharetomail').prop('value') +
'&from=' + $('#sharefrom').prop('value') +
'&frommail=' + $('#sharefrommail').prop('value');
$.ajax({
type: 'POST',
url: form.attr('action'),
data: data,
success: function() {
sharecallback = true;
$('.msg').hide();
$('.msg.done').fadeIn(200);
return false;
},
error: function() {
$('.msg').hide();
$('.msg.error').fadeIn(200);
}
});
return false;
};
});
The PHP file that handles the data post holds the following code:
$where = 'here';
$to = htmlentities(addslashes($_POST['shareto']));
$tomail = htmlentities(addslashes($_POST['sharetomail']));
$from = htmlentities(addslashes($_POST['sharefrom']));
$frommail = htmlentities(addslashes($_POST['sharefrommail']));
$con = mysql_connect('localhost','root','mypass');
mysql_select_db('mydatabase', $con);
$sql="INSERT INTO list (date, whereto, towhom, tomail, fromwhom, frommail) VALUES (NOW(), '$where', '$to', '$tomail', '$from', '$frommail')";
mysql_close($con);
And, finally, all else I can show you is the form HTML:
<form id="shareform" name="shareform" method="post" action="php/mail.php">
<input id="shareto" name="shareto" />
<input id="sharefrom" name="sharefrom" />
<input id="sharetomail" name="sharetomail" />
<input id="sharefrommail" name="sharefrommail" />
<button type="submit" id="sharesubmit" name="sharesubmit"></button>
</form>
In the past, I've used similar coding to do something similar and it has worked fine. However, this time, I don't know where I'm going wrong, but I've been through it time and time again for the better part of today and I can't seem to find a solution.
If I get rid of the return false that runs at the end of if(form.valid()==true) ..., that is to say, the second return false in the jQuery code, I get the data input into the DB just fine. The issue is that I'm redirected into the PHP file. If I set the return false as you see above, I don't get redirected, but the only data to be input is the $where variable and the date created by the NOW() PHP code, which are not posted by the AJAX but rather created in the PHP file itself. So I think it's safe to suppose that something is going wrong in passing the form data into the PHP file and onto the database input code when return false is set(*).
(*)I have tested posting the data without the return false and printing the data content and everything seems fine. What I can't do is test this same thing when no redirect occurs. So I can't know for sure if the problem is from AJAX to PHP or from PHP vars to DB input code.