I'm performing multiple delete records operation using jQuery and php currently i'm able to delete single / multiple records by clicking on checkbox its working fine as of now but my page gets refreshed every time i delete record because im not using ajax.
I'm a beginner in ajax I want to perform this same operation using JQUERY/AJAX which will not make my page reload every time i delete my record so i want to use ajax for the same code so that i can handle my page reload.
Somebody help me out in achieving it Thanks!!
HTML/PHP
<form method="post" name="data_table">
<table id="table_data">
<tr>
<td>Name</td>
<td>Select All <input type="checkbox" id="check_all" value=""></td>
</tr>
<?php
$query = mysql_query("SELECT * FROM `products`");
while($row = mysql_fetch_array($query))
{
?>
<tr>
<td>
<?php echo $row['product_title']; ?>
</td>
<td>
<input type="checkbox" value="<?php echo $row['id'];?>" name="data[]" id="data">
</td>
</tr>
<?php
}
?>
</table>
<br />
<input name="submit" type="submit" value="Delete" id="submit">
</form>
JQuery
jQuery(function($)
{
$("form input[id='check_all']").click(function()
{
var inputs = $("form input[type='checkbox']");
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(this.checked)
{
inputs[i].checked = true;
}
else
{
inputs[i].checked = false;
}
}
}
});
$("form input[id='submit']").click(function()
{ var inputs = $("form input[type='checkbox']");
var vals=[];
var res;
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(inputs[i].id=="data"&&inputs[i].checked){
vals.push(inputs[i].value);
}
}
}
var count_checked = $("[name='data[]']:checked").length;
if(count_checked == 0)
{
alert("Please select a product(s) to delete.");
return false;
}
if(count_checked == 1)
{
res= confirm("Are you sure you want to delete these product?");
}
else
{
res= confirm("Are you sure you want to delete these products?");
}
if(res){
/*** This portion is the ajax/jquery post calling ****/
$.post("delete.php", {data:vals}, function(result){
$("#table_data").html(result);
});
}
});
});
PHP delete code
<?php
if(isset($_POST['data']))
{
$id_array = $_POST['data']; // return array
$id_count = count($_POST['data']); // count array
for($i=0; $i < $id_count; $i++)
{
$id = $id_array[$i];
$query = mysql_query("DELETE FROM `products` WHERE `id` = '$id'");
if(!$query)
{
die(mysql_error());
}
}?>
Please do the changes jquery as
jQuery(function($)
{
$("form input[id='check_all']").click(function()
{
var inputs = $("form input[type='checkbox']");
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(this.checked)
{
inputs[i].checked = true;
}
else
{
inputs[i].checked = false;
}
}
}
});
$("form input[id='submit']").click(function()
{ var inputs = $("form input[type='checkbox']");
var vals=[];
var res;
for(var i = 0; i < inputs.length; i++)
{
var type = inputs[i].getAttribute("type");
if(type == "checkbox")
{
if(inputs[i].id=="data"&&inputs[i].checked){
vals.push(inputs[i].value);
}
}
}
var count_checked = $("[name='data[]']:checked").length;
if(count_checked == 0)
{
alert("Please select a product(s) to delete.");
return false;
}
if(count_checked == 1)
{
res= confirm("Are you sure you want to delete these product?");
}
else
{
res= confirm("Are you sure you want to delete these products?");
}
if(res){
/*** This portion is the ajax/jquery post calling ****/
$.post("delete.php", {data:vals}, function(result){
$("#table_data").html(result);
});
}
});
});
Delete.php as
<?php
if(isset($_POST['data']))
{
$id_array = $_POST['data']; // return array
$id_count = count($_POST['data']); // count array
for($i=0; $i < $id_count; $i++)
{
$id = $id_array[$i];
$query = mysql_query("DELETE FROM `test` WHERE `id` = '$id'");
if(!$query)
{
die(mysql_error());
}
}?>
<tr>
<td>ID</td>
<td>TITLE</td>
<td>Select All <input type="checkbox" id="check_all" value=""></td>
</tr>
<?php
$query = mysql_query("SELECT * FROM `test`");
while($row = mysql_fetch_array($query))
{
?>
<tr>
<td>
<?php echo $row['id']; ?>
</td>
<td>
<?php echo $row['name']; ?>
</td>
<td>
<input type="checkbox" value="<?php echo $row['id'];?>" name="data[]" id="data">
</td>
</tr>
<?php
} unset($row);
}
Related
Hello i have a trouble with my code.
I have HTML with JS:
$(document).ready(function () {
// allowed maximum input fields
var max_input = 5;
// initialize the counter for textbox
var x = 1;
// handle click event on Add More button
$('.add-btn').click(function (e) {
e.preventDefault();
if (x < max_input) { // validate the condition
x++; // increment the counter
$('.wrapper').append(`
<div class="input-box">
<input type="text" name="input_name[]"/>
<input type="text" name="input_price[]">
Remove
</div>
`); // add input field
}
});
// handle click event of the remove link
$('.wrapper').on("click", ".remove-lnk", function (e) {
e.preventDefault();
$(this).parent('div').remove(); // remove input field
x--; // decrement the counter
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="input-box">
<input type="text" name="input_name[]">
<input type="text" name="input_price[]">
<button class="btn add-btn">+</button>
</div>
</div>
and i need insert in DB all inputs (name and price)
Now if i trying insert only first line.
php script:
This is a function and $id_produkt is GET from url.
if (isset($_POST["input_name"]) && is_array($_POST["input_name"])){
$input_name = $_POST["input_name"];
$input_price = $_POST["input_price"];
foreach (array_combine($input_name, $input_price) as $field_name => $field_price){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $field_name, $field_price);
$result = db_query($sql, $data);
return $result;
}
}
Can help me please ? I am tired
I make function like that and working.
function insertVariantsProduct($id_produkt){
$userData = count($_POST["input_name"]);
if ($userData > 0) {
for ($i=0; $i < $userData; $i++) {
if (trim($_POST['input_name'] != '') && trim($_POST['input_price'] != '')) {
$var_id = $_POST["input_id"][$i];
$name = $_POST["input_name"][$i];
$price = $_POST["input_price"][$i];
if(empty($var_id) && !isset($var_id)){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $name, $price);
}else {
$sql = "UPDATE variant_product SET name='$name',price='$price' WHERE id='$var_id' ";
$data = null;
}
$result = db_query($sql, $data);
}
}
return $result; // This should be out of loop because it's will break the loop
}
}
I'm trying to populate HTML table with filter(two dropdowns) from CSV file by using PHP, JS, and jQuery. When user open the page user will see below dropdown,
the options for this drop downs are file names in the dir.
<form name="form1" method="post">
<select class="form-control col-sm-5" onChange="document.forms['form1'].submit();" id="choosefile" name="choosefile">
<option value="" selected>Choose Term</option>
<?php
foreach ($files as &$value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
?>
</select>
</form>
when user submit the form below PHP code gets executed
<?php
if(isset($_POST['choosefile']) && !empty($_POST['choosefile'])) {
$t = $_POST["choosefile"];
$filepath = "uploads/$t";
$row = 0;
$the_big_array = [];
$unique_start_date = [];
$unique_ids = array();
if (($h = fopen("{$filepath}", "r")) !== false) {
while (($data = fgetcsv($h, 1000, ",")) !== false) {
$the_big_array[] = $data;
$unique_ids[] = $data[0];
$a unique_start_date[] = $data[1];
}
fclose($h);
}
//closing bracket for parent if statement is at the end of the file
?>
Below two dropdowns act as a filter
<select name="" id="session_id">
<option value="">[Select Session]</option>
</select>
<select name="" id="start_date">
<option value="">[Select Start Date]</option>
</select>
<table border="1" class="table" id="personDataTable">
<thead>
<tr>
<th scope="col">Session</th>
<th scope="col">Start Date</th>
</tr>
</thead>
<tbody id='tbody'>
</tbody>
</table>
<script>
var obj1 = <?php array_shift($the_big_array); echo json_encode($the_big_array); ?>;
var obj2 = <?php array_shift($unique_start_date); echo json_encode(array_unique($unique_start_date)); ?>;
var obj3 = <?php array_shift($unique_ids); echo json_encode(array_unique($unique_ids)); ?>;
var table = document.getElementById("personDataTable").getElementsByTagName("tbody")[0];
var temp,temp1 = {};
var row = 0;
$("#choosefile, #session_id, #start_date").on('change', function() {
var d1 = $( "#session_id" ).val();
var d2 = $( "#start_date" ).val();
$("#tbody").empty();
for (var i = 0; i < obj1.length; i++) {
if (d1 && obj1[i][0] !== d1 && row > -1) continue;
if (d2 && obj1[i][1] !== d2 && row > -1) continue;
row++;
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][0]));
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][1]));
}
});
</script>
<?php }?>
The problem I'm having is when user submit first dropdown(options with file name) table doesn't get generated or it does not call .on('change', function() under which table generator code is present.
I'm not able to trigger that .on('change', function() for first dropdown but when user click on filter dropdowns that part works well
This answer is an extent to my last comment, as example.
//Put it into a seperate named function:
function fillTable() {
var d1 = $( "#session_id" ).val();
var d2 = $( "#start_date" ).val();
$("#tbody").empty();
for (var i = 0; i < obj1.length; i++) {
if (d1 && obj1[i][0] !== d1 && row > -1) continue;
if (d2 && obj1[i][1] !== d2 && row > -1) continue;
row++;
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][0]));
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][1]));
}
}
// reference to that function here
$("#choosefile, #session_id, #start_date").on('change', fillTable);
// call when the page is loading:
fillTable();
I try to edit name field for the specific input. I need this to get all the variables from this site and add them to my invoice script. I have two divs with client select and service select
HTML:
<div class="service-select">
<?php
$query = "SELECT id,service_name,quantity,net_price,gross_value FROM service";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
?>
<div class='single-service-<?php echo $row["id"]; ?>'>
<input type='checkbox' name=''>
<input type="text" name="service_name" class='name' value="<?php echo $row["service_name"]; ?>" placeholder='NAZWA USŁUGI' disabled/>
<label>Ilość:</label><input type="number" name="quantity" value="<?php echo $row["quantity"]; ?>" placeholder='ILOŚĆ' disabled/>
<label>Cena netto:</label><input type="number" name="net_price" value="<?php echo $row["net_price"]; ?>" placeholder='CENA NETTO' disabled/>
</div>
<?php
}
$result->free();
}
?>
</div>
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for(var i=0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function() {
var div = this.parentNode;
var name_input = div.getElementsByClassName("name");
var name = name_input.name;
var parent_div = div.parentNode;
var x = div.childNodes;
console.log(name_input);
if (parent_div.className == 'service-select') {
if (name_input.name != 'service_chcecked[]') {
name_input.name = 'service_chcecked[]';
}
else {
name_input.name = 'service_name';
}
}
else {
if (name != 'client_chcecked[]') {
name_input.name = ['client_chcecked[]'];
}
else {
name_input.name = ['client_name'];
}
}
for(y=0; y < x.length; y++) {
if(x[y].type === "number" || x[y].type === "text") {
x[y].disabled = !x[y].disabled;
}
}
}, false);
};
My problem is that currently the given name is added to the div :/
Hi Guys I have this search from that takes a search term matches it with a table.field and in php it searches all matching data.
I want to add autocomplete to it, can anyone PLEASE assist?
Here is the HTML FORM
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<input type="text" id="searchThis" name="searchThis" placeholder="search" value="" size="14" />
<select name="searchItems" id="searchItems">
<optgroup value="Vehicles" label="Vehicles">Vehicles
<option value="vehicles.Make">Make</option>
<option value="vehicles.model">Model</option>
<option value="vehicles.RegNumber">Registration Number</option>
<option value="vehicles.licenseExpireDate">License Expire Date</option>
</optgroup>
<optgroup value="Owners" label="Owners">Clients
<option value="owners.OwnerName" label="" >Name</option>
<option value="owners.mobile">Mobile Number</option>
</optgroup>
</select>
<input type="submit" id="doSearch" name="Search" value="Search" />
</form>
<ul id="result">
</ul>
There is the JS
<script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
(function($j){
$j(document).ready(function (){
$j("#searchThis").keyup(function()
{
var searchThis = $j('#searchThis').val();
var searchItems = $j('#searchItems').val();
var dataString = {'searchThis': searchThis,'searchItems':searchItems};
if(searchThis!='')
{
$j.ajax({
type: "POST",
url: "doAutocomplete_search.php",
data: dataString,
dataType: "html",
cache: false,
success: function(data)
{
$j("#result").html(data).show();
}
});
}return false;
});
$j("#result").live("click",function(e){
var clicked = $j(e.target);
var name = clicked.find('.name').html();
var decoded = $j("<div/>").html(name).text();
$j('#searchThis').val(decoded);
});
$j(document).live("click", function(e) {
var clicked = $j(e.target);
if (! clicked.hasClass("search")){
$j("#result").fadeOut();
}
});
$j('#searchid').click(function(){
$j("#result").fadeIn();
});
});
})($j);
And the PHP
function implement($cxn,$searchThis, $field) {
$show = "";
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
$srchData = array();
$rows = mysqli_fetch_row($selectc);
echo $rows;
//if() {, MYSQL_ASSOC
//echo var_dump($srchData);
$show .= '
<table style="border:2px solid #0000">';
//foreach($srchData as $fields=>$data) {
for($s=0; $s < $rows && $srchData = mysqli_fetch_assoc($selectc);$s++) {
if($srchStack[0] == 'vehicles' && $fields == 'RegNumber') {
$dataItem = $data;
$editTbl = 'Vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
} elseif($srchStack[0] == 'vehicles' && $fields == 'Make') {
$dataItem = $data;
$editTbl = 'vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
}
$show .= '<tr><td><a '.$link.'>'.$data.'</a></td></tr>
';
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
//}
}
echo implement($cxn, $_POST['searchThis'], $_POST['searchItems']);
$cxn->close();
Hi Guys so i had to do some refactoring, realized it was more the PHP MySQL code.
Here is the refactored PHP code
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
//$srchData = array();
$rows = mysqli_num_rows(#$selectc) or die(mysqli_error($cxn).'<br>No Rows returned...');
if($rows > 0) {//, MYSQL_ASSOC
//$link = ''; $l_c = 0;
$show .= '<table style="border:2px solid #0000">';
for($c = NULL;$c != $rows && $srchData = mysqli_fetch_assoc($selectc); $c++) {
foreach($srchData as $fields=>$data) {
if($fields == $srchStack[1]) {
$dataItem = $data;
$editTbl = $srchStack[0];
$show .= '<tr><td>'.$dataItem.'</td></tr>';//$a_json_row($dataItem);
//$show .= $link[$c];$link[$c]
}
}
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
Of-course the JS code still needs some more work but this greatly improved the results...
Hope this help someone...
I have a PHP based form. It has a drop down list which fetches values from the mysql database.
<select name=cat onchange="AjaxFunction(this.value);" style="width=600"> <br>
<option value='' Select One</option>
<br>
<?
require "config.php";// connection to database
$q=mysql_query("select cat_id from categories");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
The drop down list works 100%. I then have another text input field,
<input type=text name=copycat>
I want the value of the copycat input box to be equal to the selected value of the drop down list and to update in real time.
Can this be done? I should imagine quite easily. I am thinking something like:
<input type=text name=copycat onBlur="document.getElementById('cat').value=this.value;">
Any help would be appreciated.
Thanks and Regards,
Ryan
UPDATE
Code to get the javscript sendValue working with value of copycat.
catalin87, please assist with getting sendvalue working, currently, clicking the select button has no response fromthe browser.
Thanks again,
Ryan
<?
$con = mysql_connect('localhost', 'username', 'password');
if (!$con)
{
die('Could not connect to server: ' . mysql_error());
}
$db=mysql_select_db("database", $con);
if (!$db)
{
die('Could not connect to DB: ' . mysql_error());
}
$sql="select packcode,category,description,grouping,packconfig,sellingunits,eottpoints from skudata order by category, packcode";
$result=mysql_query($sql);
?>
<script type="text/javascript">
function AjaxFunction(cat_id) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
var myarray = eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for (j = document.testform.subcat.options.length - 1; j >= 0; j--) {
document.testform.subcat.remove(j);
}
for (i = 0; i < myarray.length; i++) {
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd.php";
url = url+"?cat_id="+cat_id;
url = url+"&sid="+Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<script type="text/javascript">
function updateinput(){
var e = document.getElementById("subcat");
var catSelected = e.options[e.selectedIndex].value;
document.getElementById("copycat").value=catSelected;
}
</script>
<script type="text/javascript">
function sendValue(value)
{
value = e.options[e.selectedIndex].value;
var parentId = <?php echo json_encode($_GET['id']); ?>;
window.opener.updateValue(parentId, value);
window.close();
}
</script>
<form name="testform">
Category: <select name=cat id=cat onchange="AjaxFunction(this.value);" style="width=600"> <br>
<option value='' style="width=600">Select One</option>
<br>
<?
require "config.php";// connection to database
$q=mysql_query("select * from categories");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
<br><br>
Pack Code:
<select name=subcat onchange="updateinput();" >
<br><br>
</select>
<br><br>
<input type=text name=copycat id=copycat >
<br><br>
<td><input type=button value="Select" onClick="sendValue(document.getElementById(copycat))" /></td>
</form>
1`st set an id to the select box and to the input, and add an onChange event:
<select name=cat id=cat onchange="updateinput();" style="width=600">
<input type=text name=copycat id=copycat >
Then put this function somewhere:
<script type="text/javascript">
function updateinput(){
var e = document.getElementById("cat");
var catSelected = e.options[e.selectedIndex].text;
document.getElementById("copycat").value=catSelected;
}
</script>
This will populate withe the label of the selected item, if u want the value of the selected item use this function:
<script type="text/javascript">
function updateinput(){
var e = document.getElementById("cat");
var catSelected = e.options[e.selectedIndex].value;
document.getElementById("copycat").value=catSelected;
}
</script>
here is your full code:
<?
$con = mysql_connect('localhost', 'username', 'password');
if (!$con)
{
die('Could not connect to server: ' . mysql_error());
}
$db=mysql_select_db("dbname", $con);
if (!$db)
{
die('Could not connect to DB: ' . mysql_error());
}
$sql="select packcode,category,description,grouping,packconfig,sellingunits,eottpoints from skudata order by category, packcode";
$result=mysql_query($sql);
?>
<script type="text/javascript">
function AjaxFunction(cat_id) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
var myarray = eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for (j = document.testform.subcat.options.length - 1; j >= 0; j--) {
document.testform.subcat.remove(j);
}
for (i = 0; i < myarray.length; i++) {
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd.php";
url = url+"?cat_id="+cat_id;
url = url+"&sid="+Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<script type="text/javascript">
function sendValue(value)
{
var parentId = <?php echo json_encode($_GET['id']); ?>;
window.opener.updateValue(parentId, value);
window.close();
}
</script>
<script type="text/javascript">
function updateinput(){
var e = document.getElementById("cat");
var catSelected = e.options[e.selectedIndex].value;
document.getElementById("copycat").value=catSelected;
}
</script>
<form name="testform">
Category: <select name=cat id=cat onchange="updateinput();" style="width=600"> <br>
<option value='' style="width=600">Select One</option>
<br>
<?
require "config.php";// connection to database
$q=mysql_query("select * from categories");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
<br><br>
Pack Code:
<select name=subcat >
<br><br>
</select>
<br><br>
<input type=text name=copycat id=copycat >
<br><br>
<td><input type=button value="Select" onClick="sendValue('<?php echo $rows['packcode']; ?>')" /></td>
</form>
I changed:
Put : onchange="updateinput();"
<select name=cat id=cat onchange="updateinput();" style="width=600">
and
<input type=text name=copycat id=copycat >
remove:
onBlur="document.getElementById('cat').value=this.value;"
you should add id="cat" to :
<select name="cat" id="cat" onchange="AjaxFunction(this.value);" style="width=600">
and:
echo "<option value='".$n['cat_id']."'>".$n['category']."</option>";
demo : http://jsfiddle.net/V94AJ/