0
votes

Sorry for the weird title. I have the following code that tests the post() function of jquery:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Untitled Document</title>
<script type="text/javascript" src="../../jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
     $(document).ready(function() {

        $("form#f").submit(function(){
            var result = "";
            $.ajax({
                async: false,
                type: "POST",
                url: "test.php",
                dataType: "script",
                success: function(data){
                    result = data;
                }
            });
            alert(result);
        });

     }

</script>
</head>

<body>

<form method="post" action="test.php" id="f">
    <input type="text" name="name" />
    <input type="submit"/>
</form>

</body>
</html>

... and this is the test.php implementation:

<?php 
    header('Content-Type: text/plain');
    echo "hello " . $_POST['name'];
?>

Why is the page shown instead of data appearing in the alert dialog in submit() function? Sorry I know that this is a n00b question. I'm not really good at Javascript.

3
Try adding return false; at the end of the function you assign to the submit action. I believe this will override the default behaviour which is to actually submit the form to the action url. - Endophage
change your <input type='submit'/> to <input type='button'/> - Rafay

3 Answers

2
votes

do return false; at the end of your submit handler. Otherwise you are not preventing the normal submit (post to test.php) to occur

$("form#f").submit(function(){
            var result = "";
            $.ajax({
                async: false,
                type: "POST",
                url: "test.php",
                dataType: "script",
                success: function(data){
                    result = data;
                    alert(result);  // And move that here
                }
            });
            return false;  // Here

        });
1
votes

An alternative to returning false is to use jQuery's event.preventDefault():

    $("form#f").submit(function(e){
        e.preventDefault();
        // do stuff
    });
0
votes

@Jairo I tried your original code and it worked using the CDN.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>