简体   繁体   中英

Why isset post doesn't work with ajax search using PHP?

I have the problem with search using PHP and AJAX. Currently, when I type something, then I see only numbers in console and echo doesn't work.

If I delete if (isset($_POST['invite'])) { and type whatever, then echo display users, but search doesn't work.

Where I made a mistake?

$(document).ready(function() {
  $('#invite_cc').keyup(function() {
    var query = $(this).val();
    if (query != '') {
      $.ajax({
        url: 'form-search-user.php',
        type: 'POST',
        data:{query:query},
        success: function(response) {
          $('#invite_result_cc').html(response);
          console.log(response);
        }
      });
    }
  });
});

form-search-user.php

<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/mysql/config.php');

if (isset($_POST['invite'])) {

  $invite_rows_cc = $db->QueryGetNumRows("SELECT * FROM user_about WHERE firstname LIKE '%".$_POST['invite']."%' OR lastname LIKE '%".$_POST['invite']."%' LIMIT 5");
  $invite_value_cc = $db->QueryFetchArrayAll("SELECT * FROM user_about WHERE firstname LIKE '%".$_POST['invite']."%' OR lastname LIKE '%".$_POST['invite']."%' LIMIT 5");

  if ($invite_rows_cc > 0) {

    foreach ($invite_value_cc as $key) {
      echo "
      <div class='invite_search_cont'>
        <div class='invite_search_img'><img src='{$key['profile_image']}'></img></div>
        <div class='invite_search_name'>{$key['firstname']} {$key['lastname']}</div>
      </div>
      ";
    }

  } else {

    echo 'No results';

  }

}

HTML

<input type='text' name='invite' value='' id='invite_cc' placeholder='Search' class='form-control'>
<div id='invite_result_cc'></div>

You're not sending anything named 'invite' in you post array:

data:{query:query}

You can fix that by adding the proper key: value pair:

data:{query:query, invite:'invite'}

Now $_POST['invite'] will be set to 'invite'. You can use whatever variable value you would like. For example:

if (isset($_POST['invite']) && 'invite' == $_POST['invite'])...

EDIT I can see now you intend $_POST['invite'] to contain the search value, so make the following changes to your AJAX:

data:{invite :query}

This set the name of the variable $_POST['invite'] and makes that array variable's value the value of query

Change

if (isset($_POST['invite'])) {

to

if (isset($_POST['query'])) {

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