简体   繁体   English

无法获得Ajax发布信息

[英]Cannot get ajax post to work

I am able to the js file to fire which does do the first alert but i cannot get the 2nd alert to happen, php file is there and working returning 0 but the alert('finished post'); 我能够触发执行第一个警报的js文件,但是我无法获得第二个警报的发生,php文件在那里并且工作返回0,但是alert('finished post'); is not coming up. 没有来。 I think its some syntax I am missing. 我认为它缺少某些语法。

$(function () {
$("#login_form").submit(function () {
    alert('started js');
    //get the username and password  
    var username = $('#username').val();
    var password = $('#password').val();

    //use ajax to run the check  
    $.post("../php/checklogin.php", { username: username, password: password }, 
        function (result) {
            alert('finished post');
            //if the result is not 1  
            if (result == 0) {
                //Alert username and password are wrong 
                $('#login').html('Credentials wrong');
                alert('got 0');
            }
    });
});

}); });

Here is the php 这是PHP

session_start();
include 'anonconnect.php';

// username and password sent from form 
$myusername= $_POST['username']; 
$mypassword= $_POST['password']; 

$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$sql = $sql->fetch();

$admin = $sql['admin'];

$password_hash = $sql['UserPass'];
$salt = $sql['salt'];

/*** close the database connection ***/
$dbh = null;

if(crypt($mypassword, $salt) == $password_hash){
    // Register $myusername, $mypassword and redirect to file
    $_SESSION['myusername'] = $myusername;
    $_SESSION['loggedin'];
    $_SESSION['loggedin'] = 1;

    if($admin == 1){
        $_SESSION['admin'] = 1;
    }

    header("location:search.php");
}
else {
    $_SESSION['loggedin'];
    $_SESSION['loggedin'] = 0;
    echo 0;
}

Ok so I'll take a stab at this, see if we can work this out. 好吧,我将对此进行介绍,看看我们是否可以解决。 First, let's clean up your code a little bit - clean code is always easiest to debug: 首先,让我们清理一下代码-清理代码始终最容易调试:

$(function () {
  $("#login_form").on('submit', function(){
    console.log('form submitted');

    // get the username and password  
    var login_info = { username: $('#username').val(), password: $('#password').val() }

    // use ajax to run the check
    $.ajax({
      url: '../php/checklogin.php',
      type: 'POST',
      data: login_info,
      success: loginHandler
      error: function(xhr, status, err){ console.log(xhr, status, err); }
    });

   return false;

  });

  function loginHandler(loggedIn){
    if (!loggedIn) {
      console.log('login incorrect');
    } else {
      console.log('logged in');
    }
  }

});

...ok great, we're looking a little better now. ...好极了,我们现在看起来要好一些。 Let's go over the changes made quickly. 让我们回顾一下快速进行的更改。


  • First, swapped alert s for console.log s - much less annoying. 首先,交换alert S代表console.log秒-恼人的要少得多。 Open up your console to check this out -- command + optn + J if you're using Chrome. 打开控制台进行检查-如果使用的是Chrome,请使用command + optn + J

  • Second, we compressed the login info a bit - this is just aesthetics and makes our code a little cleaner. 其次,我们稍微压缩了登录信息-这只是美观,使我们的代码更加简洁。 Really you should be using variables when they need to be used again, and in this case you only use them once. 确实,当需要再次使用变量时,应该使用变量,在这种情况下,只需使用一次。

  • Next, we swapped the $.post function for $.ajax . 接下来,我们将$.post函数替换为$.ajax This gives us two things -- one is a little finer control over the request details, and the second is an error callback, which in this case is especially important since you almost certainly are getting a server error which is your original problem. 这给了我们两件事–一是对请求详细信息的更好控制,其二是错误回调,在这种情况下,这尤其重要,因为您几乎肯定会收到服务器错误,这是您的原始问题。 Here are the docs for $.ajax for any further clarification. 这是$.ajax的文档, $.ajax进行进一步的说明。

  • We're also pointing the success handler to a function to minimize the nesting here. 我们还将成功处理程序指向一个函数,以最大程度地减少此处的嵌套。 You can see the function declared down below, and it will receive the data returned by the server. 您可以在下面看到向下声明的函数,它将接收服务器返回的数据。

  • Finally we're returning false so that the page doesn't refresh. 最后,我们返回false,以便页面不会刷新。


Now, let's get to the issue. 现在,让我们解决这个问题。 When you use this code, you should see a couple things in your console. 使用此代码时,您应该在控制台中看到几件事。 The first will probably be a red message with something like 500 internal server error , and the second should be the results of the error callback for the ajax function. 第一个消息可能是红色消息,带有类似500 internal server error消息,第二个消息应该是ajax函数的错误回调的结果。 You can get even more details on this in Chrome specifically if you click over to the Network Tab and look through the details of the request and response. 如果您单击“ 网络”选项卡并浏览请求和响应的详细信息,则可以在Chrome中获得有关此操作的更多详细信息。

I can't fix your PHP because you didn't post it, but I'll assume you'll either follow up with an edit or figure that out yourself. 我无法修复您的PHP,因为您没有发布它,但是我认为您将继续进行编辑或自己弄清楚。 Once you have the server issue ironed out, you should get back a clean console.log with the response you sent back, and you can move ahead. 解决服务器问题后,您应该返回干净的console.log以及发送回的响应,然后就可以继续进行。

Alternately, this will work because of the lack of page refresh in which case you can ignore the previous 2 paragraphs and declare victory : ) 或者,由于缺少页面刷新,因此可以使用这种方法,在这种情况下,您可以忽略前两段并声明胜利:)

Hope this helps! 希望这可以帮助!

Ah, so damned obvious. 啊,真该死。 You aren't cancelling the default submit action so the form is submitting normally. 您没有取消默认的提交操作,因此表单可以正常提交。 Add this 加上这个

$("#login_form").submit(function (e) {
    e.preventDefault();

    // and so on

See http://api.jquery.com/event.preventDefault/ 参见http://api.jquery.com/event.preventDefault/

you need to change 2nd line and add the e.preventDefault to prevent the form from refreshing the whole page. 您需要更改第二行并添加e.preventDefault,以防止表单刷新整个页面。

$("#login_form").submit(function (e) {
    e.preventDefault();

Also I would change the AJAX request to use GET and change the code in PHP to read variables from GET so you can easily test the PHP page is working by running it in the browser like this checklogin.php?username=x&password=y 另外,我将更改AJAX请求以使用GET并更改PHP中的代码以从GET读取变量,因此您可以通过在浏览器中运行它(如checklogin.php?username = x&password = y)来轻松测试PHP页面是否正常工作

try this: 尝试这个:

$("#login_form").submit(function () {
    alert('started js');
    //get the username and password  
    var username = $('#username').val();
    var password = $('#password').val();

    //use ajax to run the check  
    $.post("../php/checklogin.php", { username: username, password: password }, function (result) {
        alert('finished post');
        //if the result is not 1  
        if (result == '0') {
        //Alert username and password are wrong 
            $('#login').html('Credentials wrong');
            alert('got 0');
        }
    }, 'text');
});
  1. }, 'text'); },'text');

maybe the server does not give the right data format. 可能是服务器没有提供正确的数据格式。 for example, if you request for json, and the jQuery cannot convert result sting to json. 例如,如果您请求json,而jQuery无法将结果字符串转换为json。 then the function would not be executed and then you would not able to get 'alert('got 0');' 那么该函数将不会执行,那么您将无法获得'alert('got 0');' thing. 事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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