1

I am creating a chat system. I am sending a form data through ajax method in jquery. My first problem is ajax method is not sending data to proccess.php and page goes to redirect to its self.

<div id="chatOutput"></div>
<form id="myform">
    <textarea id="chatInput" name="chatInput"></textarea>
    <input type="submit" id="send" name="send" value="send" />
</form>

and script is :

$('#send').click(function () {
    $('#myform').submit();
    $.ajax({
        url: 'process.php',
        type: 'post',
        dataType: 'json',
        data: $('#myform').serialize(),
        success: function () {
            alert("Submitted!"); // for testing
        }
    });
    return false;
});

but script is not working and page goes to refresh and i see the variables and its values in the address bar like get method.

if this problem goes to solve, process.php will create a chat.txt and append data from #chatInput into it. and then will append chat.txt 's data to #chatOutput.

After appending data, div#chatOutput 's size goes to change. I want to fixed/specified width and height of this div. After the fixing size, how to scroll to bottom to see the last chatting?

4

4 回答 4

0

问题在这里:

$('#myform').submit();

模拟“提交”按钮点击事件

于 2013-08-25T09:58:29.520 回答
0

EDIT You had a syntax error. Make sure u have e.preventDefault(); as the first thing in your event click function. Then the default action will be prevented even when an error occurs later on.

$('#send').click( function(e) {
    e.preventDefault(); //disable default action

    $('#myform').submit();
        $.ajax({
            url: 'process.php',
            type: 'post',
            dataType: 'json',
            data: $('#myform').serialize(),
            success: function() {
               alert("Submitted!"); // for testing
            }
        });
    });

    return false; //return something
});
于 2013-08-25T09:56:39.137 回答
0

You can just do :

$('#myform').submit(function() {
    $.ajax({
        url: 'process.php',
        type: 'post',
        dataType: 'json',
        data: $('#myform').serialize(),
        success: function() {
           alert("Submitted!"); // for testing
        }
    });
    return false;
});

You used $('#myform').submit(); which just submits the form in the normal way and thus ignoring the ajax etc after that.

Also, put this code either after the form itself or within $(function(){ ... });

于 2013-08-25T09:56:51.320 回答
0

删除行:

$('#myform').submit();

它在进行 ajax 调用之前提交表单。

于 2015-11-13T09:44:42.917 回答