开发者

post multi forms with Ajax and php same page

i have an easy ajax script which sending data to php file with no problem index.php

    <script type="text/javascript">
      $(function() {
        $('#submit').click(function() {
        $('#container').append('<img src="img/loading.gif" alt="Currently Loading" id="loading" />');

       开发者_开发知识库     var name = $('#name').val();
            var email = $('#email').val();
            var comments = $('#comments').val();

            $.ajax({
                url: 'submit_to_db.php',
                type: 'POST',
                data: 'name=' + name + '&email=' + email + '&comments=' + comments,

                success: function(result) {
                    $('#response').remove();
                    $('#container').append('<p id="response">' + result + '</p>');
                    $('#loading').fadeOut(500, function() {
                        $(this).remove();
                    });

                }
            });

            return false;
        });

      });
    </script>

with in the same page i have another form which needed to be submitted so i don't know how to do it without no conflict with in this function i already use ? btw it won't processed with in the same php file it will use another file


I don't see what's the point. What kind of problems do you have in submitting more than one form? You're referencing elements by id.

Note that you really should change your code to intercept the $('#form-id').submit(), not the $('#submit').click event, because a form could be submitted also with enter key, or via javascript callbacks, not only using the submit button.

In your code what is the problem in doing something like this

$(function() {
        $('#other-form-id').submit(function() {
            $.ajax({
                url: 'other-php-script.php',
                type: 'POST',
                data: 'name=' + name + '&email=' + email + '&comments=' + comments,

                success: function(result) {
                    // your success handling
                }
            });
            return false;
        });
      });

This is going to work as far as Dom ID are unique across the document.

BTW I strongly advise you to use this wonderful plugin to manage ajax form to keep your js code cleaner and simple. With that your code could be rewritten as:

$(document).ready(function() { 
        // bind 'myForm' and provide a simple callback function 
        $('#myForm').ajaxForm(function() { 
            $('#response').remove();
            $('#container').append('<p id="response">' + result + '</p>');
            $('#loading').fadeOut(500, function() {
                $(this).remove();
            });                
        }); 
    }); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜