如何Ajax和PHP的工作? [英] How does Ajax work with PHP?

查看:119
本文介绍了如何Ajax和PHP的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用AJAX和PHP的烦恼。我想要做的是调用一个Ajax功能,抓住从表单的输入值,并检查是否在数据库中的电子邮件存在。这是我目前的javascript:

I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:

//Checks for Existing Email
function checkExisting_email() {
    $.ajax({
        type: 'POST',
        url: 'checkExist.php',
        data: input
    });

emailExists = checkExisting_email();

//If it exists
if (emailExists) {
    alert("This email already exists!");
}

不幸的是,我不能让我的警惕熄灭。在我的PHP函数,它检查输入的是否是用户名或电子邮件(只是我的目的,所以你懂的),然后寻找它或者列研究。如果它发现它,它返回true,如果没有,则返回false:

Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:

include ('func_lib.php');
connect();
check($_POST['input']);

function check($args)
{
    $checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
    if (!preg_match($checkemail, $args)) {
        //logic for username argument
        $sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
        $res = mysql_query($sql) or die(mysql_error());

        if (mysql_num_rows($res) > 0) {
            return true;
        } else {
            return false;
        }
    } else {
        //logic for email argument
        $sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
        $res = mysql_query($sql) or die(mysql_error());

        if (mysql_num_rows($res) > 0) {
            return true;
        } else {
            return false;
        }
    }

}

所以我的问题是,如何将这些收益AJAX响应,以及​​如何使AJAX功能来呢?主要是,为什么不这项工作?

SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?

任何帮助是非常AP preciated。谢谢!

Any help is very much appreciated. Thank you!

推荐答案

您需要将成功选项添加到您的Ajax请求,这是一个被执行的JS功能当XHR成功。看一看在 jQuery的文档获得更多的信息。

You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.

如果没有运行该脚本,我想你会发现, $ _ POST ['输入'] 是空的;你需要通过你的数据,像数据:{输入:输入}

Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.

您的PHP还需要返回一些内容脚本;考虑更改您的来电检查()来是这样的:

Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:

echo (check($_POST) ? 'true' : 'false');

您现在可以检查JavaScript中的内容。

You can now check the content in JavaScript.

这篇关于如何Ajax和PHP的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆