2

I am having trouble with ajaxForm plugin. I want it to display a result message to the user without leaving the page.

The problem is that when I submit the form, instead of prepending the alert into the .jumbotron.modded (this is the div container of the form), it navigates away to supportForm.php and just displays the echoed number.

This does work well sometimes, but most of the times it just navigates away to supportForm.php . I cannot understand why it does not always have the same behaviour.

Here's the HTML form:

        <form id="supportForm" action="supportForm.php" method="post" style="padding-top:10px">
            <div class="form-group">
                <input type="text" name="subject" id="subject" placeholder="Subject" class="form-control" required>
            </div>
            <div class="form-group">
                <textarea class="form-control" rows="4" name="comment" id="comment" placeholder="Write your message here" required></textarea>
            </div>
            <button type="submit" class="btn btn-upload" style="margin-top:20px;float:right;" value="">SEND<img src="img/plus.png" style="margin-bottom:5px;padding-left:5px;" /></button>
        </form>

Here's the Javascript code:

    window.onload = function()
    {
        $('#supportForm').ajaxForm({
            success: function(res) {
                console.log(res);
                if(res=='1')
                {
                    $(".jumbotron.modded").prepend('<div class="alert alert-success alert-dismissible" role="alert">  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>Successfully sent. Thank you</div>');
                }else{
                    switch(res)
                    {
                        case '0':
                            $(".jumbotron.modded").prepend('<div class="alert alert-danger alert-dismissible" role="alert">  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>Error 1. Please contact mail@asd.com<</div>');
                        break;
                        case '-1':
                            $(".jumbotron.modded").prepend('<div class="alert alert-danger alert-dismissible" role="alert">  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>Error 2. Please contact mail@asd.com<</div>');
                        break;
                        case '-2':
                            $(".jumbotron.modded").prepend('<div class="alert alert-danger alert-dismissible" role="alert">  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>Error 3. Please contact mail@asd.com</div>');
                        break;
                        case '-3':
                            $(".jumbotron.modded").prepend('<div class="alert alert-danger alert-dismissible" role="alert">  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>Error 4. Please contact mail@asd.com<</div>');
                        break;
                    }
                }
            }
        });
    }

Here's the PHP code:

if ($row = $db->query("SELECT user FROM tblusers WHERE userId='".$fromId."'")->fetch_array())
{
    $fromMail1 = $row['user'];
    if($row2 = $db->query("SELECT name,lastname,email FROM tblprofile WHERE userId='".$fromId."'")->fetch_array())
    {
        $fromMail2 = $row2['email'];
        $fromName = $row2['name']." ".$row2['lastname'];
        if ($db->query("INSERT INTO tblSupports (supportTitle,supportComment,userId) VALUES ('".$title."','".$comment."','".$fromId."')"))
        {
            if(sendEmail($fromMail1,$fromMail2,$fromName,$titleClean,$commentClean))
            {
                echo 1;
            }else{// (error 1)
                echo 0;
            }
        }else{//(error 2)
            echo -1;
        }
    }else{//(error 3)
        echo -2;
    }
}else{//(error 4)
    echo -3;
}

How can I solve this? Thank you very much

Manuel Azar
  • 853
  • 2
  • 14
  • 24
pablito.aven
  • 1,135
  • 1
  • 11
  • 29

4 Answers4

1

Try this

$('#supportForm').ajaxForm({
    /* bla-bla-bla*/

    return false;
    })

But I really don't understand for what, you are using this plugin. It's easy to do without any plugin.

$('#submit').click(function(){
    $.ajax({
      method: "POST",
      url: "some.php",
      data: $('#supportForm').serialize(),
        success: function(data){
            alert(data)
        }
        error: function(error){
            alert(error);
        }
    });
    return false;
});

something like this.

ArtemKh
  • 950
  • 7
  • 15
  • what is the purpose of the `return false;` statement here? – pablito.aven Jun 05 '15 at 12:55
  • `Uncaught SyntaxError: Unexpected token false ` outputs in console if I add the return false. – pablito.aven Jun 05 '15 at 12:58
  • @ArtemKh how would I be able to do this with a form that includes a file upload (using PHP back end)? `serialize()` doesn't seem like the right option, because it turns all of the form inputs into a string. – Yami Medina Jan 10 '16 at 00:43
  • @YamiMedina For file upload this variant isn't working. See this http://stackoverflow.com/a/23981045/4357197 – ArtemKh Jan 12 '16 at 09:37
1

Make sure that your jquery.form.js script is actually included before this function is called. You can check using firebug on firefox for example: set a breakpoint on the ajaxForm call and then when it's stopped there, see if the jquery.form.js is among the scripts.

Netta
  • 11
  • 2
0

Try .trim on your response before checking it, might be some white space in there

$.trim(res);

EDIT: trim didn't work - is it possible that the onload function isn't firing before you hit submit? If you put a console.log in as below you'll know if it has definitely fired first. That might explain why sometimes it works and sometimes not. If it always works when that console outputs then you have your answer.

 window.onload = function()
  {
    console.log('fired');
   $('#supportForm').ajaxForm({
leapin_leprechaun
  • 605
  • 1
  • 4
  • 15
0

Definately loose the plugin and make sure Jquery is loaded then in your js functions file use this:

$('#supportForm').on('submit', function(e) {
        e.preventDefault();
        $(this).find('input[type="submit"]').val('Processing');
        $.ajax({
            type: "POST",
            url: 'http://supportForm.php',
            data: $(this).serialize(),
            success:function(data) {
                if (data == 'success') {
                    -- Code if form submitted successfully & returned a positive output --
                }else{
                    -- Code if form submitted successfully but did not return a postive outpt --
                }
            },
            error: function() {
                -- Code if there is an error in your php --
            }
        })
    });

I use Ajax for almost every form and what I do is echo success with my php file if everything went through successfully. Then as you see in the above code 'data' will be whatever gets echoed from the php file so you can keep adding if/else cases for anything you want to echo. The last part is if there is an error in your php file then that section will be triggered.

Action Coding
  • 830
  • 5
  • 17