使用 php 从 ajax 选择文本框中的值


Select value into the textbox FROM ajax using php

无论用户名是否可用,我都在尝试从数据库中获取结果。但它没有给出任何结果,我没有得到 ajax 响应,这是 html 代码

<form id="user_form">
        <input placeholder="username here" type="text" name="ajax-data" id="ajax-data">
        <input type="submit" name="btnSubmit" id="btnSubmit" Value="Submit">
    </form>
    <span class="php_responce_here"></span>

这是我使用的 ajax 代码

     $(document).ready(function()
         {
    $("form#user_form").click(function()
    {
        var textboxvalue = $('input[name=ajax-data]').val();
        $.ajax(
        {
            type: "POST",
            url: 'second.php',
            data: {ajax-data: textboxvalue},
            success: function(result)
            {
                $(".php_responce_here").html(result);
            }
        });
    });
});​
                </script>

PHP 的最终代码,我使用验证和查询来查找用户名在数据库中是否可用,问题是它没有给出任何结果

         <?php
error_reporting(0); 
    require "config.php";// configuration file holds the database info
    $user_name = $_POST['ajax-data']; // textbox in the html

    if($user_name)
    {
        $usernamecheck=  mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
        $check=  mysql_fetch_row($usernamecheck);
        if($check[0]==0)
        {
            if($user_name!=""){
                if(strlen($user_name)>25){
                    echo "You have reached the maximum limit";
                }
                else{
                    echo "User name is valid";
                 }
            }
            else
            {
                echo "username is empty";   
            }
        }
        else{
           echo "Username Already Taken";
       }
    }
?>

应该是提交事件而不是点击:

$("form#user_form").submit(function(e) {
    e.preventDefault();
    var textboxvalue = $('input[name=ajax-data]').val();
    $.ajax(
    {
        type: "POST",
        url: 'second.php',
        data: { "ajax-data": textboxvalue },
        success: function(result) {
            $(".php_responce_here").html(result);
        }
    });
});

正如@Cyril博格努指出的那样;

data: { "ajax-data": textboxvalue }
例如,

如果要返回 JSON,则还应添加要与参数一起返回的数据类型

数据类型:"JSON",

是的,我认为你应该更好地写

data: { "ajax-data": textboxvalue }

所以更新应该是

$(document).ready(function()
{
    $("form#user_form").click(function()
    {
    var textboxvalue = $('input[name=ajax-data]').val();
    $.ajax(
            {
                type: "POST",
                url: 'second.php',
                dataType: 'JSON',
                data: {"ajax-data": textboxvalue},
                success: function(result)
                {
                    $(".php_responce_here").html(result.message);
                }
        });
    });
});

并从 PHP 脚本返回 json 字符串

<?php
error_reporting(0);
require "config.php"; // configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html

if ($user_name) {
    $usernamecheck = mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
    $check = mysql_fetch_row($usernamecheck);
    if ($check[0] == 0) {
        if ($user_name != "") {
            if (strlen($user_name) > 25) {
                $message = "You have reached the maximum limit";
            } else {
                $message = "User name is valid";
            }
        } else {
            $message = "username is empty";
        }
    } else {
        $message = "Username Already Taken";
    }
    echo json_encode(["message" => $message]);
}
?>

注意:mysql已被弃用。 您应该使用mysqliPDO

您的代码中存在一些错误。请检查以下代码。它应该可以工作。

<script>
    $(document).ready(function () {
        $("form").submit(function (event) {
            var textboxvalue = $("#ajax-data").val();
            $.ajax({
                data: {ajaxdata: textboxvalue},
                type: "POST",
                url: 'second.php',
                success: function (result)
                {
                    $(".php_responce_here").html(result);
                }
            });
            return false;
        });
    });
</script>

不能使用 - 创建变量ajax-data

.PHP

$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$user_name'");
$check = mysql_num_rows($usernamecheck);

您应该使用 mysql_num_rows 而不是 mysql_fetch_row 。 它将自动计算行。

检查工作示例

空页面?什么都没有打印出来?

<?php
  error_reporting(-1);
  ini_set('display_errors', 1);
  require "config.php";// configuration file holds the database info  
  if(isset($username = $_POST['ajax-data'])){
    if($l = strlen($username) <= 25 && $l > 2){
      $sql = "SELECT * FROM users WHERE username='$username'"; // wide open for SQL injections. use mysqli or PDO instead.
      if($rsl = mysql_query($sql) != false){ // ALWAYS verify if your query's ran successfully.
        if(mysql_num_rows($rsl) != 0){
          echo 'Username already exists';
        } else {
          echo 'Username is available';
        }
      } else {
        echo 'Query failed: ' . mysql_error();
      }
    } else {
      echo $l > 25 ? 'Reached limit' : 'Needs to be longer';
    }
  } else {
    echo "post['ajax-data'] not set<'br>";
    print_r($_POST);
  }
?>

然后是我的Javascript代码,我有疑问。然而,您有一个提交按钮,但您想检查它在更改时是否有效?

$(document).ready(function(){
  $("#user_form").submit(function(event){
    event.preventDefault();
    $.ajax({
      url: "second.php",
      type: "post",
      data: $(this).serialize(),
      success: function(result){
        $(".php_responce_here").html(result);
      }
    });
  });
});​