简体   繁体   English

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

[英]Select value into the textbox FROM ajax using php

I am trying to get the results from the database whether username is available or not . 无论用户名是否可用,我都试图从数据库中获取结果。 But it is not giving any results i am not getting ajax response this is the html code 但是它没有给出任何结果,我没有得到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>

This is the ajax code which i have used 这是我用过的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>

final code of php where i have used the validation and the query to find whether the username is available in the database or not the problem is that it is not giving any of the result 我在其中使用验证和查询来查找用户名是否在数据库中可用的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";
       }
    }

?>

should be submit event not click: 应该是提交事件,不要单击:

$("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);
        }
    });
});

and as @Cyril BOGNOU pointed out; 正如@Cyril BOGNOU所指出的;

data: { "ajax-data": textboxvalue }

You should too add data type to be returned with the parameter if you want to return JSON for example 如果您想返回JSON,也应该添加数据类型以与参数一起返回

dataType: 'JSON', dataType:“ JSON”,

and Yes I think you should better write 是的,我认为你最好写

data: { "ajax-data": textboxvalue } 数据:{“ ajax-data”:textboxvalue}

So the update should be 所以更新应该是

$(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);
                }
        });
    });
});

and return json string from PHP script 并从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]);
}

?>

Empty page? 空页? Nothing prints out? 什么都没打印出来?

<?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);
  }

?>

Then there is your Javascript code that I have questions on. 然后是您有疑问的Javascript代码。 Yet you have a submit button but you want to check if its valid upon change? 但是,您有一个提交按钮,但是您想检查其更改后是否有效?

$(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);
      }
    });
  });
});​ 

NOTE : mysql is deprecated. 注意:不建议使用mysql you should use mysqli or PDO 您应该使用mysqliPDO

There are some mistakes in your code. 您的代码中有一些错误。 check the below code. 检查以下代码。 it should work. 它应该工作。

<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>

You can not create variable ajax-data with - . 您不能使用-创建变量ajax-data

PHP PHP

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

you should use mysql_num_rows instead of mysql_fetch_row . 您应该使用mysql_num_rows而不是mysql_fetch_row it will auto calculate the rows. 它将自动计算行。

Check working example 检查工作示例

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

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