Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

javascript - Send HTML form post data to file with Jquery?

I am trying to send post data to my post data file handler called postinfo.php with jQuery but so far I can make it.

Here is my post.php code:

<HTML>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<script type="text/javscript">
$('#form_id').on('submit', function(e){
    e.preventDefault();
    $.ajax({
       type: "POST",
       url: "http://www.vemvo.com/test/postinfo.php",
       data: $(this).serialize(),
       success: function() {
         alert('success');
       }
    });
});
</script>   
<form method="post" id="form_id">
<input type="text" name="ime">
<input type="submit" id="submit" name="submit" value="Send">
</form>

You can see the page here: http://www.vemvo.com/test/post.php

Here is the code from my postinfo.php:

<?PHP

$ime = $_POST['ime'];

echo "Your name is $ime";
?>

Here is located postinfo.php - http://www.vemvo.com/test/postinfo.php

So where is my mistake and how I can make it work? Now it's not sending the data and not giving me the success alert.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your jQuery selector isn't going to find that form, since the selector is running before the form tag exists in the DOM. Try wrapping it in the jQuery function to wait for the document to be ready:

$(function () {
    $('#form_id').on('submit', function(e){
        // the rest of your code
    });
});

It also might be a good idea to return false at the end, to further suppress the form's default post action:

e.preventDefault();
$.ajax({
   type: "POST",
   url: "./postinfo.php",
   data: $(this).serialize(),
   success: function() {
     alert('success');
   }
});
return false;

Currently the form is posting as normal. Since the AJAX handler is never attached (because the element doesn't exist when the selector executes), it's just doing a normal document-level form post. And since there's no action attribute specified in the form tag, the page is posting to itself by default. Which just responds with the current page.

Edit: You also have a typo which may be preventing the browser from executing your JavaScript code at all:

<script type="text/javscript">

You're missing the second "a". This should be:

<script type="text/javascript">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...