简体   繁体   中英

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

<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

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

data: { "ajax-data": textboxvalue }

You should too add data type to be returned with the parameter if you want to return JSON for example

dataType: 'JSON',

and Yes I think you should better write

data: { "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

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. 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. you should use mysqli or PDO

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

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 . it will auto calculate the rows.

Check working example

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