How to submit a form and execute javascript simultaneously - javascript

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.

Related

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.

Boostrap modal form with 2 submit buttons and save in database

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.

Adding MySQL requests to JS Code from JSFiddle

First and foremost, I want to say how amazing this community is. I've been reading and using this place for a bit now to get answers to a plethora of questions.
I'm currently working on building a student list (never really built a system before) system for our company using Bootstrap 3. I've got the meat of it worked out and have found this awesome JSFiddle by user Mils (many thanks) that does what I need it to in terms of adjusting data dynamically, which would be ideal for what we want.
http://jsfiddle.net/NfPcH/645/
My question is: how can I alter this so that it pulls data from a MySQL database I've created, and how do I alter it so that when adding/editing a row, it writes it to the db? I have a students.php page I created that pulls in the information as such:
// Prepare SQL Query
$STM = $db->prepare("SELECT `student_firstname`, `student_lastname`, `student_class`, `year` FROM students ORDER BY student_firstname");
// For executing prepared statement
$STM->execute();
// Fetch records
$STMrecords = $STM->fetchAll();
foreach($STMrecords as $row)
{
echo"<tr>";
echo"<td><a href='#' id='student-firstname' data-type='text' data-pk=".$row['student_firstname']."</td>";
echo"<td>".$row['student_lastname']."</td>";
echo"<td>".$row['student_class']."</td>";
echo"<td>".$row['year']."</td>";
echo"</tr>";
}
But this doesn't go hand-in-hand with the aforementioned JSFiddle, as it only posts the data on the page.
Thanks, everyone!
You need to redirect the get request in the JSFiddle to you php script. And the php script needs to return something on the expected format.
At the end of the fiddle there is a couple of mocks, there you can see how the output from the php script should be formatted.

Grab GET ajax calls from page just by providing URL

Here's an example of a page from the API I'm working with:
http://www.easports.com/fifa/football-club/apps/proclubs/PS4/CHIP%20IT%20BRO
On this page almost all of the data is being loaded in via GET calls.
Here are 3 of the main calls that I'm interested in:
http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/66232/members
http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/66232/info
http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/66232/stats
You'll notice that there is one thing in common with these calls, and that is the number after the "clubs/" part of the URL. In this case, it's 66232. That is the ID of the club. Basically, if I have this ID, I can get all of the information I need from this API.
The problem:
The only way I can grab this ID is if I manually inspect the page myself via Firebug. On my website, users will need to be able to automatically register their clubs. I want them to be able to provide the URL to their club page, eg.:
http://www.easports.com/fifa/football-club/apps/proclubs/PS4/CHIP%20IT%20BRO
Is there any way I can grab the ID in these ajax calls just by having the URL of the page? I don't even need the info that is returned from these calls, I just need the club ID that is part of the URL of these calls, eg.:
www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/66232/members
I can just use some string functions to grab the ID after the "clubs/" substring up until the next "/".
I've been looking all over for a solution but can't seem to find what I'm looking for.
Thanks in advance. :)
EDIT:
Why is my question getting downvoted like crazy? I think I explained it pretty well. :/
Try using PHP's DOMDocument:
// clubId.php
<?php
$dom = new DOMDocument; #$dom->loadHTMLFile('http://www.easports.com/fifa/football-club/apps/proclubs/PS4/CHIP IT BRO');
$bod = $dom->getElementsByTagName('body');
if($bod = $bod->item(0)){
$cid = $bod->getAttribute('club-id');
$ea = 'http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/'.$cid;
$members = #file_get_contents("$ea/memebers");
$info = #file_get_contents("$ea/info");
$stats = #file_get_contents("$ea/stats");
}
else{
echo 'Sorry, the Page is Probably Blocked!';
}
?>
Now you can echo $members, and the like, into HTML that creates JavaScript. Of course, you should have a firm grasp on JavaScript Objects and Arrays.
IT DOES APPEAR BLOCKED THOUGH!!!

Auto populate text_fields based on selected item from another collection_select in Rails 3

Hello people
I'm trying to figured this out, but I still can't do it.
I have a rails 3 app, I'm working with invoices and payments. In the form for payments I have a collection_select where I display all the invoices number (extracted from a postgres database), and what I'm trying to do is when i select an invoice autopopulate others text_fields (provider, address, etc.) without reloading the page, in the same form.
I know I should use ajax, js, jquery, but I'm a beginner in these languages, so i don't know how or where to start
hope you can help me... thanks
What you are going to want to do is route an ajax call to a controller, which will respond with json containing the information. you will then use jquery to populate the different fields.
In your routes:
get "invoice/:id/get_json", :controller=>"invoice", :action=>"get_json"
In your invoice_controller:
def get_json
invoice = Invoice.find(params[:invoice_id])
render :text => invoice.to_json
end
In your invoice model (if the default to_json method is not sufficent):
def to_json
json = "{"
json += "id:'#{self.id}'"
json += ",date_created:'#{self.date}'"
... //add other data you want to have here later
json += "}"
end
In your javascript file,
$("#invoice_selecter").change(function(){ //calls this function when the selected value changes
$.get("/invoice/"+$(this).val()+"/get_json",function(data, status, xhr){ //does ajax call to the invoice route we set up above
data = eval(data); //turn the response text into a javascript object
$("#field_1").val(data.date_created); //sets the value of the fields to the data returned
...
});
});
You are probably going to run into a few issues, i would highly recommend downloading and installing fire bug if you are not on google chrome.. and if you are, make sure you are using the development tools. I believe you can open them up by right clicking and hitting inspect element. Through this, you should be able to monitor the ajax request, and whether or not it succeeded and things.

Categories