简体   繁体   中英

Jquery ajax() function won't load PHP script

I'm trying to create a simple login with PHP and MySQL and I'm using the AJAX() jquery function to load the PHP script. All that I want to do is to load a new web page (for example java2s.com) when the script finds the user in my database. Problem is that the script won't work at all. This is the HTML with the Jquery:

EDIT: This is the fixed code thanks to all those who commented, which sadly still doesn't work.

<!DOCTYPE HTML>
<html>
<head>
<title> Login </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="JavaScript">
function change()
{
document.location.href="http://www.java2s.com";
}

$(document).ready(
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
        type: 'POST',
        url: 'login.php',
        async: false,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: sendstr,
        success:function(response){
        if (response['result']=="login successful")
            {
            change();
            }
        }
    });

    })
  )
</script>
</head>
<body>
<h1> INSERT USERNAME AND PASSWORD</h1>
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="submit" id="loginForm" class="button positive">
</body>
</html>

The PHP script is very simple:

<?php
$data = file_get_contents('php://input');
$result = json_decode($data);
$con=mysqli_connect("localhost","****","*****","*******");
$str="SELECT ID FROM users WHERE username='".$result->username."' AND password='".$result->password."';";
$exists = mysqli_query($con,$str);
if (mysqli_num_rows($exists) ==1)
{
    $arr = array('result'=>"login successful");
    $ris=json_encode($arr);
    echo $ris;
}
else
{
    $arr= array('result'=>"login error");
    $ris=json_encode($arr);
    echo $ris;
}
mysqli_close($con)
?>

When I load the page and press the submit button nothing will happen. Anyone can help? Thank you very much in advance

try something like this

$("#loginForm").click(function() {
    var jsonlogin=new Object();
    jsonlogin.username=$('#username').val();
    jsonlogin.password=$('#password').val();
    $.ajax({
        type: 'POST',
        url: 'login.php',
        async: false,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: jsonlogin,
        success:function(response){
            if (response['result']=="login successful")
            {
                change();
            }
        }
    });
})

EDITED CODE

you have not implemented DOM ready method correctly

    $(document).ready(function(){
        // code goes here
    });

Maybe because all the php is commented out?

Also in your success function should look like this:

success: function(response){
    dosomethingwithrespones(response);
}

The data in the $.ajax denotes what you send.

why are you using function ajaxJson() ... try to remove it and if you really want to use it then modify your button code like this and remove $("#loginForm").click(function() { } from jquery...

  <input type="submit" id="loginForm" class="button positive" onclick="ajaxJson()">

and change <script type="text/javascript"> instead of <script language="javascript"> .. this identifier is not standard, this attribute has been deprecated(outdated by newer constructs) in favor of type.

first way

 function ajaxJson()
 {
       //your code goes here without triggering **click** event.. 
 }

 <input type="submit" id="loginForm" class="button positive" onclick="ajaxJson()">

second way

  $("#loginForm").click(function() 
  {
      //your code goes here...
  }

  <input type="submit" id="loginForm" class="button positive">

keep everything outside $(document).ready function...

hope it may help you

try this query in login.php,

     $str="SELECT ID FROM users WHERE username='".$result->username."' AND password='".$result->password."' "; 

Jquery:

           $(document).ready(function(){
            $("#loginForm").click(function() {
                var jsonlogin=new Object();
                jsonlogin.username=$('#username').val();
                jsonlogin.password=$('#password').val();
                var sendstr = JSON.stringify(jsonlogin);
                $.ajax({
                        type: 'POST',
                        url: 'login.php',
                        async: false,                         
                        dataType: 'json',
                        data: sendstr,
                        success:function(response){
                        if (response.result=="login successful")
                            {
                             change();
                            }else{
                                alert(response.result);
                                return false;
                            }   
                        }
                    });

                 });
        });

You have missed ending { and } for ready function.try below code.

<!DOCTYPE HTML>
<html>
<head>
<title> Login </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="JavaScript">
function change()
{
document.location.href="http://www.java2s.com";
}

$(document).ready(function () {
$("#loginForm").click(function() {
alert("hi");
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
        type: 'POST',
        url: 'login.php',
        async: false,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: sendstr,
        success:function(response){
        if (response['result']=="login successful")
            {
            change();
            }
        }
    });

    });
});
</script>
</head>
<body>
<h1> INSERT USERNAME AND PASSWORD</h1>
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="button" id="loginForm" class="button positive">
</body>
</html>

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