开发者

get a forms values via jquery, post to a php script, and have php script process for errors and return value

开发者 https://www.devze.com 2023-03-22 15:29 出处:网络
I have this form: <form action= \'addperm.php\' class = \'addperm\' method=\'post\'> <input type=\'text\' name=\'user\' /><br />

I have this form:

<form action= 'addperm.php' class = 'addperm' method='post'>
    <input type='text' name='user' /><br />
    <input type='radio' name='perm' value='1' CHECKED /> Can view only<br />
<input type='radio' name='perm' value='2' /> Can make chan开发者_JAVA百科ges <br />
<input type='submit' value='Add'>
</form>

I want to know how, without redirecting to another page, I can get these two input values (user and perm), post them to a php script via ajax, and then have the php return the results


Read the jQuery API documentation for $.post.


$('input[type=submit]').click(function(e){
    $.ajax({
        type: "POST",
        url: "some.php",
        data: "user=" + $('input[name=user]').val() + "&perm=" + $('input[name=perm]:checked').val(),
        success: function(msg){
            // msg is your content
        }
    });
    e.preventDefault();
});

some.php

echo json_encode(array($_POST['user'],$_POST['perm']));

I wouldn't take my syntax at face value, but that's the idea.


Download jQuery from http://jquery.com

Include it in the head of your page as such:

<script type="text/javascript" src="jquery/jquery.min.js"></script>

Change the src to whatever the name of the file you downloaded is.

Then also in the head of your page paste this:

<script type="text/javascript">
$(document).ready(function() {
    $('.addperm').submit(function(){
        var query = 'perm='+$('#perm').val()+'&user='+$('#user').val(); 
            $.post("addperm.php", query, function(response){
                alert(response);
            });
    });
});
</script>

To make this work you are going to have to change your HTML to this:

<form action= 'addperm.php' class = 'addperm' method='post'>
<input type='text' name='user' id='user' /><br />
<input type='radio' name='perm' value='1' id='perm' CHECKED /> Can view only<br />
<input type='radio' name='perm' value='2' id='perm' /> Can make changes <br />
<input type='submit' value='Add'>
</form>

I havent tested it yet, but it should work.

0

精彩评论

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