Retrieving and posting session data - php

I am creating a chat box, retrieving the user_id saved in the session and then using the ajax post but for some reason the user_id that is saved in the session is empty and not saving in the database and I am stocked now.
Controller
function add_chat_messages() {
// Grab the $chat_message_content, $user_id and $chat_id
$user_id = $this->session->userdata("user_id");
$chat_message_content = $this->input->post('chat_message_content');
$this->abt_db->add_chat_message($user_id, $chat_message_content);
}
Model
function add_chat_message($user_id, $chat_message_content) {
$query_str = "INSERT INTO chat_message(user_id, chat_message_content) VALUES (?,?)";
$this->db->query($query_str, array($user_id, $chat_message_content));
}
function set_session() {
// session->set_userdata is a CodeIgniter function that
// stores data in a cookie in the user's browser. Some of the values are built in
// to CodeIgniter, others are added (like the user_id).
$this->session->set_userdata(array(
'user_id' => $this->details->user_id,
'email' => $this->details->email,
'username' => $this->details->username,
'isLoggedIn' => true
)
);
}
View
<script type="text/javascript">
var user_id = "<?php echo $this->session->userdata('user_id'); ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
<!--loads the header-->
<?php $this->load->view('abt-header'); ?>
<!--this is the login page-->
<div data-role="page" id="Abt-chat" data-add-back-btn="true">
<div data-role="header" data-position="fixed">
<h1>Peer Chat</h1>
</div>
<div data-role="content">
<div data-role="fieldcontain">
<div id="chat_viewport"></div>
<p>
<label>Input Chat: </label>
<input name="chat" id="chat" type="text" value=""/>
</p>
<p>
<?php echo anchor('#', 'Send Chat', array('title' => 'Send Chat', 'id' => 'submit')); ?>
</p>
</div>
<?php echo form_close(); ?>
</div>
</div>
Javascript file
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
$(document).ready(function(){
$("a#submit").click(function(){
var chat_message_content = $("input#chat").val();
if(chat_message_content == ""){
return false;
}
$.post(base_url + "index.php/abovetheblues/add_chat_messages", {
chat_message_content : chat_message_content,
user_id : user_id
},
function(data){
alert(data);
},"json");
return false;
});
return false;
});

Related

Select ajax with an app built using CodeIgniter

I have a company_model and a controller. I also have 3 corresponding tables in a database for where the data is saved and read from. The goal of this is to manage companies linked to sub holdings and the corresponding directors of the sub holdings.
When I add a new company, the Sub holding and Director fields work perfectly. My issue is when editing an already saved company, the corresponding Director field is not populated or populating. I have been trying to find the issue for sometime now, I am not receiving any console errors or Network XHR when checking with Chrome. I know this is going to be a simple fix, I can not see it or find the issue. Any advice or pointers would be greatly appreciated
The Database structure is as follows:
Table 1 is for the director information (director_id, director_name, director_subholding_id)
Table 2 is for subholding information (subholding_id, subholding_name)
Table 3 is for company information (company_id, company_name, ceo_name, company_subholding_id,
company_director_id)
Company_Model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Company_model extends CI_Model{
function get_subholding(){
$query = $this->db->get('subholding');
return $query;
}
function get_director($subholding_id){
$query = $this->db->get_where('director', array('director_subholding_id' => $subholding_id));
return $query;
}
function save_company($company_name,$subholding_id,$director_id,$ceo_name){
$data = array(
'company_name' => $company_name,
'ceo_name' => $ceo_name,
'company_subholding_id' => $subholding_id,
'company_director_id' => $director_id
);
$this->db->insert('company',$data);
}
function get_company(){
$this->db->select('company_id,company_name,ceo_name,subholding_name,director_name');
$this->db->from('company');
$this->db->join('subholding','company_subholding_id = subholding_id','left');
$this->db->join('director','company_director_id = director_id','left');
$query = $this->db->get();
return $query;
}
function get_company_by_id($company_id){
$query = $this->db->get_where('company', array('company_id' => $company_id));
return $query;
}
function update_company($company_id,$company_name,$subholding_id,$director_id,$ceo_name){
$this->db->set('company_name', $company_name);
$this->db->set('ceo_name', $ceo_name);
$this->db->set('company_subholding_id', $subholding_id);
$this->db->set('company_director_id', $director_id);
$this->db->where('company_id', $company_id);
$this->db->update('company');
}
//Delete Product
function delete_company($company_id){
$this->db->delete('company', array('company_id' => $company_id));
}
Company Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Company extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('Company_model','company_model');
$this->load->library('session');
}
function index(){
$data['companies'] = $this->company_model->get_company();
$this->load->view('company_list_view',$data);
}
// add new company
function add_new(){
$data['subholding'] = $this->company_model->get_subholding()->result();
$this->load->view('add_company_view', $data);
}
// get sub category by category_id
function get_director(){
$subholding_id = $this->input->post('id',TRUE);
$data = $this->company_model->get_director($subholding_id)->result();
echo json_encode($data);
}
//save company to database
function save_company(){
$company_name = $this->input->post('company_name',TRUE);
$subholding_id = $this->input->post('subholding',TRUE);
$director_id = $this->input->post('director',TRUE);
$ceo_name = $this->input->post('ceo_name',TRUE);
$this->company_model->save_company($company_name,$subholding_id,$director_id,$ceo_name);
$this->session->set_flashdata('msg','<div class="alert alert-success">Company Saved</div>');
redirect('company');
}
function get_edit(){
$company_id = $this->uri->segment(3);
$data['company_id'] = $company_id;
$data['subholding'] = $this->company_model->get_subholding()->result();
$get_data = $this->company_model->get_company_by_id($company_id);
if($get_data->num_rows() > 0){
$row = $get_data->row_array();
$data['director_id'] = $row['company_director_id'];
}
$this->load->view('edit_company_view',$data);
}
function get_data_edit(){
$company_id = $this->input->post('company_id',TRUE);
$data = $this->company_model->get_company_by_id($company_id)->result();
echo json_encode($data);
}
//update company to database
function update_company(){
$company_id = $this->input->post('company_id',TRUE);
$company_name = $this->input->post('company_name',TRUE);
$subholding_id = $this->input->post('subholding',TRUE);
$director_id = $this->input->post('director',TRUE);
$ceo_name = $this->input->post('ceo_name',TRUE);
$this->company_model-
>update_company($company_id,$company_name,$subholding_id,$director_id,$ceo_name);
$this->session->set_flashdata('msg','<div class="alert alert-success">Company Updated</div>');
redirect('company');
}
//Delete Company from Database
function delete(){
$company_id = $this->uri->segment(3);
$this->company_model->delete_company($company_id);
$this->session->set_flashdata('msg','<div class="alert alert-success">Company Deleted</div>');
redirect('company');
}
Edit Company View
<!DOCTYPE html>
<html>
<head>
<title>Edit Company</title>
<link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="row justify-content-md-center">
<div class="col col-lg-6">
<h3>Edit Company:</h3>
<form action="<?php echo site_url('company/update_company');?>" method="post">
<div class="form-group">
<label>Company</label>
<input type="text" class="form-control" name="company_name" placeholder="Company
Name" required>
</div>
<div class="form-group">
<label>Subholding</label>
<select class="form-control subholding" name="subholding" required>
<option value="">No Selected</option>
<?php foreach($subholding as $row):?>
<option value="<?php echo $row->subholding_id;?>"><?php echo $row->subholding_name;?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Director</label>
<select class="form-control director" name="director" required>
<option value="">No Selected</option>
</select>
</div>
<div class="form-group">
<label>CEO</label>
<input type="text" class="form-control" name="ceo_name" placeholder="CEO Name"
required>
</div>
<input type="hidden" name="company_id" value="<?php echo $company_id?>" required>
<button class="btn btn-success" type="submit">Update Company</button>
</form>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>"></script>
<script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
<script type="text/javascript">
$(document).ready(function(){
//call function get data edit
get_data_edit();
$('.subhodling').change(function(){
var id=$(this).val();
var director_id = "<?php echo $director_id;?>";
$.ajax({
url : "<?php echo site_url('company/get_director_id');?>",
method : "POST",
data : {id: id},
async : true,
dataType : 'json',
success: function(data){
$('select[name="director"]').empty();
$.each(data, function(key, value) {
if(director_id==value.director_id){
$('select[name="director"]').append('<option value="'+ value.director_id
+'" selected>'+ value.director_name +'</option>').trigger('change');
}else{
$('select[name="director"]').append('<option value="'+ value.director_id
+'">'+ value.director_name +'</option>');
}
});
}
});
return false;
});
//load data for edit
function get_data_edit(){
var company_id = $('[name="company_id"]').val();
$.ajax({
url : "<?php echo site_url('company/get_data_edit');?>",
method : "POST",
data :{company_id :company_id},
async : true,
dataType : 'json',
success : function(data){
$.each(data, function(i, item){
$('[name="company_name"]').val(data[i].company_name);
$('[name="subholding"]').val(data[i].company_subholding_id).trigger('change');
$('[name="director"]').val(data[i].company_director_id).trigger('change');
$('[name="ceo_name"]').val(data[i].ceo_name);
});
}
});
}
});
</script>
</body>
</html>
In your view, the select field for the Director is:
<select class="form-control director" name="directore" required>
Everywhere else in your view, controller and model, you're expecting a variable named director which is not really there, so when you use $this->input->post('director') you're actually getting a NULL value which explains why your updates are not working.
A simple fix would be to change your select to
<select class="form-control director" name="director" required>
and you should be ok

php-mysql login system with ajax

I started learning php lately so i'm not so good with it. I've been trying to create a login system with php/ajax. I've tried all i could but can seem to figure out where the actual problem is coming from. Ajax couldn't get the data from my process.php file even though i already added it in the url. The only codes that get executed are those from the index script but nothing from process. My database connection is ok. Just that there seem to be no communication between ajax and process.php. It just executes the 'else'(data==true) code in Ajax instead. I'm sorry i may not be able to express myself very well but i just hope you understand what i mean.
Below are the files i created.
here is the member.php class
<?php
class member {
public $table;
public function __construct(){
$this->table = "users";
}
//login check
public function check($username,$password,$conn){
$this->table = "users";
//$password_hash = md5($password);
$stmt = $conn->prepare("SELECT * FROM ".$this->table." WHERE
Username='$username' AND Password='$password' LIMIT 1");
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
// print_r($row);
$_SESSION['id'] = $row['id'];
;
$_SESSION['email'] = $row['email'];
return true;
}
} else {
return false;
}
}
}
?>
here is the process.php file
<?php
session_start();
require_once('member.php');
//for login
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username ==""){
echo "Please enter your email";
}
elseif($password == ""){
echo "Please enter your password";
}
else{
//connect to database
require_once('db.php');
//instantiate the member class
$member = new member();
$login_check = $member->check($username,$password,$conn);
if($login_check == true){
echo true;
}
else{
echo "Invalid email or password";
}
}
}
?>
and here is the index file that contains the ajax code
<?php
//session_start();
include('header.php');
require_once('db.php');
require('process.php');
?>
<html lang="en">
<head>
<title>Login/Signup</title>
</head>
<body>
<div class="container">
<div class="content">
<div class="form">
<div id = "message"></div>
<ul class="tab">
<li>LOGIN</li>
<li>SIGNUP</li>
</ul>
<div class="tab-content">
<div class="login-tab">
<form id="login_form" method="post" class="login-
form" >
<div class="">
<input type="text" id = "username"
name="username" class="form-control" placeholder="Enter your Username">
</div>
<div class="">
<input type = "password" id = "password"
name="password" class="form-control" placeholder="Enter your Password">
</div>
<div><button type = "submit" id = "login"
name="login" class="btn btn-primary" >login</button></div>
</form>
<div class="clearfix"></div>
<p>Or Login with</p>
<ul class="alt-login">
<li><img src=""></li>
<li><img src=""></li>
<li><img src=""></li>
</ul>
</div>
<div class="clearfix"></div>
<div class="tab_signup">
<form>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$( document ).ready(function() {
$("#login").click(function(e){
e.preventDefault();
var username = $("#username").val();
var password = $("#password").val();
var data = $("login_form").serialize();
$.ajax({
type : "POST",
url: 'process.php',
data : data,
success: function(data){
if(data==true){
$("#message").addClass('alert alert-success');
$("#message").html("Login successful");
$("#login").html('Redirecting..');
window.location ="dashboard.php";
}
else{
//alert(data);
$("#message").addClass('alert alert-danger');
$("#message").html('login failed');
$("#login").html('Failed');
}
},
error : function(jqXHR,textStatus,errorThrown){
if(textStatus ='error'){
alert('Request not completed');
}
$("#login").html('Failed');
},
beforeSend :function(){
$("#message").removeClass('alert alert-danger');
$("#message").html('');
$("#login").html('Logging in..');
},
});
// }
});
});
</script>
</html>
P.S i'm not bothering about hashing the password now cos i'm still test.
You are passing data using GET method in Ajax but using POST when retrieving data in process.php file. You need to change ajax calling code and should use post method. Also serialize function doesn't append login input element which you need to push manually. I have updated code and it will be like below:
$("#login").click(function (e) {
e.preventDefault();
var data = $("#login_form").serializeArray();
data.push({ name: this.name, value: this.id });
console.log(data);
$.ajax({
type: "POST",
url: 'process.php',
data: data,
success: function (data) {
if (data == true) {
$("#message").addClass('alert alert-success');
$("#message").html("Login successful");
$("#login").html('Redirecting..');
window.location = "dashboard.php";
} else {
$("#message").addClass('alert alert-danger');
$("#message").html('login failed');
$("#login").html('Failed');
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus = 'error') {
alert('Request not completed');
}
$("#login").html('Failed');
},
beforeSend: function () {
$("#message").removeClass('alert alert-danger');
$("#message").html('');
$("#login").html('Logging in..');
},
});
});
You can update your code as it is and it should work fine. Hope it helps you.

Get specific information depends user logged in jquery mobile

I'm developing a jquery mobile app that uses php to get information from the database ( e.g user login ). but I've this problem: I need to display specific information from the database depends on the user logged ( clients and proyects are related one each other by 'project' field in clients and 'id' in projects )
I was trying to add the field 'project' into the 'login' query but when I made this the app couldn't logged
Thanks in advance for your help
----------- index.html --------------
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="theme/css/jquery.mobile.min.css" />
<link rel="stylesheet" href="theme/css/surinteractive.min.css" />
<link rel="stylesheet" href="theme/css/jquery.mobile.icons.min.css" />
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.js"></script>
<script src="js/json.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="a">
<header data-role="header" data-position="fixed">
<h1>Sistema de gestión de Requerimientos</h1>
</header>
<div data-role="content">
<div id="fm">
<form id="form">
<label for="username">User:</label>
<input type="text" value="" name="username" id="username"/>
<label for="password">Pass:</label>
<input type="password" value="" name="password" id="password"/>
<a data-role="button" id="login-button" data-theme="a" class="ui-btn-icon-right ui-icon-plus ui-btn-b">
Sign in
</a>
</form>
</div>
</div>
<footer data-role="footer" data-position="fixed" id="footer">
<p>© Copyright 2014 </p>
</footer>
</div>
<div data-role="page" id="menu" data-theme="a">
<header data-role="header" data-position="fixed">
Back
<h3>Bugs List</h3>
</header>
<div data-role="content">
<h3>Welcome: </h3>
<ul data-role="listview" data-inset="true">
<li>Create a bug</li>
<li>Create an enhacement</li>
</ul>
</div>
<footer data-role="footer" data-position="fixed" id="footer">
<p>© Copyright 2014</p>
</footer>
</div>
</body>
</html>
------------------ json.js --------------------------
$(document).on('pagebeforeshow', '#login', function(){
$('#login-button').on('click', function(){
if($('#username').val().length > 0 && $('#password').val().length > 0){
userObject.username = $('#username').val();
userObject.password = $('#password').val();
var outputJSON = JSON.stringify(userObject);
ajax.sendRequest({action : 'login', outputJSON : outputJSON});
} else {
alert('Please fill all requested information');
}
});
});
var ajax = {
sendRequest:function(save_data){
var address = null;
//address = 'http://127.0.0.1/app/inc/userValidation.php?jsoncallback=?';
$.ajax({url: address,
crossDomain: true,
data: save_data,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.loading('show', {theme:"a", text:"Initializing...", textonly:true, textVisible: true});
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.loading('hide');
},
success: function (result) {
if(result == "true") {
$.mobile.changePage( "#menu", { transition: "slide"} );
} else {
alert('Invalid login. Please try again!'); // In case result is false throw an error
}
// This callback function will trigger on successful action
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Connection error, please try again');
}
});
}
}
// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
username : "",
password : ""
}
------------ userValidation.php -------------------
<?php
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$username = $jsonObject->{'username'}; // Get username from object
$password = $jsonObject->{'password'}; // Get password from object
$connection = null;
$connection = new mysqli('127.0.0.1', 'xxxx', 'xxxx', 'xxxx');
$query = "SELECT * FROM clients WHERE username = '".$username."' and password = '".$password."'";
$result = mysqli_query($connection,$query);
$num = mysqli_affected_rows($connection);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
Database ( Structure & Relationship )
clients
id, name, username, password, projectid, status, creation_date
projects
id, project, description, technologies, status, creation_date
bugs
id name projectid, type, environment,description, status, creation_date
projectid.clients = id.projects
id.projects = projectid.bugs
Objective: Store the username in a global variable to be recovered in another page
Finally I've solved this issue creating a new schema called sessions, when the user signs it to the app, it will be store in that schema. After this, if the user wants to get the list of bugs created a new sql sentence will be called to join 'sessions' in that search

NetworkError: 500 Internal Server Error in Ajax $post request

I am trying to create a chat box and performing this AJAX post in Codeigniter but for some reason I am getting a server 500 internal server error and no response at all when I use firebug? Can anyone help?
This is my Javascript code
$(document).ready(function(){
$("a#submit").click(function(){
var chat_message_content = $("input#chat").val();
if(chat_message_content == ""){
return false;
}
$.post(base_url + "index.php/abovetheblues/add_chat_messages", {
chat_message_content : chat_message_content,
user_id : user_id
},
function(data){
alert(data);
},"json");
return false;
});
return false;
});
This is my controller
function add_chat_messages() {
// Grab the $chat_message_content, $user_id
$user_id = $this->input->post($this->session->userdata("user_id"));
$chat_message_content = $this->input->post('chat_message_content');
$this->abt_db->add_chat_message($user_id, $chat_message_content);
}
This is my model
function add_chat_message($user_id, $chat_message_content) {
$query_str = "INSERT INTO chat_message(user_id, chat_message_content) VALUES (?,?,?)";
$this->db->query($query_str, array($user_id, $chat_message_content));
}
And my view page
<script type="text/javascript">
var user_id = "<?php echo $this->session->userdata("user_id"); ?>";
</script>
<!--loads the header-->
<?php $this->load->view('abt-header'); ?>
<!--this is the login page-->
<div data-role="page" id="Abt-chat" data-add-back-btn="true">
<div data-role="header" data-position="fixed">
<h1>Peer Chat</h1>
</div>
<div data-role="content">
<div data-role="fieldcontain">
<div id="chat_viewport"></div>
<p>
<label>Input Chat: </label>
<input name="chat" id="chat" type="text" value=""/>
</p>
<p>
<?php echo anchor('#', 'Send Chat', array('title' => 'Send Chat', 'id' => 'submit')); ?>
</p>
</div>
<?php echo form_close(); ?>
</div>
</div>
You are passing user id as user_id. But while retrieving it in function you are doing mistake. Change it like below.
$user_id = $this->input->post('user_id');
And also -> need to be there before query()
$this->db->query($query_str, array($user_id, $chat_message_content));

passing id name on click using ajax to php

i am using Ajax to make a filtered search system. I have three different tabs where users can search by names, by category and location.
I am able to seacrh when user enters name in the search box(tab-1).
In second tab, how can I use the same Ajax, so when user clicks a link, the id is passed in the ajax script to my php, and that id is passed as varibale in my mysql query.
First time with Ajax, any help would be highly appreciated.
AJAX script:
$(document).ready(function () {
$("#search_results").slideUp();
$("#button_find").click(function (event) {
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function (event) {
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way() {
$("#search_results").show();
var search_this = $("#search_query").val();
$.post("search.php", {
searchit: search_this
}, function (data) {
$("#display_results").html(data);
})
}
html:
<form id="searchform" method="post">
<input id="search_query" name="search_query" placeholder="What You Are Looking For?"
size="50" type="text" />
<input id="button_find" value="Search" type="submit" />
</form>
<div id="display_results">
</div>
<div class="tab">
<input id="tab-2" name="tab-group-1" type="radio" />
<label for="tab-2">Search by Category</label>
<div class="content">
<div id="searchbycategory">
<div id="nav_1_a">
<ul>
<li>All Categories</li>
<li>Category-1</li>
<li>Category-2</li>
<li>Category-3</li>
</ul>
<div id="display_results">
</div>
</div>
<!-- END nav_1_a -->
</div>
</div>
</div>
<div class="tab">
<input id="tab-3" name="tab-group-1" type="radio" />
<label for="tab-3">Search by location</label>
<div class="content">
<div id="searchbylocation">
<div id="nav_1_a">
<ul>
<li>All</li>
<li>Location-1</li>
<li>Location-2</li>
<li>Location-3</li>
<li>Location-4</li>
</ul>
</div>
search.php:
<?php
$connection = mysql_connect('localhost', 'user', 'pwd');
$db = mysql_select_db('db', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term);
echo "Enter name to search";
else{
$sql = mysql_query("select col1,col2 from tab2 where tab2.somecolm like
'{$term}%'", $connection);
echo "<ul>";
if (mysql_num_rows($sql)){
while($info = mysql_fetch_array($sql, MYSQL_ASSOC ) ) {
echo "<li>";
echo "" . $info['col2'] . "";
echo "</li>";
}
}else{
echo "No matches found!";
}
echo "</ul>";
}
?>
Pass block id to search_ajax_way function:
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way(this.id);
});
Then pass block id in data param in ajax request:
function search_ajax_way(blockId){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this, 'blockId': blockId}, function(data){
$("#display_results").html(data);
})
}
Now blockId will be availible in your php script as $_POST['blockId'].
You say you want to pass the id when a link is clicked, but you don't have any code that handles link clicks. Add a click handler for links, and modify search_ajax_way() to accept an optional id for when links are clicked:
$("a").click(function (event) {
event.preventDefault();
search_ajax_way(this.id);
});
function search_ajax_way(clickedId) {
$("#search_results").show();
var postData = { searchit: $("#search_query").val() };
if (clickedId) {
postData.clickedId = clickedId;
}
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}
The id will be available in PHP as $_POST['clickedId']
Edit: Actually, I'd refactor to use search_ajax_way() as the event handler, rather than calling it from an anonymous event handler:
$("#button_find,a").click(search_ajax_way);
$("#search_query").keyup(search_ajax_way);
function search_ajax_way(event) {
event.preventDefault();
$("#search_results").show();
var postData = {
searchit: $("#search_query").val(),
clickedId: this.id
};
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}

Categories