简体   繁体   中英

how to write jQuery ajax's success function

I am getting started to learn jQuery (web development in general) and in this example, I am supposed to send the input (username and password using submit button) to php page using .ajax and success function.

this is the html (form) code:

<form id="form1">
    Enter Username :
    <input type="text" id="userName">
    <br>
    Enter Password:
    <input type="password" id="passWord">
    <br>
    <input type="submit" value="Submit" id="sub">
    <br>
</form>
<div id="result"></div>

this the jQuery code (the 3 alerts just to check where does my code stops going and the 3rd alert never reached):

$(document).ready(function(){
        $("form").submit(function(){
            alert('clicked');
            var send = $(this).serialize();
            alert('gotData');
            $.ajax({
                type: "POST",
                url: "login.php",
                data: send,
                dataType: "json",
                success: function(msg){
                    alert('inAjax');
                    $("#result").html(msg.name + " " + msg.pass);
                }
            });
            return false;
        }); 
    });

this is my php code:

<?php

$name = $_REQUEST['userName'];
$pass = $_REQUEST['passWord'];

$list = array('name' => $name, 'pass' => $pass);
$c = json_encode($list);
echo $c;

?>

The code doesn't work (nothing appears on the webpage)

First off, form elements need to have name attributes. id values don't matter for submission purposes.

You're better off just using the .post() method:

$.post('login.php', $(this).serialize(), function(resp){ alert(resp); });

Rather than track it with alerts, if you use Chrome, just put debugger; at the beginning of your function so it will pause the code and open the inspector for you.

First of all check if you are sending the request in a http enviroment. In order to do that, you can use the PHP built-in webserver as a quick solution.

//Choose the directory
$ cd ~/public_html
//Start the webserver on port 8000
$ php -S localhost:8000

Also change the type property to method instead.

And if there's a problem on the server side check your request using the browser devtools or another http client like Postman.

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