How to access the php variable from my external javascript file

advertisements

How to access the php variable from my external javascript file.

this is my getting.js file

$(function(){

$(".search").keyup(function() 

{ 

var searchid = $(this).val();

var dataString = 'search='+ searchid;

if(searchid!='')

{

    $.ajax({
    type: "POST",
    url: "search.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $("#result").html(html).show();
    }
    });
}return false;
});

and this my search.php file.

<?php

include('db.php');

if($_POST)
{

$q=$_POST['search'];

$sql_res=mysql_query("select id,name,email from detail where name like '%$q%' or email like '%$q%' order by id LIMIT 5");

while($row=mysql_fetch_array($sql_res))

{
$username=$row['name'];

$email=$row['email'];

$b_username='<strong>'.$q.'</strong>';

$b_email='<strong>'.$q.'</strong>';

$final_username = str_ireplace($q, $b_username, $username);

$final_email = str_ireplace($q, $b_email, $email);

?>
<div class="show" align="left">

<span class="name"><?php echo $username; ?></span>&nbsp;<br/><?php echo $email; ?><br/>

</div>

<?php

}

}

?>

I want to use $username in my getting.js file. how do I access this. Please let me know.


I love php, which does not knew about html at all.

Try to change your search.php to return json instead of html:

...
$result = array('users' => array(), 'method'=>'search');
while($row=mysql_fetch_array($sql_res))
{
  $result['users'][] = $row;
}
header('Content-type: application/json; charset=UTF-8');
echo json_encode($result);

and handle all received data in javascript:

success: function(json) {
 var data = JSON.parse(json);
 console.log(data);
 // change DOM with new data etc.
}