AJAX update to multiple database tables - javascript

I have an ajax table that reads data from two mysql tables, the tables are
project_ownerships - id_own, project, code, own_current, own_future
projects - id, project, location, type, type2, area, transport, stage
the data reads into the web page table fine, using a join table sql query.
$query_value = isset($_GET['value']) ? $_GET['value'] : "";
$sql = "SELECT project_ownerships.*, projects.*
FROM project_ownerships, projects
WHERE project_ownerships.project = projects.project
AND project_ownerships.code = $query_value'";
$result = $mysqli->query($sql);
however I can't get the edit update working properly. I am only able to get a data - id value from one db-table.
so any updates that belong to projects table update fine, but any updates to project_ownerships do not have the correct id value and update the wrong db-record
here's the update function. this function returns the error "column not found with index or name id_own"
$.ajax({
url: 'update_multi.php',
type: 'POST',
dataType: "html",
data: {
tablename: editableGrid.getColumnName(columnIndex) == "own_current" ? "project_ownerships" : "projects",
id: editableGrid.getColumnName(columnIndex) == "own_current" ? editableGrid.getValueAt(rowIndex, editableGrid.getColumn("id_own")) : editableGrid.getRowId(rowIndex),
newvalue: editableGrid.getColumnType(columnIndex) == "boolean" ? (newValue ? 1 : 0) : newValue,
colname: editableGrid.getColumnName(columnIndex),
coltype: editableGrid.getColumnType(columnIndex)
},
success: function (...,
error: function(...,
async: true
});
here's the php update
$tablename = $mysqli->real_escape_string(strip_tags($_POST['tablename']));
$id = $mysqli->real_escape_string(strip_tags($_POST['id']));
$value = $mysqli->real_escape_string($_POST['newvalue']);
$colname = $mysqli->real_escape_string(strip_tags($_POST['colname']));
$coltype = $mysqli->real_escape_string(strip_tags($_POST['coltype']));
$id_column = "";
if ($tablename == "projects") {$id_column = "id";} else {$id_column = "id_own";}
if ( $stmt = $mysqli->prepare("UPDATE ".$tablename." SET ".$colname." = ? WHERE ".$id_column." = ?")) {
$stmt->bind_param("si",$value, $id);
$return = $stmt->execute();
$stmt->close();
}
basically what I am trying to do....
if projects.id is removed from the sql the update will not work
if project_ownership.id_own is changed to project_ownership.id and projects.id is removed the update will work, but only with project_ownership.* fields
so... I need a column in the sql query called *.id
separately, when an update is sent, the correct table name can be selected by
tablename: editableGrid.getColumnName(columnIndex) == "own_current" ? "project_ownerships" : "projects",
so using the same logic
id: editableGrid.getColumnName(columnIndex) == "own_current" ? editableGrid.getValueAt(rowIndex, editableGrid.getColumn("id_own")) : editableGrid.getRowId(rowIndex),
firstly, recognises that own_current is there, and passes the argument to editableGrid.getValueAt(rowIndex, editableGrid.getColumn("id_own")) but the error returned is "no column found with the id_own name"... ?
I am really confused..
it cannot not be there (removed from the sql) otherwise the update just freezes
but when it is there it cannot be found...
any help would be great
how is it possible to define the ajax - data - id column or the rowIndex column ?
I am working on the theory that
editableGrid.getRowId(rowIndex)
could be the something like (which it's obviously not otherwise this would work)
editableGrid.getValueAt(rowIndex, editableGrid.getColumn("id_own"))
but I have also tried, amongst others
editableGrid.getValueAt(rowIndex, editableGrid.getColumnIndex("id_own"))
which returns "invalid column index -1"
and
editableGrid.getValueAt(rowIndex, editableGrid.getColumnName("id_own"))
UPDATE
there's a couple private functions in editablegrid that define what row id is. so I guess that makes it an editablegrid question and not really a javascript, ajax, or php question suitable for here

You should rename "id" column of each table in your SQL query with AS operator so they dont conflict.
For example :
SELECT B.*,A.name,A.id as author_id FROM BOOKS B
INNER JOIN AUTHORS A ON A.id=B.authorid

Related

oracle Apex Interactive grid

I have a interactive grid. If no rows selected I want to display a error msg as 'No records selected'. If more than 1 record selected then display 'select 1 record'. If 1 row selected then call a procedure. How can I achieve this using Java Script?
The error message should appear as inline notification.
I have tried this code. But this doesn't give correct error message. If I try clicking one record it is giving correct error msg then if I click one more record the error msg is incorrect. I mean whatever error I'm getting for first time I'm getting the same error always.
var gridView = apex.region("your-IG-static-id").widget().interactiveGrid("getViews").grid;
var records = gridView.getSelectedRecords();
var recs = records.length;
if (recs = 0) {apex.message.alert("No records selected")};
if (recs > 1) {apex.message.alert("Select 1 record")};
if (recs = 1) {
apex.server.process("CALL_YOUR_AJAX_PROCESS", {
x01: $v("PAGE_ITEM_1") ,// Parameters to pass to AJAX process if any
x02: $v("PAGE_ITEM_2") ,// Parameters to pass to AJAX process if any
}, {
//pageItems: ''
//dataType: 'text'
}).done(function (pData) {
console.log(pData);
});
};

After successful getting the result from filter how to show in blade file in Laravel 8

I am working on the filter part in search page but the issue is In the main search page all the result looped from the controller, and Now I am using jquery for the filter process, but things are confusing. How to do this in a right way?
So here is the process :
Step 1 : user search something Like "support" and then system go to the searchController file and give the result
return view('/search')->with(["documents" => $results, "filters" => $filters]);
Here $filter indicates the category filters; Like this
Then When User click on any category then it will filter the result but now the issue is I am using jquery and now things getting weird. Can somebody help me on this.
JS Code :
$(document).on("click", ".category_filter1",function() {
var test = new Array();
$("input[name='category_filter']:checked").each(function() {
test.push($(this).val());
});
showValue(test);
});
function showValue(data){
$.ajax({
'url': 'search/filter/'+(data.length > 0 ? data : "all"),
'type': 'GET',
success: function(response){ // What to do if we succeed
if(response.data == "success")
document.getElementById('result').innerHTML = response.categories;
},
error: function(response){
// alert('Error');
}
});
}
and The Controller from where all result came from :
public function filter($data){
$t_data = explode(',' , $data);
$filters = $this->load_filters();
if(count($t_data)>0 && $t_data[0]!== "all"){
$results = DB::table('documents')
->whereIn('category', $t_data)
->paginate(5);
}else{
$results = Document::paginate(5);
}
return redirect('/search')->with(["documents" => $results, "filters" => $filters]); // This part is really confusing
}
So the flow will be like this :
Summarizing from as discussed in comments,
In order to call the controller without refreshing the page you need to use ajax, (use jquery or any other frontend framework). Return your response as json,
return response()->json($your_return_array);
For images store it in public folder, such as public/images/your-image.png.
Then call it using url() method in your blade.
<img src="{{url('/images/your-image.png')}}" alt="Image"/>

How to bring a json result into PHP

I have some results from a fetch.php using json and I successfully brought all results to my bootstrap modal HTML screen.
When the Modal is being shown, I would like to run a MYSQL query using a value coming from the same json I used for the modal, however I can't put this value into a PHP variable to run the SQL query.
How can I get this?
I am trying to bring the same value I input into the HTML textbox (modal), but it is not working. I also tried to use the value from json '$('#PCR').val(data.PCRNo);)', but nothing happen.
This is the script to collect information from database using fetch.php file:
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
</script>
This is the PHP code
<?php
//trying to get the value I have included on #PCR (textbox) which has ID='PCR' and name ='PCR' **
$PCR= $_POST['PCR'];
//running now the code to check if the database has the value and return the desired response to be shown **
$sql1 = mysqli_query($dbConnected,"SELECT * FROM change_management.tPCN");
while ($row1 = mysqli_fetch_array($sql1)) {
if ($row1['PCRNo']==$PCR){
echo $row1['PCNNo'];
echo "<br/>";
}else{
}
}
?>
I would like include value from this val(data.PCRNo) json return into the $PCR variable, so the MYSQL query is going to work
There are a number of quite basic logical issues with your code which are preventing it from working.
1) data: { pcr_number: pcr_number}- the name pcr_number doesn't match the value PCR which the server is searching for using $_POST['PCR'];. The names must match up. When making an AJAX request, the name you gave to the form field in the HTML does not matter (unless you use .serialize()) because you are specifying new names in the data parameter.
2) Your SQL query doesn't make sense. You seem to be wanting to read a single row relating to a PCR number, yet your query makes no usage of the input PCR value to try and restrict the results to that row. You need to use a SQL WHERE clause to get it to select only the row with that ID, otherwise you'll fetch all the rows and won't know which one is correct. (Fetching them all and then using an if in a PHP loop to check the correct one is very inefficient.) I wrote you a version which uses the WHERE clause properly, and passes the PCR value to the query securely using prepared statements and parameters (to project against SQL injection attacks).
3) Your output from the PHP also makes no sense. You've told jQuery (via dataType: "json" to expect a JSON response, and then your code inside the "success" function is based on the assumption you'll receive a single object containing all the fields from the table. But echo $row1['PCNNo']; echo "<br/>"; only outputs one field, and it outputs it with HTML next to it. This is not JSON, it's not even close to being JSON. You need to output the whole row, and then use json_encode() function to turn the object into a JSON string which jQuery can parse when it receives it.
Here's a version of the code containing all the above changes:
JavaScript:
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
$.ajax({
url: 'fetch.php',
method: 'post',
data: { pcr: $(this).attr('id'); },
dataType: "json",
success: function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
PHP:
<?php
$PCR = $_POST['pcr'];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt->bind_param('s', $PCR);
$stmt->execute();
$result = $stmt->get_result();
//an "if" here will cause a single row to be read
if ($row = $result->fetch_assoc()) {
$output = $row;
}
else
{
$output = new StdClass();
}
$stmt->free_result();
$stmt->close();
//output the result
echo json_encode($output);
?>
N.B. I would potentially suggest studying some tutorials on this kind of subject, since this is a fairly standard use case for AJAX/JSON, and you should be able to find samples which would improve your understanding of all the different parts.
P.S. Currently the PHP code above will return an empty object if there is no matching row in the database. However, this is probably an error condition (and will cause your JavaScript code to crash due to trying to read nonexistent properties), so you should consider how you want to handle such an error and what response to return (e.g. 400, or 404, and a suitable message).
You need to first return json from php by using json_encode.
Inside this loop
while ($row1 = mysqli_fetch_array($sql1)) {
$data = array('PCRNo' => 'itsvalue', 'PCC' => 'itsvalue', 'Creation_Date' => 'itsvalue')
}
print json_encode($data)
store all the data in an associative array and then convert it into json using json_encode and return the json.
Use json data in you ajax file
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
var data = JSON.parse(data);
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
Below is the changed script to store different values in $PCR variable
<script>
$(document).ready(function(){
var i = 1;
$('#table').on('click', '.fetch_data', function(){
if(i == 1) {
var pcr_number = $(this).attr('id');
} else {
var pcr_number = $('#PCR').val();
}
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
i++;
}
});
});
});
</script>

Load more return duplicate

I trying to make load more content from database via php and ajax and read some tutorial but what I tried return duplicate entry. (here is just an example of my real code:)
Query:
$sql = "SELECT name FROM table WHERE cat = 2 LIMIT 10";
This load first 10 items.
Query for load more:
$limit = $_GET['limit'];
$current = $_GET['current'];
$sql = "SELECT name FROM table WHERE cat = 2 LIMIT $current OFFSET $limit";
Ajax:
$('.getMore').click(function() {
var adslen = $('.Ads').length; // this return current items
var limit = $(this).attr('data-limit'); // this return current item and items after load more
$.ajax({
type: "GET",
data: {
limit: limit,
current: adslen
},
dataType: 'html',
url: '/api/fetch.php?getBrowse',
success: function(data) {
// do something
}
});
});
For example now we have 10 items, after click on loadMore it load another 10 items, but the problem is it load duplicate itemes too, what I have done wrong?
HTML:
<a class="getMore" id="browse-getMore" data-limit="10">More</a>
After press load more it update data-limit:
<a class="getMore" id="browse-getMore" data-limit="20">More</a>
The problem is that you do not specify order. In your case SELECT statement returns rows with no specific order. When you run it once, it may return one list of records, when you run it twice (the same select query) it may return another set of records. So, do it like so:
$sql = "SELECT name FROM table WHERE cat = 2 ORDER BY id LIMIT $current OFFSET $limit";
And read theory. It says that relation (or table) is an unordered set of records, unless you specify order explicitly. And by the way, if you specify order, it is no longer a relation, if I'm not mistaken.

Saving changes to a dropdown box into a database in CakePHP

I am new to cake and mysql, and am trying to create a simple job tracking app. I want to have a dropdown box for each job with a list of the status' a job can be at. When a user changes the active item in the box I want to save this into the database.
Any help in how to handle this would be very much appreciated. Below is what I have tried so far:
How I create the set of forms in the view with the options taken from the enums in my database table:
<?php $id = count($jobs)-1; ?>
<?php for ($job = count($jobs)-1; $job >= 0; --$job): ?>
<tr>
<td>
<?php echo $this->Form->input('status'.(string)$id, array('type'=>'select', 'class' => 'statusSelect','label'=>'', 'options'=>$states, 'default'=>$jobs[$job]['Job']['Status'])); ?>
</td>
I am using a jquery script to set an on change listener for each dropdown and call an action in my controller:
$(".statusSelect").change(function(){
//Grab job number from the id of select box
var jobNo = parseInt($(this).attr('id').substring(6));
var value = $(this).val();
$.ajax({
type:"POST",
url:'http://localhost/projectManager/jobs',
data:{ 'id': jobNo,
'status':value},
success : function(data) {
alert(jobNo);// this alert works
},
error : function() {
//alert("false");
}
});
});
And I have this function in my controller:
public function changeState($id = null, $status = null) {
//I don't think the id and status are actually
//being placed as arguments to this function
//from my js script
}
Thank you!!!
You are POSTing to /projectManager/jobs, which corresponds to ProjectManagerController::jobs().
Your function is declared as public function changeState($id = null, $status = null). Assuming changeState(..) is a function within ProjectManagerController, this corresponds to /projectManager/changeState/$id/$status.
You need to switch the URL the AJAX is POSTing to. You can either do something like:
url:'http://localhost/projectManager/changeState/'+jobNo+'/'+value', remove the data {} and leave your function as is, or you can do
url:'http://localhost/projectManager/changeState', leave the data {}, change your function to changeState() and then use $this->request->data within changeState() to access the data.
I am guessing you have another function, jobs(), and that is why the AJAX is working properly and the alert is generating.

Categories