Boostrap modal form with 2 submit buttons and save in database - javascript

I am trying to make a form on a modal. I have a form with 2 buttons: accept and reject.
If the user clicks on accept there is an update in that database, if the user clicks on reject there is another update.
I need to retain a certain value from database before, so I am making a select.
The problem is that I don't know how to make an insert in database using javascript (I know it is possible with jquery/ajax but how to call
it in the button?).
Here is my code:
Here is the Javascript function to insert in database that doesn't work
<script type="text/javascript">
function clicked1() {
//update candidate_jobs SET is_hired='1' WHERE candidate_id=$userId and applied_to=$row["job_id"];
var connection = new ActiveXObject("ADODB.Connection"),
recordSet = new ActiveXObject("ADODB.Recordset"),
connectionString = '';
connection.Open(connectionString);
recordSet.Open(
"update candidate_jobs SET is_hired='1' WHERE candidate_id=".$userId." and applied_to=".$row["job_id"]."";,
connection);
recordSet.close;
connection.close;
alert('You accepted the offer');
}
function clicked2() {
//idem clicked1 but change the is_hired value to be inserted in the database
alert('You rejected the offer');
}
</script>
Can it be done using Jquery and Ajax? How?
What it wrong with the code?
Thank you very much!

The concatenated sql string is prone to sql injection attacks (although obviously anyone viewing the page source can do whatever they like to the database anyway) - parameterization is the solution here and we need to use an IDENTITY or GUID.
Here is a list of possible issues:
1) The code will only ever run in IE browsers
2) You may need to download and install the COM components - ADO
3) You may need to run IE as an Administrator
4) You may need to open all sorts of security loopholes in IE (ActiveX controls, safe for scripting etc)
If you enable script debugging on the browser you'll get more info on the actual issue.
hope it helps you.

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 store the state of an input on a website? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I created a webUI to control a relay board with a raspberry pi.
When a button is pressed I access the relais.php with an AJAX request. The relais.php sends the corresponding commands to a python script from where the relays are controlled.
<!DOCTYPE html>
<html>
<body>
<label class="switch">
<input type="checkbox" id="IN1" onclick="in1()">
</label>
</body>
<script>
function in1() {
var x = document.getElementById("IN1").checked;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "relais.php?dir=IN1=" + x, true);
xhttp.send();
var out1 = x; }
</script>
</html>
The problem is the page gets reloaded the buttons are reset to the "unchecked" state. How could I store the states of the inputs on the webserver? The result would be that I could access the webUI from another device and the buttons would be "remembered" every time I reload.
Q: How could i make the webbrowser know which buttons are in the "checked" state and which are "unchecked" every time i load the website?
A: If you want to "save state" with respect to a particular web browser, use cookies.
If you just want to "save state", you'll need some kind of "database" on the Web/PHP server.
MySQL is a good choice, but in your case ANYTHING would work: including something like a MongoDB noSQL database, or even a simple text file.
Personally, I would prefer a sever-side solution. But here's an example that uses jQuery and cookies - completely browser-side:
jQuery Toggle with Cookie
There are two ways to keep consistency across pages (that I can think of off the top of my head).
You need to store the state in a database and/or in a server session.
Otherwise you can store it within a cookie, and get the cookie contents, but cookies can be deleted and edited, so it might not be the best solution.
Example PHP:
<?php
// Set the header
header("Content-Type: text/json");
/*
* Create a Mysql connection with PDO
* http://php.net/manual/en/pdo.construct.php
*/
// Prepare a query
$sth = $dbh->prepare("select col1, col2, col3 from fruit where user_id = ? limit 1");
// Execute the query, and replace the `?` with the value of `$_GET['key']`
$sth->execute([$_GET['key']]);
// Get the row
$reslut = $sth->fetch();
// print the result to the page
echo json_encode($reslut);
Example jQuery ajax:
// Make a request to the php file with the key `123456`.
// This could be a user id, hash or whatever you want it to be
// as long as it is in the database.
// this example is using it as a user id.
$.get('/path/to/phpfile.php?key=123456', result => {
console.log(result);
});

Is it possible to delete an entire Webpage when the user navigates away?

If the user navigates off the webpage, is it possible to execute a php script?
I know that Javascript can be executed..
$(window).bind('beforeunload', function(){
return 'DataTest';
});
Cookies might work, but I am not sure how a listener could track an expired cookie, and then delete the correct webpage.
A sample file system is like this:
user0814HIFA9032RHBFAP3RU.php
user9IB83BFI19Y298RYBFWOF.php
index.php
listener.py
data.txt
Typically, to create the website, php writes to the data.txt and the Python listener picks up this change, and creates the file (user[numbers]). As you might think, these files stack up overtime and they need to be deleted.
The http protocol is stateless, therefore users simply can not "navigate away".
The browser requires a page, the server returns it, and the communication stops.
The server doesn't have reliable methods to know what the client will do with that page.
Disclaimer: I'm not sure, as Fox pointed out, that this is the right way to go in your case. I actuallly upvoted Fox's answer.
However, if you absolutely need to delete each page right after the user left it, use this:
$(window).bind('beforeunload', function() {
$.ajax('yourscript.php?currentUser=0814HIFA9032RHBFAP3RU');
});
Then in yourscript.php, put something like the following:
<?php
// load your userId (for example, with $_SESSION, but do what you want here)
$actualUser = $_SESSION['userId'];
// checks if the requested id to delete fits your actual current user's id
if (isset($_GET['currentUser'] && $_GET['currentUser'] == $actualUser)
{
$user = $_GET['currentUser'];
$file = 'user'.$user.'.php';
unlink($file);
}

What can I use to avoid mailto size limit?

I have read a lot of pages about avoiding the mailto length limit, but I haven't found an answer to my issue.
My problem is that I cannot send mail from the server (with PHP) because the employees have to keep a history of their emails on their private mail box.
I have to open the mail software client with some fields that are filled, after selecting one type of email.
My select looks like like this :
<select <!-- ... --> onchange="sendMailClientSide(this.value);">
<!-- ... -->
</select>
and my javascript function :
function sendMailClientSide(refType) {
// ...
var dest = "test#domain.ty";
var subj = "Why this doesn't work ?";
var body = /* a very big body */;
var linkMailto = "?bcc="+dest+"&subject="+subj+"&body="+body;
document.location.href = "mailto:"+linkMailto;
// ...
}
For some mails types, this works perfectly.
But with a body more larger than 1400 characters, the client software doesn't open.
I have tried submitting HTML form too. With this method, the limit seems to be highter but it still has a limit because it fails with a bigger mail.
And finally, I tried cutting the body (something like this "&body="+body1+"&body="+body2+...) but it doesn't work.
Anybody know if a Firefox plugin exists to expand the mailto size ? Or something like this (something from client side) ?
I don't think that it is directly possible. Maybe with a plugin, as you already suggested.
My workaround would be to provide the user with a simple form which submits to the server which then sends the mail out directly (without opening the clients mail program at all). Thus you can easily avoid the size limit at all.
The problem with this would be, that the user don't have their known email interface and thus special text formatting, custom signatures and stuff like this won't work.
You would have to decide this based on the formatting needs and who is the recipient.

Categories