NetworkError: 500 Internal Server Error in Ajax $post request - php

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));

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

Jquery php mysql login does send data to mysql but doesn't return right value?

Question: I can see that the data is getting written to the database but $action doesn't become register in the insert.php call from the html file and hence php JSON return is NULL ??
<!DOCTYPE html>
<html>
<head>
<title>Load </title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
Register
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="registerp">
<div data-theme="a" data-role="header">
<h3>Register</h3>
</div>
<div data-role="content">
<form id="registerform" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="fname">First Name:</label>
<input type="text" value="" name="fname" id="fname"/>
</div>
<div data-role="fieldcontain">
<label for="lname">Last Name:</label>
<input type="text" value="" name="lname" id="lname"/>
</div>
<div data-role="fieldcontain">
<label for="uname">User Name:</label>
<input type="text" value="" name="uname" id="uname"/>
</div>
<div data-role="fieldcontain">
<label for="pwd">Enter your password:</label>
<input type="password" value="" name="pwd" id="pwd"/>
</div>
<div data-role="fieldcontain">
<label for="email">Email:</label>
<input type="text" value="" name="email" id="email"/>
</div>
<input type="button" data-theme="b" name="submit" id="register" value="Register">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3>Welcome Page</h3>
</div>
<div data-role="content">
Welcome
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
<script type="text/javascript">
$(document).on('pageinit', '#login', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: "action=login&" + $('#check-user').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert('Log on unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
<script type="text/javascript">
$(document).on('pageinit', '#registerp', function(){
$(document).on('click', '#register', function() {
if($('#uname').val().length > 0 && $('#pwd').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'insert.php',
data: "action=register&" + $('#registerform').serialize(),
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#second");
} else {
alert(' Try again later ! Server is busy !');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
</script>
</body>
</html>
While my PHP Script is simple as shown below... please help
<?php
$con=mysqli_connect("...............", "...........", ".........","........");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$fname = mysqli_real_escape_string($con, $_POST['fname']);
$lname = mysqli_real_escape_string($con, $_POST['lname']);
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['pwd']);
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
$sql="INSERT INTO userdb (username, fname, lname, password, email) VALUES ('$uname', '$fname', '$lname', '$password','$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
if($action == 'register'){
$output = array('status' => true, 'message' => 'Registered');
}
echo json_encode($output);
?>
Insert php script doesnt work while the below register php script works fine.
<?php
// We don't need action for this tutorial, but in a complex code you need a way to determine Ajax action nature
$action = $_POST['action'];
// Decode JSON object into readable PHP object
//$formData = json_decode($_POST['formData']);
// Get username
$username = $_POST['username'];
// Get password
$password = $_POST['password'];
$db = #mysql_connect('..........', '........', '..........') or die("Could not connect database");
#mysql_select_db('users', $db) or die("Could not select database");
$result = mysql_query("SELECT `password` FROM `userdb` WHERE `username`= '$username'");
$r = mysql_fetch_assoc($result);
$pass_ret = $r['password'];
// Lets say everything is in order
if($action == 'login' && $password == $pass_ret){
$output = array('status' => true, 'message' => 'Login');
}
else
{
$output = array('status' => false, 'message' => 'No Login');
}
echo json_encode($output);
?>
You should use Chrome Dev Tools or Firebug in Firefox to inspect the response from the AJAX call. You set the call to expect JSON as the data type and you also use it as JSON. The problem is you have this line:
echo "1 record added";
Which is output before your JSON. So your response probably looks something like:
1 record added{"status": false, "message": "No Login"}
This isn't valid JSON and it will not parse, and thusly this line will never work:
if(result.status) {

No alert in success function

I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>

Retrieving and posting session data

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;
});

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