yuli chika
yuli chika

Reputation: 9221

php-How to post value with ajax?

test.html

<html>
    <!--
     Please see the full php-ajax tutorial at http://www.php-learn-it.com/tutorials/starting_with_php_and_ajax.html
     If you found this tutorial useful, i would apprciate a link back to this tutorial. 
     Visit http://www.php-learn-it.com for more php and ajax tutrials
     -->
    <title>php-learn-it.com - php ajax form submit</title>
    <head>      
        <script type="text/javascript" src="prototype.js"></script>
        <script>

            function sendRequest() {
                new Ajax.Request("test.php", 
                    { 
                    method: 'post', 
                    postBody: 'name='+ $F('name'),
                    onComplete: showResponse 
                    });
                }

            function showResponse(req){
                $('show').innerHTML= req.responseText;
            }
        </script>
    </head>

    <body>
        <form id="test" onSubmit="return false;">
            <input type="hidden"  name="name" id="name" value="value">
            <input type="hidden" name="somethingElse" value="test" value="submit" onClick="sendRequest()">
        </form>
        <a href="#" onclick="myForm.submit()">Post!</a>

        <div id="show"></div>
        <br/><br/>

    </body>

</html>


<?php
/*
 * Please see the full php-ajax tutorial at http://www.php-learn-it.com/tutorials/starting_with_php_and_ajax.html
 * If you found this tutorial useful, i would apprciate a link back to this tutorial. 
 * Visit http://www.php-learn-it.com for more php and ajax tutrials
 */

if($_POST["name"] == "")
    echo "name is empty";
else
    echo "you typed ".$_POST["name"];
?>

Where is the wrong in form thanks.

Upvotes: 0

Views: 1408

Answers (2)

John Giotta
John Giotta

Reputation: 16934

A few things are wrong here:

  1. You have an onclick on a hidden form element
  2. The Post! anchor onclick isn't submitting anything

Suggested changes:

<head>      
    <script type="text/javascript" src="prototype.js"></script>
    <script>
        function showResponse(req){
            $('show').innerHTML = req.responseText;
        }
    </script>
</head>

<body>
    <form id="test" name="test" action="test.php">
        <input type="hidden"  name="name" id="name" value="cats" />
        <input type="hidden" name="somethingElse" value="test" />
    </form>
    <a href="#" onclick="$('test').request({onComplete: showResponse})">Post!</a>

    <div id="show"></div>

</body>

Upvotes: 3

Beiru
Beiru

Reputation: 312

form id="test" and no name

and yet :

a href="#" onclick="myForm.submit()"

just for starters.

Upvotes: 1

Related Questions