I m trying to save popup windows data in to database.but its throw error when i m trying pass data in queryString.Its just write "error".I dont know why its not call the update_clientstatus.php
Javscript :
function SaveNotes()
{
var notecontent = $("#txtPopNotes").val();
lookup(notecontent, globalNoteId);
overlay.appendTo(document.body).remove();
return false;
}
function lookup(inputstr, eleid) {
var inputString = inputstr;
// var row = parseFloat(eleId.substring(eleId.indexOf('_') + 1))+1;
var noteId = '#noteContent_' + eleid;
var editLinkId = '#editlink_' + eleid;
var saveLinkId = '#savelink_' + eleid;
var cancelLinkId = '#cancellink_' + eleid;
var txtBoxId = '#txt_' + eleid;
// var eleId = ele.id;
$.post("update_clientstatus.php", {queryString: ""+inputString+"", id: ""+eleid+"" }, function(data){
if(data=="success") {
alert("Status updated successfully");
$('.popup').hide();
var noteId = '#noteContent_' + globalNoteId;
$(noteId).html(inputstr);
$('.message').html('Status Updated successfully');
}
else
{
**document.write('error');**
}
});
} // lookup
PHP code(update_clientstatus.php)
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
}
try this
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
if ($query ) {
echo "success";
} else {
echo "error";
}
} else {
echo "error";
}
Related
I copied this code from stackoverflow it working fine when i upload multiple file through it. but i cannot send other parameter with it . it only upload the file but dont send the other parameter. i tried different way but i am unable to send the data.
My code is below but i dont send the second parameter of NewDir:foldername to my php file
This is my javascript code///////////
function OnProgress(event, position, total, percentComplete){
//Progress bar
console.log(total);
$('#pb').width(percentComplete + '%'); //update progressbar percent complete
$('#pt').html(percentComplete + '%'); //update status text
}
$(document).ready(function(){
$('#files').change(function(){
var files = $('#files')[0].files;
var foldername = $('#Reciter_Name').val();
var error = '';
var form_data = new FormData();
var bar = $('.bar');
var status = $('#status');
var percent = $('.percent');
if(foldername == ''){
alert("Your Don't enter any name");
return false;
}
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['mp3']) == -1)
{
error += "Invalid " + count + " Mp3 File"
}
else
{
form_data.append("files[]", files[count]);
}
}
if(error == '')
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/admin/upload", //base_url()
return http://localhost/tutorial/codeigniter/
method:"POST",
data:{form_data,NewDir:foldername},
contentType:false,
cache:false,
processData:false,
beforeSend:function()
{
// $('#uploaded_files').html("<label class='text-success'>Uploading...</label>");
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
success:function(data)
{
$('#uploaded_files').html(data);
$('#files').val('');
}
})
}
else
{
alert(error);
}
});
});
This is my php code given below///////////
function upload()
{
sleep(3);
if($_FILES["files"]["name"] != '')
{
$output = '';
$config["upload_path"] = './uploads/audio/';
$config["allowed_types"] = 'mp3';
$config["overwrite"] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["files"]["name"]); $count++)
{
$_FILES["file"]["name"] = $_FILES["files"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["files"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["files"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["files"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["files"]["size"][$count];
if($this->upload->do_upload('file'))
{
$data = $this->upload->data();
$output .= '
<input type="hidden" name="url[]" value="'.base_url().'uploads/audio/'.$data["file_name"].'" />
<input type="hidden" name="surahname[]" value="'.$data["file_name"].'" />
'.$data["file_name"].'
';
}
}
}
echo $output;
}
So please tell me how i can pass data from php file.
/////////////////////////////////////////////////////////////////
You just need to add
form_data.append('NewDir',foldername);
Before assign form_data to ajax data variable
I have a function called function getContactsToForm();
This function runs on a div row called results that holds the values from my sql. On click each row is supposed to load this function grab the data from li[0] and pass it on to the rest of the function.
I seem to be getting it to work all right, however the Li's show up empty on my console log even though the table is populated. I assume that means that the sequencing is wrong.
Previously I had a working sample that had everything it table rows. The original function commented out would use the Tr tags and grab the value. The function was called within the getContacts() function and it all worked well, with the LI I am having trouble. Any thoughts?
functions.js
// JavaScript Document
//formoverlay
function formSubmit() {
$.ajax({
type: 'POST',
url: 'contactsinsert.php',
data: $('#frmBox').serialize(),
success: function(response) {
$('#success').html(response);
}
});
var form = document.getElementById('frmBox').reset();
window.location.reload();
return false;
}
$(document).ready(function() {
$('#srchbtn').click(function start() {
getContacts();
});
});
function getContacts() {
var txtsearch = $('#txtsearch').val();
$.ajax({
url: 'contactstable.php',
type: "POST",
//dataType: "json",
data: ({
txtsearch: txtsearch
}),
success: function(response) {
$('#displayContacts').html(response);
//addRowHandlers();
//getContactsToForm();
}
});
}
window.onload = getContacts();
/*function addRowHandlers() {
console.log("hi");
var table = document.getElementById("resultstable");
var rows = table.getElementsByTagName("li");
console.log(rows[0]);
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
console.log(currentRow);
var createClickHandler = function(row) {
return function() {
*/
function getContactsToForm() {
var table = document.getElementById("resultstable");
var rows = table.getElementsByTagName("ul")['results'];
console.log(rows);
var lis = table.getElementsByTagName('li')[0];
console.log(lis);
var id = lis.innerHTML;
console.log(id);
//alert("id:" +id);
document.getElementById("id").value = id;
$.ajax({
url: "inputtest.php",
success: function(result) {
var frm = document.getElementById("frmBox2");
var ID = document.getElementById("id").value;
if (/\S/.test(ID)) {
ajax_request(this.action, {
"action": "fetch",
"ID": ID
}, process_response);
} else {
alert("No ID supplied");
}
function ajax_request(url, data, callback) {
var i, parts, xhr;
// if data is an object, unroll as HTTP post data (a=1&b=2&c=3 etc.)
if (typeof data == "object") {
parts = [];
for (i in data) {
parts.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
data = parts.join("&");
}
// create an XML HTTP Request object
xhr = new XMLHttpRequest();
if (xhr) {
// set a handler for changes in ready state
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// check for HTTP status of OK
if (xhr.status == 200) {
try {
callback(JSON.parse(xhr.responseText));
} catch (e) {
console.log(xhr.responseText); // for debug
alert("AJAX request incomplete:\n" + e.toString());
}
} else {
alert("AJAX request failed: " + xhr.status);
}
}
};
// open connection and send payload
xhr.open("GET", "inputtest.php" + "?" + data, true);
xhr.send(null);
}
}
/**
* process the response, populating the form fields from the JSON data
* #param {Object} response the JSON data parsed into an object
*/
function process_response(response) {
var frm = document.getElementById("frmBox2");
var i;
console.dir(response); // for debug
for (i in response) {
if (i in frm.elements) {
frm.elements[i].value = response[i];
}
}
}
}
});
};
// currentRow.onclick = createClickHandler(currentRow);
// }
// }
//window.onload = addRowHandlers();
function openNav() {
document.getElementById("myNav").style.width = "100%";
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
window.location.reload();
}
function openCon() {
document.getElementById("conNav").style.width = "100%";
}
function closeCon() {
document.getElementById("conNav").style.width = "0%";
var form = document.getElementById('frmBox').reset();
}
function enablebuttons() {
document.getElementById("insert").disabled = false;
}
contactstable.php (calls the mysql and receives contacts)
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<?php
include_once "iud.php";
$arrayval = array();
$search=$_POST['txtsearch'];
$search1 = explode(" ", $search);
array_push($arrayval, $search1);
foreach ($arrayval as $val){
$orIndex = checkOr($val);
if(empty($orIndex)){
$resultstable = getResults($val);
$resultstable1 = buildTable($resultstable);
print($resultstable1);
}else{
print"there is an or here";
$resultstable = getResults($orIndex);
$resultstable1 = buildTable($resultstable);
print($resultstable1);
}
}
buildTable($resultstable);
/*if (empty($orIndex)){
print "no or";
$resultstable = getResults($val);
$resultstable1 = buildTable($resultstable);
print $resultstable1;
function getResults($array){
include_once "iud.php";
$db = connectDatabase();
$totalResults = array();
$length = count($array);
for ($i = 0; $i < $length; $i++){
$outputDisplay = "";
$myrowcount = 0;
$sql_statement = "SELECT id, firstname, lastname, pcat, position, state ";
//, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes ";
$sql_statement .= "FROM contacts ";
$sql_statement .= "WHERE (firstname LIKE '%$array[$i]%' or lastname LIKE '%$array[$i]%')";
$sql_statement .= "ORDER BY lastname, firstname";
$sqlResults = selectResults($db, $sql_statement);
$error_or_rows = $sqlResults[0];
if (substr($error_or_rows, 0 , 5) == 'ERROR')
{
$outputDisplay .= "<br />Error on DB";
$outputDisplay .= $error_or_rows;
} else {
$totalResults = array_merge($totalResults, $sqlResults);
//$totalResults = array_map("unserialize", array_unique(array_map("serialize", $totalResults)));
$arraySize = $error_or_rows;
}
}
//return $totalResults;
//print $arraySize;
//print_r($error_or_rows);
return $totalResults;
}
function buildTable($totalResults){
include_once "iud.php";
$outputDisplay = "";
//$outputDisplay .= '<table id="resultstable" style="overflow-x:auto;">';
//$outputDisplay .= '<tr><th align="left">ID</th><th align="left" width="30%">First Name</th><th align="left" width="30%">Last Name</th><th align="left" width="30%">Pages Category</th><th align="left" width="30%">Position</th><th align="left" width="30%">state</th></tr>';
$outputDisplay .= '<div id="resultstable">';
$outputDisplay .= '<div id="headers">';
$outputDisplay .= '<ul id="headers">';
$myrowcount = 0;
for ($i=0; $i < count($totalResults); $i++)
{
$myrowcount++;
$contactid = $totalResults[$i]['id'];
$firstname = $totalResults[$i]['firstname'];
$lastname = $totalResults[$i]['lastname'];
$pcat = $totalResults[$i]['pcat'];
$position = $totalResults[$i]['position'];
$state = $totalResults[$i]['state'];
$outputDisplay .= '<ul id="results">';
$outputDisplay .='<li>'.$contactid.'</li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon();getContactsToForm();">'.$firstname.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$lastname.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$pcat.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$position.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$state.'</span></li>';
$outputDisplay .= '</ul>';
//echo $myrowcount;
}
$outputDisplay .= "</div>";
return $outputDisplay;
}
function checkOr($searchArray){
if (in_array("OR",$searchArray)){
$orPos = array_search("OR", $searchArray);
//$surrVal =array();
//$surrVal = array(--$orPos, ++$orPos);
if (!empty($orPos)){
$surrVal = "";
$surrVal = --$orPos;
$orValArray = array();
array_push($orValArray,$searchArray[$surrVal]);
$surrVal = $orPos+2;
array_push($orValArray,$searchArray[$surrVal]);
return $orValArray;
}
}
}
The results I get are:
209AnisBakerDC
but from the console side:
I have a page with ajax pagination on it, I am currently able to check if the session exists and process accordingly. However, I cannot seem to remove the menu or reload the page properly if the session has expired. Only the menu remains and the login page shows in the small area where the table was.
Controller code
public function index()
{
$conditions = array();
$data = array();
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search(array('limit'=>$this->get_per_page()));
$data['user'] = $this->AccountModel->get_person($this->get_person_id());
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('layout/admins/common/header');
$this->load->view('layout/admins/common/navigation');
$this->load->view('layout/admins/common/title');
$this->load->view('layout/admins/common/errors');
$this->load->view('layout/admins/common/search');
$this->load->view('admins/documents/index',$data);
$this->load->view('layout/admins/common/footer');
}
public function search(){
if($this->input->is_ajax_request()){
if(!$this->logged_in()){
$this->index();
}else{
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('admins/documents/ajax_pagination', $data, false);
}
}
}
My JS Code that is placed in the view
<script>
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (html) {
$('#list').html(html);
$('.loading').fadeOut("slow");
}
});
}
function changeStatus(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/ChangeStatus/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
console.log(result);
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
function deleteDocument(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/Delete/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
</script>
i am assuming $('#list').html(html); code loads the html in the dom. instead of directly sending the html from php you can send a json containing the html as well the login status. like this.
$data = [
'login_status' => 1 // or 0,
'html' => $html // full html your are sending now
];
echo json_encode($data);
then in ajax success.
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (response) {
var data = $.parseJSON(response);
if(data.login_status == 0)
{
window.location.href = 'redirect to login page';
}
if(data.login_status == 1)
{
$('#list').html(data.html);
}
$('.loading').fadeOut("slow");
}
});
}
controller method :
public function search(){
if($this->input->is_ajax_request()){
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$html = $this->load->view('admins/documents/ajax_pagination', $data, true);
$res['html'] = $html;
$res['login_status'] = ($this->logged_in()) ? '1' : '0';
echo json_encode($res);
}
I am attempting to write code that will edit a Single entry in a SQL database, the $num is the invoice ID number, I must be passing it incorrectly, because my console was showing an Undefined value for the idinvoice,
Now the console isn't showing any errors :/
Google and stack haven't yield much yet,
Here is my Javascript
$scope.saveEdit = function($param){
$scope.list2 = { };
if($scope.who == 'Dealer'){ $scope.list2.billTo = 'Dealer'; $scope.billTo = ''; }
else { $scope.list2.billTo = 'Customer'; $scope.billTo = ''; }
if($scope.billStart) { $scope.list2.billStart = $scope.billStart; $scope.billStart = ''; }
if($scope.customerName) { $scope.list2.customerName = $scope.customerName; $scope.customerName = ''; }
if($scope.dealerName) { $scope.list2.dealerName = $scope.dealerName; $scope.dealerName = ''; }
if($scope.item) { $scope.list2.item = $scope.item; $scope.item = ''; }
if($scope.price) { $scope.list2.price = $scope.price; $scope.price = ''; }
if($scope.qty) { $scope.list2.qty = $scope.qty; $scope.qty = ''; }
if($scope.cost) { $scope.list2.cost = $scope.cost; $scope.cost = ''; }
if($scope.contractTerms) { $scope.list2.contractTerms = $scope.contractTerms; $scope.contractTerms = ''; }
$scope.list2.per = $scope.per; $scope.per = '0';
$http.post('DealerRec/writeInvoice.php?$num='+$param+'&action=writeEdit', $scope.list2)
.success(function(data){ console.log("Data Written"); console.log(data); })
.error(function() { console.log("Data Not Written"); });
}
Here is my php file for connecting to SQL
switch($_GET['action']){
case 'writeInvoice':
writeInvoice();
break;
case 'fetchInvoice':
echo fetchInvoice($_GET['num']);
break;
case 'saveEdit':
writeEdit($_GET['num']);
break;
}
function writeEdit($num){
$data = json_decode(file_get_contents("php://input"));
$customerName = $data->customerName;
$dealerName = $data->dealerName;
$billTo = $data->billTo;
$billStart = substr($data->billStart,0,10);
$contractTerms = $data->contractTerms;
$item = $data->item;
$price = $data->price;
$qty = $data->qty;
$per = $data->per;
$cost = $data->cost;
$qry = "UPDATE invoice
SET
customerName = '{$customerName}',
dealerName = '{$dealerName}',
billTo = '{$billTo}',
billStart = '{$billStart}',
contractTerms = '{$contractTerms}',
item = '{$item}',
itemPrice = '{$price}',
quantity = '{$qty}',
cost = '{$cost}',
sharePercent = '{$per}'
WHERE idInvoice ='{$num}'";
echo ($qry);
$qry_res = new Query($qry);
if ($qry_res) { $arr = array('msg' => "Invoice edited successfully!!!", 'error' => ''); }
else { $arr = array('msg' => "", 'error' => 'Error in inserting record'); }
}
The solution was as follows
change to this
$http.post('DealerRec/writeInvoice.php?action=saveEdit', $scope.list2)
.success(function(data){ console.log("Data Written"); console.log(data); })
.error(function() { console.log("Data Not Written"); });
}
and this
case 'saveEdit':
saveEdit();
break;
and finally this
$price = $data->price;
$qty = $data->qty;
$per = $data->per;
$cost = $data->cost;
$num = $data->idInvoice; <----------------------
These functions now work. Thank you all for your help.
what i am trying to do is getting data from database and tick the checkbox according to that but i did not success any idea?
i am not sure what is the problem
JS code
function editPer(role_pk) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4) {
var jsonObj = JSON.parse(xmlHttp.responseText);
document.getElementById("role_pk1").value = jsonObj.pk;
document.getElementById("role_name1").value = jsonObj.name;
for (var i = 1; i < 29; i++){
if (jsonObj.permission_fk+i != null)
document.getElementById("per"+i).checked = true;
else
document.getElementById("per"+i).checked = false;
}
}
};
xmlHttp.open("GET", "classes/controller/RoleController.php?action=getp&pk=" + role_pk, true);
xmlHttp.send();
/*
* Reset error message
* Show update role button
*/
resetErrorMessage("roleMessage");
showUpdateRoleButton();
$("#perModalDetail").modal('show');
};
PHP code RoleController.php
}else if ($action == "getp") {
if (isset($pk)) {
/*
* Select single Role value
*/
$itemArray = $roleDao->getp($pk);
if (count($itemArray) == 0) {
echo NULL;
} else {
echo json_encode($itemArray[0]);
}
}
PHP code in the class roleDao
public function getp($pk) {
$query = "SELECT pk, name FROM roles WHERE pk=".$pk.";";
$result = mysql_query($query, $this->dbconn);
$itemArray = array();
while ($row = mysql_fetch_row($result)) {
$item = array("pk" => $row[0], "name" => $row[1]);
array_push($itemArray, $item);
}
$query = "SELECT permission_fk FROM role_permission WHERE role_fk=".$pk.";";
$result = mysql_query($query, $this->dbconn);
$i=1;
while ($row = mysql_fetch_row($result)) {
$item = array("permission_fk$i" => $row[0]);
$i++;
array_push($itemArray, $item);
}
//print $itemArray;
return $itemArray;
}