ajax请求,查询数据库,json_encode,成功返回,显示结果

ajax请求,查询数据库,json_encode,成功返回,显示结果

问题描述:

I'm working on a new piece of code and I'm new to ajax so I cant get it to work. I've got a textbox that has a javascript onKeyUp assigned to it. The first function is a delay function. It sets a delay timer, and as long as no other request is made via that delay timer, it runs a second function with the ajax after a certain time period. Inside the ajax, it runs a database query located in the second file based on the text that was entered in the textbox. It sets up an array of the results, json_encodes them, and returns them back to the original page. Then, I need to populate the page with the results (with php).

The Textbox

<input type="text" onKeyUp="delay_method('search_customer',search_customer(this.value),'2000')" />

The delay function

<script type="text/javascript">
function delay_method(label,callback,time){
    if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}  
    delayed_methods[label]=Date.now();
    var t=delayed_methods[label];
    setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{  callback();}}, time||500);
  }
</script>

The ajax function

<script type="text/javascript">

function search_customer(value){    

console.log(value); 

    $.ajax({
  type: "POST",
  url: "secondpage.php",
  data: query,
  dataType: 'json',
  success: function(data){
    console.log(data.name); // customer name
    console.log(data.company);   // customer company name
  }
});
}

</script>

second page

set up an array for testing. Bypassing the query for now. Just need to get results back into main page. I can set up the array from the php once its working. My query will use LIKE %search text%

$arr = array(
  'name'=>'overflow',
  'company'=>'value'
);
echo json_encode($arr);

I have NO clue how to retrieve the data from the ajax function and populate the results. I would love to get the results back into a php array, and then loop through the array to echo out the results. I can loop through the array in php...my biggest concern is getting the results back into a php array.

Any assistance would be great. I cant seem to get the code to work. I am new to ajax so I'm learning this as I go.





UPDATE

Everything is working the way it should except the delay. Its not putting a delay on anything. I need it to wait for 2 seconds from each keyup before it activates the ajax function. If it receives another keyup, it waits an additional 2 seconds. IT continues until there is 2 seconds with no keyups. That way its not querying the database on every single keyup if the person is still typing. Right now its processing everything with each keyup.

textbox

<input type="text" onKeyUp="delay_method('search_customer',search_customer(this.value),'2000')" />

delay

function delay_method(label,callback,time){
    if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}  
    delayed_methods[label]=Date.now();
    var t=delayed_methods[label];
    setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{  callback();}}, time||500);
  }

ajax function

function search_customer(value){    

console.log(value); 

    $.ajax({
  type: "POST",
  url: "secondpage.php",
  data: { "value": value },
  dataType: 'html',
  success: function(data){
      $('#resultDiv').html(data);
  }
});
}

second page:

$value = $_POST['value'];

if ((isset($value)) && ($value != "")) { 
$arr = array();
$search_query = $db1q->query("SELECT first_name, company FROM Users WHERE first_name LIKE '%$value%' OR last_name LIKE '%$value%' OR company LIKE '%$value%'");
if ($search_query->num_rows > 0) {

    while ($search_result = $search_query->fetch_assoc()) {
$arr[$search_result['first_name']] = $search_result['company'];
    }
}

   $html = '';
    $html .= '<div>';
    foreach ($arr as $key => $value) {
        $html .= '<div class="sub-div"><h2>'.$key.'</h2> : ' . '<h4>' . $value . '</h4></div>';
    }
    $html .= '</div>';

echo $html;
}

You can't get the results back into a php array in js. So, what you have to do is to pass processed html in js and just print on page.

For example, In second page

$arr = array(
  'name'=>'overflow',
  'company'=>'value'
);

using above array $arr make html over here and store it in variable. pass that variable into js.

For Ex :

    $html = '';
    $html .= '<div>';
    foreach ($arr as $key => $value) {
        $html .= '<div class="sub-div"><h2>'.$key.'</h2> : ' . '<h4>' . $value . '</h4></div>';
    }
    $html .= '</div>';

echo $html;

Now you will get html in your ajax success. just show on div like

$('resultDiv').html(data);

There are multiple commas after URL tag in ajax request remove it like following:

 url: "secondpage.php",

Generally, the ajax request format should be the following using jQuery:

var index=0;
var menuId = $( "ul.nav" ).first().attr( "id" );
var request = $.ajax({
  url: "script.php",
  method: "POST",
  data: { id : menuId },
  dataType: "html"
});

request.done(function( msg ) {
  index++;
  //Append the result to the js array and then try storing the array value to PHP using HTML;
  //Call your next event;
  $( "#log" ).html( msg );
});

request.fail(function( jqXHR, textStatus ) {
  alert( "Request failed: " + textStatus );
});

Now for your logic rather go with delayed call you should be using done or success event. Inside the success event, you should be calling next requirement. Because Ajax is asynchronous.

Your problem with my snippet of code (The delay function) is that on the keyup event when you are calling the delay function and passing the function/callback argument you are calling it and executing it immediately which is not the purpose of it. You should pass it as a function that then calls your functions ( in a closure way). Because of that, the closure will lost the parent context of (this) in this case the input.. so to solve it, you should use the bind javascript method, to preserve the "this" parent and its properties like value

The correct input onkeyup event becomes this one:

<input type="text" onKeyUp="delay_method('search_customer',function(){search_customer(this.value);}.bind(this),'2000')" />