简体   繁体   中英

Simple hello world using jQuery ajax and php doesn't works

I'm trying to do a simple hello world using jQuery and Ajax for getting a response from a php in the same folder.

The jQuery code is:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

    <link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"
    rel="stylesheet" type="text/css">
    <link href="http://pingendo.github.io/pingendo-bootstrap/themes/default/bootstrap.css"
    rel="stylesheet" type="text/css">

    <script type="text/javascript">
        function jsonIt(){
            var x = document.getElementById("input1").value; 
            var y = document.getElementById("input2").value; 

            var obj = '{'
                       +'"id" : "'+x+'",'
                       +'"name" : '+y+''
                       +'}';

            var person = {
                id:x,
                name:y
            }; 

            var str_json = JSON.stringify(person);

            $.ajax({
                type: 'get',
                url: 'a.php',
                dataType: 'text', 
                data: obj,
                success: function(data) {
                    alert(data);
                },
                error: function(e){
                        console.log(e.message);
                        //alert('error');
                    }
            });
            alert("Pause");
        }


    </script>
</head>

<body>
    <div class="section">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <form class="form-horizontal" role="form">
                        <div class="form-group">
                            <div class="col-sm-2">
                                <label for="inputEmail3" class="control-label">Email</label>
                            </div>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="input1" placeholder="Email">
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-2">
                                <label for="inputPassword3" class="control-label">Password</label>
                            </div>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="input2" placeholder="Password">
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox">Remember me</label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-default" onclick="jsonIt()">Sign in</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Simply, called using the HTML:

<button type="submit" class="btn btn-default" onclick="jsonIt()">Sign in</button>

And the php, in the same folder, called a.php is:

<?php echo "Helo world"; ?>

So when I click the button that calls the function jsonIt() I get the following response: "[object XMLDocument]" and not Hello world.

What could be?

EDITED

After the modifications the header code will be:

<head>

    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
            <script type="text/javascript" src="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
            <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
        ...

         <script type="text/javascript">
            $(document).ready(function() {

                function jsonIt(){


                    $.ajax({
                        method: 'get',
                        url: 'a.php',
                        done: function(data) {
                            alert(data);
                        },
                        fail:function( jqXHR, textStatus ) {
                            console.log( "Request failed: " + textStatus );
                        }
                    });

                    //alert("Pause");
                }

                $(document).on('click', 'button[type="submit"]', function(e) {
                     e.preventDefault(); // prevents the default click action
                     jsonIt();
                });
            });


        </script>
    </head>

And the markup of the button like:

<button type="submit" class="btn btn-default" >Sign in</button>

But it stills returning me "[object XMLDocument]" and not Hello world.

If you're going to add jQuery scripts to the top of the page you need to surround them with a document ready handler:

<script type="text/javascript">
$(document).ready(function() {
    function jsonIt(){
            $.ajax({
                method: 'GET',
                url: 'a.php',
                //url: 'http://practica00.tk/a.php',
                dataType: 'text'
            })
            .done(function(data) {
                    alert(data);
                })

            .fail (function( jqXHR, textStatus ) {
                    console.log( "Request failed: " + textStatus );
                });
        alert("Pause");
    }

    $(document).on('click', 'button[type="submit"]', function(e) {
        e.preventDefault(); // prevents the default click action
        jsonIt();
    });
});
</script>

The document ready handler insures that all of the DOM has loaded before the jQuery runs and attaches its event handlers. If you don't wrap in a document ready handler the jQuery may attempt to attach event handlers and methods to items which are not yet loaded into the DOM .

You really shouldn't use inline JavaScript to call functions, especially since you have jQuery available to you. If you are going to you still need to prevent default actions.

<button type="submit" class="btn btn-default" onclick="jsonIt(); return false;">Sign in</button>

If you'd like to use jQuery for the click you would remove the inline JavaScript from the button and add the following to your jQuery code:

 $(document).on('click', 'button[type="submit"]', function(e) {
     e.preventDefault(); // prevents the default click action
     jsonIt();
});

I'm not sure why you're doing anything with a JSON string as you do not use it in your query anywhere. you never define the obj , so you shouldn't send it.

EDIT: I have updated my answer to reflect the more proper AJAX return methods with the version of jQuery being used.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

If you want to do a simple "hello world" you should remove any code that distracts from the purpose before adding any complexity.

Additionally: To perform AJAX (and consequently PHP) you must execute the code from an operating web server, either your localhost or a test host where everything can be executed properly.

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