1

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.

4 Answers 4

1

yes it will redirect to action coz you submited the form

Problem is from calling the submit function. by calling .submit() it submit the form to specific action after executing a code inside submit() then redirect to the action page.

how about putting the ajax in a function then call it on onsubmit.

<form id="shareform" name="shareform" method="post" action="php/mail.php" onsubmit="ajax_submit(event);">
<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>

js

function ajax_submit(e)
{
 //perform ajax 
 return false // to stop redirect
 //or 
 e.preventDefault();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, user3020044, thanks for the response. I've tried passing it through a function on onsubmit but in this way I can't catch the form submission and prevent it from redirecting. I've tried it with both return false and preventDefault() but have had no luck. The form just redirects (and, of course, the data is input into the DB, as it always does when redirecting).
try adding this onsubmit="return ajax_submit();" in the form attributes
Tried this now and, like in the previous case, I'm redirected to the PHP. Can't catch the submission and prevent the redirection this way; but the data is entered into my DB.
1

Problem is with your PHP, you see, you make connection with your db, you have created query but where are you executing it? put mysql_query($sql) before closing connection and check for return boolean too just to be carefull.

if(mysql_query($sql))
   echo "query executed";
else
   echo "oops";

For your information mysql extension is deprecated its good to use mysqli or PDO.

For preventing redirection you can use `e.preventDefault()' as other mates are saying.

Edit: Add form.validate before calling form.valid() it will solve your jQuery problem

here is your jQuery code

form.submit(function(){
    form.validate();
    if(form.valid()==true)
    {   
        $('.msg.sharing').fadeIn(200);
        var sharecallback = false;
        var data = '&shareto=' + $('#shareto').prop('value') +
                   '&sharetomail=' + $('#sharetomail').prop('value') +
                   '&sharefrom=' + $('#sharefrom').prop('value') +
                   '&sharefrommail=' + $('#sharefrommail').prop('value');
        $.ajax({
            type: 'POST',
            url: "mail.php",
            data: data,
            success: function() {
                sharecallback = true;
                $('.msg').hide();
                $('.msg.done').fadeIn(200);
                return false;
            },
            error: function() {
                $('.msg').hide();
                $('.msg.error').fadeIn(200);
            }
        });
        return false;
    }
    return false;
});

2 Comments

Hi, tomcat, thanks for the response. I do have a mysql_query($sql) check at the end in order to check if everything is going OK. I just didn't include it in the code example because I didn't want to just litter my post with code. But thanks a lot for the note. You're right: it's always a good idea to double check.
No, not yet... sadly! I'm pulling my hair out. I have another similar (almost twin) form submission coded and it works fine! I'm comparing them to see what's different. At this time, all I can see different is the use of the jQuery Validation Plugin [link] (jqueryvalidation.org). But I've tried commenting out that script loader and any appearance of it throughout, but no luck there! (Sorry for calling you "tomcat" in my first response to your answer... Could have sworn I read "tomcat" but now I see "pronox"... maybe my brain was saying bye-bye by then.)
0

Try putting e.preventDefault(); at the start of the submit event handler instead of using return false; at the end.

Oh, also remember to pass the event parameter into the event handler:

form.submit(function(e) {
    ...
});

3 Comments

Hi, russellc, thanks for the response. Unfortunately, I have also tried using e.preventDefault() instead of return false but the outcome is the same: if implemented, there is no redirect, but there is no data input either.
If you remove the conditional for form validation, does it go through? The issue might have something to do with the valid() call you made to what I presume might be a jQuery validation plugin.
Yes, you're right, I'm using jQuery Validation Plugin [link] (jqueryvalidation.org) in order to check the form before it is submit. I have now tried commenting out the valid() call and having the submit go right through but the issue remains.
0

OK! Lucky break! (Or, as I always say to myself: Go to sleep, rest your brain, tomorrow morning you'll realized the answer was staring you right in the face all the time... and you'll feel so very foolish!)

In this case, though, the solution has been very much randomly come upon, although something told me: try this!

I was building my data, as you can see in my question, like this:

var data = '&to=' + $('#shareto').prop('value') +
           '&tomail=' + $('#sharetomail').prop('value') +
           '&from=' + $('#sharefrom').prop('value') +
           '&frommail=' + $('#sharefrommail').prop('value');

So I said to myself: why not try serializing it instead of having this ugly code... perhaps it might even help you solve the issue.

I discarded that code and changed the data: data, bit to:

data: form.serialize(),

(Where form is the variable that refers to my HTML form.)

I tested it out, fingers crossed, to see if by miracle that fixed it and, know what?: It did!

So this is the simple solution to my problem, difficult to come upon.

A thousand thanks to the three of you who helped me along. I got very valuable information there!

6 Comments

Good work, i tested your code, it works even only if you add form.validate() before if(form.valid()==true). Try this too.
One thing more when your serialize form it dispatch request by processing your html form while in your jQuery you were cancelling your form and creating AJAX request, where you used different names as parameters like you used to, tomail etc though you should have used shareto, sharetomail as was expected by your mail.php.
Thanks for that last comment. Now I know where the previous code was going wrong and I won't make the same mistake in the future!
Try using developer tools of google chrome, there in network tab you can always check how did your AJAX request go, what input data was sent to server and last but not the least you can check what response was received from your server php script in your case mail.php and then you can easily debug your problems.
Hey! Thanks a lot for the "good work" incentive! Like a gold star for my efforts. And thanks A LOT for the Chrome Dev Tools hint on the Network Tab! Their dev tools are really very helpful but I had never explored the network tab, so I didn't know what I could do with it. And it's really a life-saver in something like what I've just been doing! So that's a GREAT piece of info that'll make my life loads easier. So thank you very much!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.