简体   繁体   中英

How do I get my jQuery and PHP to work together with ajax?

I've seen some similar questions, but I haven't seen any that specifically speaks to this. I've created a very simple sample, and I feel that it should work, but it doesn't. The point is to see something simple, so that other, similar things are clear.

I feel that this is very 'basic', and it's hard to be much simpler; so, people should be able to get behind it, knowing that it's the ultimate noobie stepping stone:

The HTML and JS:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="javascript"></script>
<script type="text/javascript" src="/javascript/jquery-1.8.2.js">
$(document).ready(function(){
    $("submit").click(function(){
        var req = $.ajax({
                type: 'POST',
                url: 'form.php',
                data: {
                        message: $('#message').val(),
                        author: $('#author').val()
                },
                timeout: 20000,
                beforeSend: function(msg) {
                        $("#sent").html(msg);
                }
        });

        req.fail(function(xhr, ajaxOptions, thrownError) {
                alert("AJAX Failed");
        });

        req.done(function(res) {
                 $("#received").html(res);
        });
    });
});
</script>
</head>
<body>
<div id="sent"></div>
<div id="form">
<form>  
    Your message:  <input type="text" name="message" value="Hi!" /><br />
    Your name: <input type="text" name="author" value="Michael" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>
</div>
<div id="received"></div>
</body>
</html>

And the PHP:

<?php 
  echo "The file is located at ".$_POST["message"].".<br>";
  echo "The file is named ".$_POST["author"].".";

You can use serialize instead of assigning id to the input fields:

<html>
<head>
<script type="javascript"></script>
<script type="text/javascript" src="/javascript/jquery-1.8.2.js">
$(document).ready(function(){
$("#submit").click(function(){
    var req = $.ajax({
            type: 'POST',
            url: 'form.php',
            data: $('#frm').serialize(),
            timeout: 20000,
            beforeSend: function(msg) {
                    $("#sent").html(msg);
            },
            success: function(data){
                alert('Success!Data was received by php.Message from the php script:'+data.res);
            }
    });

    req.fail(function(xhr, ajaxOptions, thrownError) {
            alert("AJAX Failed");
    });

    req.done(function(res) {
             $("#received").html(res);
    });
});});

</script>
</head>
<body>
<div id="sent"></div>
<div id="form">
<form id="frm">  
Your message:  <input type="text" name="message" value="Hi!" /><br />
Your name: <input type="text" name="author" value="Michael" /><br />
<input type="submit" id="submit" value="Submit me!" />
</form>
</div>
<div id="received"></div>
</body>
</html>

PHP SCRIPT:

<?php 
if(isset($_POST['message']) && isset($_POST['author']))
{
    $arr_to_pass_as_json = array('res'=>'This is your message:'.$_POST['message'].' and your author '.$_POST['author']);
    echo json_encode($arr_to_pass_as_json)
}
else
    echo json_encode(array('res'=>'Message and Author is required'));

We use json in displaying result from php to javascript. hope this will help.

Check the difference with this:

$(document).ready(function(){
    $("submit").click(function(){
        var req = $.ajax({
                type: 'POST',
                url: 'form.php',
                data: {
                        message: $('#message').val(),
                        author: $('#author').val()
                },
                timeout: 20000,
                beforeSend: function(msg) {
                        $("#sent").html(data);
                }
        })

        .fail(function(xhr, ajaxOptions, thrownError) {
                alert("AJAX Failed");
        })

        .done(function(res) {
                 $("#received").html(res);
        });
    });
});

Check if this works (According to http://api.jquery.com/jQuery.ajax/#jqXHR it should)

since your using

message: $('#message').val(),
author: $('#author').val()

You will need to specify your id's in you input tgs.

<form>  
    Your message:  <input type="text" name="message" value="Hi!" id="message" /><br />
    Your name: <input type="text" name="author" value="Michael" id="author" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

Your asking to find and html id selectyor, and get the value from it, 'name' is NOT the same as an ID.

Alternatively you could put and id on your html form and use .sezialize(), but simply adding an id is simpler at this step. http://api.jquery.com/serialize/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM