Inserting Duplicate data after confirmation with a dialog box - javascript

When Duplicate is data checked and the confirmation box apears I want to insert data when I press the ok button.
When I press the cancel button data should not be insert in DB.
How can I do this? Here is what I did so far:
<?php
//insert data to database
$category=Null;
$model=Null;
$part=Null;
$remarks=Null;
$partcode=Null;
$partnumber=Null;
$user=$_SESSION['login_user'];
//Recive data from form
if(isset($_POST['category'])){$category = $_POST['category'];}
if(isset($_POST['model'])){$model = $_POST['model'];}
if(isset($_POST['part'])){$part= $_POST['part'];}
if(isset($_POST['remarks'])){$remarks = $_POST['remarks'];}
//Check Duplicate Data From DB
$check="Select * From part Where Category='$category' and Model='$model' and PartName='$part'";
$checkrun=mysqli_query($conn,$check);
$checkrow=mysqli_num_rows($checkrun);
if($checkrow>0){
echo "<script>confirm('Duplicate Data! Click OK to Add & Cancel to Edit')</script>";
}
//Make Part Number
$maxPartQry="Select max(PartCode) FROM part";
$maxPartRun=mysqli_query($conn,$maxPartQry);
$maxpart=mysqli_fetch_array($maxPartRun);
$partcode=$maxpart[0]+1;
$invID = str_pad($partcode,6,'0', STR_PAD_LEFT);
$partnumber=$model."-".$part."-".$invID;
$product;
//Insert Query For inserting data in DB
$sql = "INSERT INTO `part` (`ID`, `PartCode`, `PartNumber`, `Category`, `Model`, `PartName`, `Remarks`, `Date`, `Name`)
VALUES (NULL, '$partcode', '$partnumber', '$category', '$model', '$part','$remarks', NOW(), '$user');";
if(($category != Null) ){
$insert=mysqli_query($conn,$sql);
if($insert){
echo "<script>window.alert('New Part No. ".$partnumber." is Genrated Successfully!!')</script>";
}
}
?>

You need to understand that different pieces of code are executed at different locations. Eg:
SQL queries are executed on the server side
Alert / confirmation boxes are executed on the client side (web browser)
Code for what is executed on the client side is generated on the server side
So multiple requests towards the server are needed if you wish to implement a scenario such as:
User posts data to the server
Server responds that data are duplicates (and returns script code for user confirmation)
Confirmation code is executed, user accepts the insertion of a duplicate
Confirmation is sent towards the server or data are posted again with the addition of a "accept duplicate" flag (typically, if server is stateless).
Server receives the confirmation / second post request, identifies it should accept duplicates, and perform the corresponding SQL query for insertion.
Steps 1, 3, 4 happen on the client side. Steps 2, 5 happen on the server side
In the case the user cancels, then server side code just skips the second post request.
So, you need extra code on the server side to differentiate the two requests (Is this a confirmation request? or Should duplicates be allowed?), and adapt its behavior accordingly. And you need extra code on the client side to generate the second request if user confirms that a duplicate should be inserted.
Of course, all of this would be even cleaner if client-side code was static rather than generated at server-side (google REST HTTP interfaces, for instance) but I fear that explaining this would only confuse you at the present time.

Related

How to submit a form and execute javascript simultaneously

As a follow-up to my last question, I have run into another problem. I am making a project on google homepage replica. The aim is to show search results the same as google and store the search history on a database. To show results, I have used this javascript:-
const q = document.getElementById('form_search');
const google = 'https://www.google.com/search?q=';
const site = '';
function google_search(event) {
event.preventDefault();
const url = google + site + '+' + q.value;
const win = window.open(url, '_self');
win.focus();
}
document.getElementById("s-btn").addEventListener("click", google_search)
To create my form, I have used the following HTML code:-
<form method="POST" name="form_search" action="form.php">
<input type="text" id="form_search" name="form_search" placeholder="Search Google or type URL">
The terms from the search bar are to be sent to a PHP file with the post method. I have 2 buttons. Let's name them button1 and button2. The javascript uses the id of button1 while button2 has no javascript and is simply a submit button.
The problem is that when I search using button1, the search results show up but no data is added to my database. But when I search using button2, no results show up( obviously because there is no js for it) but the search term is added to my database. If I reverse the id in javascript, the outcome is also reversed. I need help with making sure that when I search with button1, it shows results and also saves the data in the database. If you need additional code, I will provide it. Please keep your answers limited to javascript, PHP, or HTML solutions. I have no experience with Ajax and JQuery. Any help is appreciated.
Tony since there is limited code available so go with what you had stated in your question.
It is a design pattern issue not so much as so the event issue.
Copy pasting from Wikipedia "software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. Rather, it is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system."
So here is how things play out at present;
forms gets submitted to specific URL i.e. based on action attribute
Requested page gets Query sting in php and lets you play around with it
then from there on .....
3. either you get results from database and return response
4. or you put search request into database and return success response
Problem statement
if its 3 then search request is not added to database if its 4 then results in response to search request are not returned.
Solution
you need to combine both 3 and 4 in to one processing block and will always run regardless of the search query is.
So our design pattern could use mysql transaction so whole bunch of queries would run a single operation example
$db->beginTransaction(); // we tell tell mysql we will multiple queries as single operation
$db->query('insert query');
$results= $db->query('search query');
$db->commit(); // if we have reached to this end it means all went fine no error etc so we commit which will make database record insert query into database. If there were errors then mysql wont record data.
if($results) {echo $results;} else {echo 'opps no result found';}
slightly more safe version
try {
$db->beginTransaction(); // we tell tell mysql we will multiple queries as single operation
$db->query('insert query');
$results= $db->query('search query');
$db->commit(); // if we have reached to this end it means all went fine no error etc so we commit which will make database record insert query into database. If there were errors then mysql wont record data.
if($results) {echo $results;} else {echo 'opps no result found';}
} catch (\Throwable $e) {
// An exception has been thrown must rollback the transaction
$db->rollback();
echo 'oho server could not process request';
}
We have effectively combined two query operation into one always recording into database and always searching in database.

Inserting data from JS script into mysql database

I have created a script to count down whatever value I submit into a form and then output "the submitted value + the date of the moment I clicked on the submit button" as a result.
But now I want to store the result into my database every time I use the form by using SQL query and then echo all of these results in another page named "log.php" using SELECT SQL query.
var timelog = [];
function myF() {
countdown(s);
log = document.getElementById("log").innerHTML = s + 'at ' + new Date();
timelog.push(log);
}
function logged() {
document.getElementById("timeloggg").innerHTML = timelog;
}
I have tried to assign the result to a variable, but obviously, I cant use this variable outside of the script.
With some googling, I was told to use Ajax, but sadly I couldn't figure out how to insert the data using ajax, because all of the code examples out there are only about calling data from the database.
So any advice on how to insert the result into my database? I'm still a beginner so please explain in detail if you don't mind.
It is possible, of course, to insert data into your database from client side js, BUT DONT! I can't think of a way to do it that would not expose your database credentials, leaving you open to malicious actors.
What you need to do is set up a php script on your server, then send the data (either by POST or GET) you want inserted to that with an xhr request, and let that php script do the insert. HOWEVER, there is quite a bit to securing even that. Google "how to sanitize mysql inputs in php" and read several articles on it.
Depending on what you need to do, you can sanitize the inputs yourself, but the recommended way to do it is with prepared statements, which you will need to read the documentation for your specific implementation, whether it's mysqli or pdo in mySQL or some other library (say if you're using SQL, postGRE, Oracle, etc).
HTH
=================================================
Here is how to do it in js, BUT DONT DO THIS, unless you are never going to expose this code outside of your local computer.
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Provider=host;Data Source=table;User Id=user;Password=pass;";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
var sql = {{your sql statement}};
rs.Open(sql, connection);
connection.close;
==============================================
For php, do something like this, replacing host, user, pass, db with your actual credentials and hostname and database:
$db = new mysqli({host}, {user}, {pass}, {database});
if($db->connect_errno > 0){ die ("Unable to connect to database [{$db->connect_error}]"); }
to set the connection. If this is a publicly accessible php server, then there are rules about how to set up the connection so that you don't accidentally expose your credentials, but I'm going to skip that for now. You would basically save this into a file that's not accessible from the outside (above the document root, for instance) and then include it, but database security is a complex topic.
To get the values you passed in the query string of your ajax call:
$val1 = $_GET['val1'];
$val2 = $_GET['val2'];
Then to do the insert with a parameterized query:
$query = $db->prepare("
INSERT INTO your_table (field1, field2)
VALUES (?, ?)
");
$query->bind_param('ss', $val1, $val2);
$query->execute();
Now, here you're going to have to look at the documentation. 'ss' means that it's going to treat both of those values you're inserting as strings. I don't know the table set up, so you'll have to look up the right code for whatever you are actually inserting, like if they were integers, then 'ii', or 'si' would mean the first value was a string and the second one was an int.
Here are the allowed values:
i - integer
d - double
s - string
b - BLOB
but look at the documentation for prepared statements anyway. I used msqli in this example.
You might want to check Ajax requests.
I would suggest to start here.
What you will do is basically create asynchronous requests from javascript to a php file on your server.
Ajax allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. This means that it
is possible to update parts of a web page, without reloading the whole
page.

How to process many form inputs with PHP

I am building a admin panel for a distribution company and they requested to have a page where they can add orders for all clients , so i generated a form which dynamically adds inputs for each product within the system and and for each client a row is created (see )
|The problem is , every product/client that is added, will add more and more inputs, i already had to increase max_input_vars, but this can easily reach to thousands , if not tens of thousands of inputs which will slow down the application dramatically , my question is, what is the best approach to process all these inputs, or another approach to achieve this functionality ?
I would either reconsider to add an maximum to the amount of input fields which are added per client or create a seperate page for each client on which the input fields are generated.
If you do want to continue you might want to consider extending the max_execution_time which defaults to 30 seconds, by adding ini_set('maximum_execution_time', '60'); to the top of your script.
To process all those rows on the server side. Make your input fields arrays which hold the client name as a key: <input type="text" name="your_value[client1][column1]" /> and for your next client do <input type="text" name="your_value[client2][column1]" /> increment the column for each column.
Then on the server side your can perform a foreach loop to get the values.
foreach($_POST[your_value] as $client)
{
foreach($client as $key => $val)
{
echo $val;
}
}
Use JavaScript (or something client side) to only submit the data that has changed.
If the chart is filled with stored data (in a DB I assume) than when an entry is changed you can use an AJAX request to your php script so it saves the changed data to the DB.

How do I sync an AJAX call to a php file with posting data through a form to the same file?

My problem is update.php only gets the posted form data (post_edit). The variables posted earlier through AJAX don't go through
Notice: Undefined index: id_to_edit in ...\update.php on line 5
Notice: Undefined index: column_to_edit in ...\update.php on line 6
What I'm trying to do:
I have a callback function that traces the mouse's position on the table's body. This is done to detect the column and the id of the cell that the user wants to edit - id integer and column string are posted to a php file through AJAX and used in an SQL query using both values (for coordinates) on top of the data the user wants to update (posted through a form, more on this later).
Editing is done this way: when a user mouses over a cell a form is created inside, and filling in that form should post the data to update the corresponding entry in the SQL table (which is found by using the coordinates from the callback function). Mousing out removes the form.
To paraphrase a bit
How do I post the coordinates and the form data to a php file so that all these values can be used in an SQL query? If what I've been doing is fundamentally broken, is there another way?
$(function(){
$("td")
.hoverIntent(
function(e){
var id_of_edit = $(e.target).siblings('th').text();
var $clicked_column_i = $(e.target).index() + 1;
var column_of_edit = $("#tableheader").children("th:nth-child(" + $clicked_column_i + ")").text();
$.ajax({
type: 'POST',
dataType: 'text',
url: 'update.php',
data: {
'id_of_edit': id_of_edit,
'column_of_edit': column_of_edit
},
});
var $edit_button = $('<form action="update.php" method="post"><input type="text" name="post_edit"/></form>');
$(e.target).append($edit_button);
console.log(e.target.innerText + " was clicked");
console.log(id_of_edit + " is the ID");
console.log(column_of_edit + " is the column name");
//just to check the tracer function is working correctly
},
function(e){
$id_of_edit = $(e.target).siblings('th').text();
$clicked_column_i = $(e.target).index() + 1;
$column_of_edit = $("#tableheader").children("th:nth-child(" + $clicked_column_i + ")").text();
$(e.target).children('form').remove();
});
});
update.php:
<?php
include 'config.php';
echo $_POST['id_to_edit'];
echo $_POST['column_to_edit'];
echo $_POST['post_edit'];
$stmt = $pdo->prepare('UPDATE food SET :column = :edit WHERE id = :id');
$stmt->execute([
'id' => $_POST['id_to_edit'],
'column' => $_POST['column_to_edit'],
'edit' => $_POST['post_edit']
]);
?>
An ajax request and a form submission via standard postback are two separate HTTP requests. Your "update.php" script will execute twice - once for each separate request, and each request will have separate sets of POST variables, according to what you sent on that request. The variables do not persist between requests - just because you sent them to the same endpoint script does not matter.
To summarise: HTTP requests are stateless - they exist in isolation and any given request knows nothing about previous or future requests. Each one causes the named PHP script to run from start to finish, as if it had never run before, and might never run again. It remembers nothing about the past, and knows nothing about the future, unless you do something about it explicitly.
If you want values to persist between requests you have to store them yourself - in a DB, Session, cookies, whatever (it's up to you) - and then retrieve them later when you need them.
Having said that, looking at your server code it's not clear why you would want two separate requests anyway - you are doing a single UPDATE statement in the SQL, so it would make more sense to use one HTTP request to transmit all the data to the server, and then execute the script which runs the UPDATE. Unless there's some reason in the UI why this can't be done, in which case then you need to persist the values somewhere in between requests. From your description, you could potentially capture the cell/column ID into a hidden field inside the form you generate, rather than sending them immediately to the server via ajax. The hidden field values would then be posted to the server together with the user-generated values when the main form is submitted.
Also, if you really are using the mouse's position to determine the cell, this sounds very unreliable - browser windows can be resized to anything. Surely putting an ID inside the HTML markup of the cell (e.g. as a data- attribute) which you can then read when the cell is clicked / moused-over would be much more reliable?

php dynamic page content based on url

So, there are 3 urls:
example.com/first
example.com/middle
example.com/last
In my sql db, there is table with each terms that correspond to related posts:
ID NAME POSTS
1 first 12,3,343
2 middle 23,1,432
3 last 21,43,99
So if an user visits example.com/first, then I want to show posts of "12,3,343" and other posts based on what url they are visiting.
Now, this is the sequence how it would work in my head:
User types "example.com/first"
js (ajax) or something detects the url (in this case, detects "first").
the term is sent to php query.
Gets appropriate info then sends it out (either by ajax or something else).
Am I approaching this right?
How does the server detects what url was requested? I supposed I can skip the first two steps if I know how the server detects the url and I can query the correct info directly instead of relying on js to detect it.
Thanks!
When you mention ajax, I assume you are not navigating away from the page your are on. Am I correct?
If so, you have to create another php file to respond to the requests:
A request is sent to file.php with the url as a query string
In file.php, let it query the DB and json_encode the data.
Retrieve the data and update the fields without navigating away.
PHP is only executed once (Server-side). if you want to execute another query you have to either navigate to other URL or just send your request to a php file via ajax.
You can get the segments of a url request using below statements
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $url);
Now you have all the segments in an array ($segments)
print_r($segments) to get the index of the segment you require.
Now compare that segment with your value
For Eg :
if( $segments[2] == 'first')
{
//Your Piece of code
}

Categories