Quite new to all this stuff so my apologies if this question is obvious.
So my problem is: If the user enter a valid item ID, the script will scan the item ID and return the Shelf ID of that item ID. I want this to be automatic so my user can scan multiple item ID's at the same time. The Shelf ID should be displayed at the red line in the picture below.
Note: I don't want to use the Check Status/Shelf button that I have right now, I want it to be automatic like onEdit or something similar.
Is this possible to accomplish with JavaScript?
This is easily accomplished with jQuery and Ajax. Firstly create a PHP file to do the lookup and return the shelf ID for you.
<?php
$itemId = filter_input(INPUT_POST, 'itemId', FILTER_VALIDATE_INT); // Make sure than an integer has been passed.
$query = "SELECT shelfId from myTable WHERE itemId = $itemId";
//... run query
// store shelfId in $shelfId
echo json_encode(array('itemId' => $itemId, 'shelfId' => $shelfId));
Next we need to set up the jQuery Ajax call. Give all your inputs a class that you can attach an event to. I'll use a class of myClass for now.
$('.myClass').change(function() {
$.ajax({
url: 'path/to/file/above.php',
type: 'POST',
dataType: 'JSON',
data: { itemId: $(this).val() };
}).done(function(response) {
alert("Item: "+response.itemId+", Shelf: "+response.shelfId);
});
});
Related
I built my first ever app using PHP Codeigniter 4 and deployed it to producation yesterday, where users save the data of their items sold. They are saved using AJAX through JQuery where after every save function, page is reloaded. Here is my code on frontend:
$('form[name="transfer_record"]').submit(function (event) {
// This will prevent form being submitted.
event.preventDefault();
// Call your function
var save_date = $("#date").val();
var save_phone_number = $("#phone_number").val();
...
var save_team_lead = $("#team_lead").val();
var save_qa_comments = $("#qa_comments").val();
$.ajax({
url: "<?= base_url(). "/save_transfer_record";?>",
type: "POST",
data: {
save_date:save_date,
save_phone_number:save_phone_number,
...
save_team_lead:save_team_lead,
},
success: function (data) {
alert('Transfer Data Saved Successfully');
location.reload(0)
},
});
});
Here is my code on controller in PHP:
public function save_transfer_record()
{
date_default_timezone_set('America/New_York');
$usa_date = date("Y-m-d H:i:s");
$TransfersIBModel = new TransfersIBModel();
if(isset($_POST)){
$saveTransferForm = [
'date' => $usa_date,
'phone_number' => $this->request->getPost('save_phone_number'),
...
'team_lead' => $this->request->getPost('save_team_lead'),
];
$TransfersIBModel->save($saveTransferForm);
}
}
My PROBLEM IS: Yesterday was first day in production, and there were three instances where there were duplicate entries.
One of them, orange one, have different timestamp which maybe makes me think User entered it twice. But rest two were at same time. So, what could be the issue and how can I mitigate it.
How can I do ensure no duplication without making 'Phone Number' entry unique?
If I make 'Phone Number' unique, how can I make it work?
Please suggest me. I can try disabling button on Ajax click, but I don't think it would work because it feels like my AJAX request ran twice somehow because once it clicks, page should reload before second AJAX request, shouldn't it.Lastly, what is the best practice now, should I hard delete duplicate entries from Table or do not show duplicate values.
I'm having trouble understanding what I'm missing or not doing here (obviously something), and maybe someone can help.
I have a database site that displays a table generated from a SQL database on the client side. When the table is initialized, this code is executed and pulls the data needed for the dropdown in question (comments added by me for this post):
$selectOwner = "SELECT DISTINCT [Contacts].[Alias], [Contacts].[Last Name], [Contacts].[ID] FROM [TechInv].[dbo].[Contacts]";
//this is the file that contains the above query variable
require('custom/Connection.php');
$owner_arr = array();
//$conn is our connection string
$response = sqlsrv_query($conn, $selectOwner);
while ($row = sqlsrv_fetch_array($response)){
array_push($owner_arr, $row['Alias'] . " " . $row['Last Name']);
}
This generates a list of name records pulled from the database in a Alias(first name) Last Name format.
Here's where I'm having trouble
Another function of the site is a menu that allows users of a certain priveledge level to add additional contacts to the table. Everything works fine with that except nowhere in the code is the above array updated when a contact is added, which forces the user to reload the page, ew.
I know i need to use $.ajax for this, so I took a stab at it, and put the following code into the click handler for the 'add contact' submit button:
$.ajax({
type: 'POST',
data: 'listRefresh();',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function() {
alert("this succeeded?");
}
});
The data: 'listRefresh();' line refers to a function I created that is the same as the first block of code, in an attempt to just refresh the variables with new data. That's obviously where I've gone wrong, (try not to laugh) but I am out of ideas here. Can anyone shed some light?
Your ajax call is wrong. The 'data' value is what you send to the server.
Try this:
$.ajax({
type: 'POST',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function(data) {
listRefresh(data);
alert("this succeeded?");
}
});
The data variable is what the server gives you back, so you can pass that data to the listRefresh() function and re-render the upated list.
In alternative, you could just reload the page putting location.reload(); into success function
I'm creating a shipping status report and what I am trying to accomplish, I can't seem to figure out. In my report table I have a button and it shows "Mark as Shipped". If I click on that button it changes to say "Shipped". This is going to serve as just as an easy reporting method for me.
I am doing the text swap like this...
<script>
//Getting Shipping Status button to chance from 'mark as shipped' to 'shipped'
$("button").on("click", function(e) {
e.preventDefault()
var el = $(this);
el.text() == el.data("text-swap")
? el.text(el.data("text-original"))
: el.text(el.data("text-swap"));
});
</script>
I had to add
e.preventDefault()
into the code because the page would reload after I clicked on the button.
One of the issues I am having with this is it isn't allowing me to go back to the original. I tried moving e.preventDefault() to the bottom of that code, but it didn't help.
Now the main part of my question is I want this to be able to save after I have selected it. I'm not sure if I will have to scratch what I'm doing, house this in a db, or if I can do it with my existing code... I definitely need it to save once selected though.
Then one last thing. I'm not sure how to do this with just pressing a button. I know how to do it with php, but I am very new to JS.
When I select "Mark as Shipped" I want a time stamp for d - t -y and time to be added in my td row. Is this possible to do with JS?
I'm looking for ways I can accomplish doing all of this. I have looked all over and can't seem to find anything that is similar to what I want.
Any ideas?
UPDATE
I added it all in to the same script as instructed. Now my button doesn't even change at all and nothing is sending to the db.
<script>
$.ajax({
url: "shippingStatusSend.php",
data: {action: "Shipped", order: order_id},
type: "POST",
dataType: "text"
}).done(function(r){
//Do your code for changing the button here.
//Getting Shipping Status button to chance from 'mark as shipped' to 'shipped'
$("button").on("click", function(e) {
e.preventDefault()
var el = $(this);
el.text() == el.data("text-swap")
? el.text(el.data("text-original"))
: el.text(el.data("text-swap"));
});
});
</script>
PHP page called shippingStatusSend.php
I just started learning how to do prepared statements so this may be an issue too.
<?php
//connection to db
$con = mysqli_connect("localhost", "root", "", "bfb");
//Check for errors
if (mysqli_connect_errno()) {
printf ("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$order_id = trim($_POST['order_id'] );
$status = trim($_POST['action'] );
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "INSERT INTO shippingStatus (order_id, status, date_Shipped) VALUES (?, ?, NOW())")) {
/* bind parameters for markers */
$stmt->bind_param('is', $order_id, $status);
/* execute query */
$stmt->execute();
/* close statement */
mysqli_stmt_close($stmt);
}
?>
In order to make JavaScript changes static, you'll need to use some server side, such as using PHP to store the change in a database.
For that, you'll need to use AJAX, which is easy with jQuery:
$.ajax({
url: "example.php",
data: {action: "Shipped", order: orderID},
type: "POST",
dataType: "text"
}).done(function(r){
//Do your code for changing the button here.
});
Change example.php to your PHP script that will make the change server side, and make sure you pass the orderID of the order you're changing. In the PHP file, you can access $_POST['action'] and $_POST['order'] to get the information from the JavaScript.
Then in the done part (which is called after the AJAX has finished), you can update the button. You can also do some error checking in there to be on the safe side. the r variable can be used for any response data from the PHP file (for example, if you echo "Done" in your PHP, r will equal "Done").
Edit
As per your updated question/code, your problem is that you are creating an AJAX call when the page loads, and not on button click. Change it to:
$("button").on("click", function(e) {
e.preventDefault();
var el = $(this);
$.ajax({
url: "shippingStatusSend.php",
data: {action: "Shipped", order: order_id},
type: "POST",
dataType: "text"
}).fail(function(e,t,m){
console.log(e,t,m);
}).done(function(r){
//Do your code for changing the button here.
//Getting Shipping Status button to chance from 'mark as shipped' to 'shipped'
el.text() == el.data("text-swap")
? el.text(el.data("text-original"))
: el.text(el.data("text-swap"));
});
});
Update
To get order_id you'll need to store it in the DOM somewhere. As per your comments you have it in:
<td class="tdproduct"><?php echo $row['order_id']; ?> </td>
So something like:
var order_id = $('.tdproduct').text();
will get the id, but only if you only have one element with that class. Otherwise you'll have to store in some other unique element to grab.
Saving On Reload
Once you have the value saved in the database, you need to have PHP render it on page load. Rather than having your static html saying Mark as Shipped, use a PHP echo or print to output the information from the database.
I'm having a list with a lot of entries (100+) identified by an (MongoDB-)ID. Each of the entries is in an html-table and has a checkbox. When the user now selects a group, I need to query the server if each of the entries is in the specific group. The query for getting the membership isn't to heavy, but I can't execute it 100+ times, that's too much load.
Currently I have php code for getting the group membership (too long to post) and following javascript code, which is executed whenever the select is changed:
$('checkbox[data-type="group"]').each(function(idx, val) {
// get the ID and set it checked/unchecked
});
My problem is: How can I query performantly the Server once and then check for every ID if the entry is in the selected group?
Your question is a little hard to understand, but I think you should post a JSON list and post that in one query, and handle the iteration server-side, like so:
id_list = {};
$('checkbox[data-type="group"]').each(function(idx, val) {
the_id = //get the id into a variable somehow;
id_list[the_id] = val;
});
$.ajax({
url: "some url",
dataType: "json",
type: "post",
data:id_list
}).done(function(data) {
//using returned data, set each to check/unchecked
//assuming that the returned data had format of id:boolean, and the boolean defines whether it should be checked (e.g. {1: true, 2: false, 3: false} )
$.each(data, function(index,value) {
if (value == true) {
$('checkbox#'+index).attr('checked',true);
} else {
$('checkbox#'+index).attr('checked',false);
}
});
If this doesn't answer your question then please rephrase your question with more detail.
I have a simple list populated via MySql via Ajax / Json. The list is just a title and description and every entry has a checkbox. I need the checkbox, once clicked, to push to database that it is clicked. How would you go about doing that?
[btw...
right now since I have a setTimeInterval on my SQL data to deliver the list on the fly it automatically resets my checkbox. I'm assuming that if I record that my checkbox has been set via boolean in the SQL that there could be a way to keep it checked...]
I'm new at this and I'm just playing around and trying to learn so this information is entirely theoretical.
You can use the on() function to listen to checkbox clicks.
$(function() {
$(document.body).on('click', 'input.mycheckbox', function() {
var checkbox = $(this);
var checked = checkbox.attr('checked');
$.ajax('service.url', {
type: 'post',
data: {action: 'checkbox-select', id: checkbox.attr('id'), checked: checked},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
// Revert
checkbox.attr('checked', !checked);
}
});
}
});
Feel free to ask if you need any clarification or if this doesn't fit your situation.
EDIT:
The data parameter of the AJAX function is an object that will be posted to your PHP page. When your PHP code is running, $_POST will be an array containing the values we passed. So, $_POST['action'] will be 'checkbox-select', $_POST['id'] will get the ID, and $_POST['checked'] will be true or false depending on whether the checkbox was selected or deselected. Your method of getting the ID in the Javascript will probably change; I just put checkbox.attr('id') to give you an idea.
When learning PHP it can be helpful to dump the responses from the server on the client-side. Example PHP code:
if($_POST['action'] == 'checkbox-select']) {
$checkbox = $_POST['id'];
$checked = $_POST['checked'];
// Your MySQL code here
echo 'Updated';
}
echo 'Code ran';
I edited the JS to show the result from the server.