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.
Related
I've been trying to get the data I have in my database(in my PHP file) over to my javascript program. I'm trying to get the query results over to the Javascript file so I can produce a graph out of these results.
I have tried to use ajax but it isn't responding anything back. I'm not sure where I'm going wrong. My PHP file is called MySQLDau.php. Any help is much appreciated! Thanks!
PHP code:
<?php
header("Access-Control-Allow-Origin: *");
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function generateRoomID()
{
$sql = "INSERT INTO room (room_id) VALUES (null);";
$result = $this->mysqli->query($sql);
if ($result == true)
{
$toReturn["status"] = true;
$toReturn["roomID"] = $this->mysqli->insert_id;
return $toReturn;
}
else
{
$toReturn["status"] = false;
$toReturn["message"] = mysql_error($this->mysqli);
return $toReturn;
}
}
public function saveRoom($data)
{
$roomID = $data[0];
$roomDescription = $data[1];
$columns = $data[2];
$rows = $data[3];
$this->mysqli->autocommit(FALSE);
$this->mysqli->query("UPDATE room SET room_description='".$roomDescription."' WHERE room_id='".$roomID."';");
for ($i = 0; $i<count($columns); $i++)
{
for ($j = 1; $j<=$rows[$i]; $j++)
{
$currentLabel = "{$columns[$i]}{$j}";
$this->mysqli->query("INSERT INTO shelf (shelf_label) VALUES ('".$currentLabel."');");
$shelfID = $this->mysqli->insert_id;
$this->mysqli->query("INSERT INTO room_shelf (room_id, shelf_id) VALUES ('".$roomID."','".$shelfID."');");
}
}
if ($this->mysqli->commit())
{
$toReturn["status"] = true;
$toReturn["message"] = "Room Created";
return $toReturn;
}
else
{
$this->mysqli->rollback();
$toReturn["status"] = false;
$toReturn["message"] = "SQL Error";
return $toReturn;
}
}
public function updateShelf($data)
{
$shelfID = $data[0];
$itemName = $data[1];
}
public function getRoomDetails($data)
{
$roomID = $data[0];
$sql = "SELECT room.room_description, shelf.shelf_label, shelf.shelf_id FROM room INNER JOIN room_shelf ON room.room_id=room_shelf.room_id INNER JOIN shelf ON shelf.shelf_id=room_shelf.shelf_id WHERE room.room_id='".$roomID."';";
$result = $this->mysqli->query($sql);
if (mysqli_num_rows($result) > 0)
{
$toReturn["status"] = true;
$toReturn["message"] = "Room Found";
$toReturn["room_description"] = $row['room_description'];
$shelves = [];
foreach ($result as $row)
{
$currentShelf["shelf_label"] = $row['shelf_label'];
$currentShelf["shelf_id"] = $row['shelf_id'];
array_push($shelves, $currentShelf);
}
$toReturn["shelves"] = $shelves;
return $toReturn;
}
else
{
$toReturn["status"] = false;
$toReturn["title"] = "Error";
$toReturn["message"] = "Room Not Found";
return $toReturn;
}
}
echo "Hello World!";
public function getResults($data){
$sql = "SELECT * FROM room";
$result = $this->mysqli->query($sql);
if (mysql_num_rows($result) == 1) {
$obj = mysql_fetch_object($result, 'obResults');
}
echo json_encode($obj);
}
}
?>
Part of my Javascript code:
function callPHP() {
$.ajax ({
type: "GET",
url: "MySQLDao.php",
data: { action : 'getResults' },
success: function(output) {
alert(output);
}
});
}
You don't have any code that is checking the GET parameters, instantiating the class and calling the function. Your AJAX request just creates that class, but does not actually execute anything.
What you can do, is after the closing } of the class definition is this:
$daoObj = new MySQLDao();
$daoObj->getResults(); // this function takes a $data parameter, but doesn't use it
This will execute your getResults function, but is currently ignoring the "data: { action : 'getResults' }" part of your AJAX request. Get the basic functionality working (ie. returning something useful), then improve upon it to execute different functions based on the AJAX request.
This is my ajax call
function exportCSV(){
var sampleid = $("#sampleid").val();
var scheme = $("#scheme").val();
var v = $("#v").val();
var date = $("#date").val();
var assignedvalue = $("#assignedvalue").val();
var units = $("#units").val();
var assayvalue = $("#assayvalue").val();
var analyte = $("#analyte").val();
var filename=$("#filename").val();
var sample_error=$("#sample_error").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "import/validate_file",
dataType: 'json',
data: {
sampleid: sampleid,
scheme: scheme,
v: v,
date: date,
assignedvalue: assignedvalue,
units: units,
assayvalue: assayvalue,
analyte: analyte,
filename:filename,
sample_error: sample_error
},
success: function (data) {
console.log(data); //as a debugging message.
}
});
}
and this is my controller
<?php
if (!empty($unit_check) and !empty($analyt) and !empty($sch) and count($sample_id) == count(array_unique($sample_id)) and $assigned_check == '1' and $assay_check == '1') {
for ($row = 2; $row <= $lastRow; $row++) {
$data['sample_id'] = $worksheet->getCell($sampleid . $row)->getValue();
$data['scheme'] = $worksheet->getCell($scheme . $row)->getValue();
$data['v'] = $worksheet->getCell($v . $row)->getValue();
$data['units'] = $worksheet->getCell($unit . $row)->getValue();
$data['date'] = $worksheet->getCell($date . $row)->getFormattedValue();
$data['assay_value'] = $worksheet->getCell($assayvalue . $row)->getValue();
$data['assigned_value'] = $worksheet->getCell($assignedvalue . $row)->getValue();
$data['analyte'] = $worksheet->getCell($analyte . $row)->getValue();
$data['trace_id'] = $insert_id;
$this->import_model->insert_data($data);
$response['success'] = true;
}
} else {
$data['sample_id'] = '';
$data['analyte'] = '';
$data['unit_check'] = '';
$data['sch'] = '';
$data['assigned_value'] = '';
$data['assay_value'] = '';
if (count($sample_id) != count(array_unique($sample_id))) {
$data['sample_id'] = '1';
}
if (empty($analyt)) {
$data['analyte'] = '1';
}
if (empty($unit_check)) {
$data['unit_check'] = '1';
}
if (empty($sch)) {
$data['sch'] = '1';
}
if ($assigned_check == '') {
$data['assigned_value'] = '1';
}
if ($assay_check == '') {
$data['assay_value'] = '1';
}
$data['file_name'] = '';
}
?>
I have to show the errors and success message on ajax call.
Right now I'm succeeded in valuating the data and putting it in the database.
But I want to show the success message at the end of the page by clicking the submit button.
And if there is validations error it must shows the errors in that fields at the end of the page
Any help would be appreciated.
Here inside your success method of ajax
success: function (data) {
$("#resultDiv").html(data)
}
Return some real data from your controller in both case success and failed. and based on your data inside success method show your message.
Like:
success: function (data) {
$("#resultDiv").html(data.success) //this requires string to convert your result in string if neccessary
//But you should return a JSON data as msg from your controller
}
You should put a result HTML element for example:
<div id='resultDiv'></div> <!-- to match with #resultDiv -->
Put response data in both condition if success=true and else success=false
In your controller
if(.....){
//what ever check you wanna do
..........
..........
$response['msg']='success';
header('Content-Type', 'application/json');
echo json_encode($response);
}
else{
$response['msg']='failed';
header('Content-Type', 'application/json');
echo json_encode($response);
}
In your ajax
success: function (data) {
$("#resultDiv").html(data.msg)
}
Try something like:
$response = array(
'errCode' = 0,
'errMsg' = 'msg'
);
return this kind of array by json_encode() from php to ajax() call and use it in ajax() success like:
var data = JSON.parse(response);
alert(data.errMsg);
You can also put a check on errCode like:
if(errCode == 0) { something }
if(errCode == 1) { something }
I have the following code:
<script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript'>
var last_song = '$song[1]';
var jqy = jQuery.noConflict()
var change_radio = setInterval(function ()
{
jqy.ajax({
url : 'modules/ajax/refresh.php',
type : 'GET',
data : {lastsong: 'last_song'},
success: function(data)
{
last_song = data;
jqy('#radio').html(last_song);
}
});
}, ($refresh*1000));
change_radio;
</script>
refresh.php
<?php
$lastsong = $_GET['lastsong'];
$timeout = "2"; // Number of seconds before connecton times out.
$ip[1] = "198.101.13.110"; // IP address of shoutcast server
$port[1] = "8000"; // Port of shoutcast server
//$song = [];
//$msg = [];
//END CONFIGURATION
$servers = count($ip);
$i = "1";
while ($i <= $servers)
{
$fp = #fsockopen($ip[$i], $port[$i], $errno, $errstr, $timeout);
if (!$fp)
{
$listeners[$i] = "0";
$msg[$i] = "<span class=\"red\">ERROR [Connection refused / Server down]</span>";
$error[$i] = "1";
}
else
{
fputs($fp, "GET /7.html HTTP/1.0\r\nUser-Agent: Mozilla\r\n\r\n");
while (!feof($fp)) $info = fgets($fp);
$info = str_replace('<HTML><meta http-equiv="Pragma" content="no-cache"></head><body>', "", $info);
$info = str_replace('</body></html>', "", $info);
$stats = explode(',', $info);
if (empty($stats[1]))
{
$listeners[$i] = "0";
$msg[$i] = "<span class=\"red\">ERROR [There is no source connected]</span>";
$error[$i] = "1";
}
else
{
if ($stats[1] == "1")
{
$song[$i] = $stats[6];
$listeners[$i] = $stats[4];
$max[$i] = $stats[3];
// Both IFs the same? Please check that and make one only if its the case
if ($stats[0] == $max[$i]) $msg[$i] = "<span class=\"red\">";
if ($stats[0] == $max[$i]) $msg[$i] .= "</span>";
}
else
{
$listeners[$i] = "0";
$msg[$i] = " <span class=\"red\">ERROR [Cannot get info from server]</span>";
$error[$i] = "1";
}
}
}
$i++;
}
if($song[1] != "")
{
echo $song[1];
exit();
}
echo uriencode($lastsong);
?>
And I want to change it to use prototype instead. I use prototype and jQuery already, and this is conflicting as written. I've no idea where to begin, but any assistance would be appreciated... especially since there are a lot of folks in my situation. Thanks so much.
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;
}
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";
}