I am continuing to work on my multi stage bootstrap form, and I have hit a roadblock trying to pull info from my DB.
The main page is PHP and is named quote_tool.php
I have the following functional requirements:
The data must come from the MySQL database.
The user should only receive data that they requested (i.e. a row from the db with info about user license should only be grabbed if the user checked a radio button to include user licenses on the form).
The information needs to be called from the DB without refreshing/reloading the page.
Currently I have a table in my DB with the following columns:
There are 3 different products in that table right now. The user can select a radio to say they want to include endpoints, and then there are 3 check boxes to allow the user to input a quantity for which endpoint(s) they want to include.
The input field looks like this:
<label for="device-9102" class="form-partner-label"><input type="checkbox" class="quote-chkbox" id="9102-chk"> 9102 IP Phone</label>
<input type="text" name="9102-quantity" class="form-endpoint-qty form-control" id="form-partner-9102" readonly value="0">
When the user checks the box and input a value this value is dynamically updated on the summary page as well in the following field:
<input type="text" readonly name="sum-9102-qty" class="summary-field sum-qty" id="sum-9102-qty">
There is also 2 other fields on the summary page regarding this product.
MSRP
Part Number
MSRP is a hidden field that will be used for additional calculations, but Part Number is visible on the summary page.
When the user inputs the value for the endpoint quantity I need to call the DB and pull the MSRP and Part Number from the refEndpoints table.
I am currently building a function to call the DB when the user hits the "Next" button on the form, and that looks like this:
//Call DB to fetch part number and msrp of 9102
$('#form-partner-9102').change(function()){
var quantity_9102 = $('#form-partner-9102').val();
if(quantity_9102 !== 0) {
}
});
This is the point that I am stuck at. I am not sure how to call the DB and place the values of the part number and the MSRP in the correct input fields on the summary page.
jQuery runs on the client side so it cannot connect to MySQL directly, however your question is tagged php, which runs on the server side and thus can connect to your database. First you will need to setup a PHP file that can respond to HTTP POST requests and return JSON. Here is a great answer that shows you how to do this: Returning JSON from PHP to JavaScript?
Once set up (and you will need to workout what parameters this PHP file takes in and how it converts this into a query so that it can respond) you can now setup some simple JavaScript to call this PHP file (lets call it query.php). Code that does this might look like this:
$.post('/query.php', {quantity: $('#form-partner-9102').val()}, function(resp) {
$('#PartNumber').html(resp.PartNumber);
});
Some important things to keep in mind are to always be sure to use prepared statements when taking user input and turning it into a query (don't just build a SELECT statement by joining strings). Also be sure to look at your event binding, you can probably write one generic handler for your inputs that takes the partner ID as a data-* attribute making your code smaller and easier to maintain.
Related
I have html and css code for a basic quiz template. I want to give the user the ability to make their own custom quiz.
Example: I have created my own math quizzes, science quizzes, etc, that the user can take. I am looking for the ability that Users can make their own personal quiz.
You don't append users input to your code. You should have your quiz as a data and let the user update the data by adding their quiz.
The structure of a form looks like this:
<form method = 'post' action='./handleSubmission/'>
<label>Question 1: </label>
<input type='text' class='question' name='question1'>
<label>Answer 1: </label>
<input type='text' class='answer' name='answer2'>
<label>Question 2: </label>
<input type='text' class='question' name='question2'>
<label>Answer 2: </label>
<input type='text' class='answer' name='answer2'>
<button>Submit</button>
</form>
(You can find all the different input types here. You might want another type for multiple choice questions.
When the user clicks on submit, the default behaviour is that the content of the form will be sent as an http request to the action url. if you set post as method, the method will be POST. If you set get as method, the method will be GET.
Now, in order to do something useful with it, there needs to be a server-side script at './handleSubmission/' or whatever url you put in here, that can read the sent data and upload it to some place where you store the data for your quizzes. This can be either a database or a repository containing some files.
I'd go for json files. Because json files can very easily be decoded and used in any web scripting language.
In PHP for example you'd get the content of the form through a special array called $_GET (or $_POST depending on the method).
You'd then have access to 'question1' with $_GET['question1'].
You'd then have to find a way to put that data into a json file.
To use the content of the json files, you can either use a backend script or a frontend script like javascript.
Are you already using a scripting language for the backend such as PHP or Python? Or do you focus on frontend?
If you want to focus on javascript and frontend, this is the alternative:
<form>
//...
<button id='btn-submit'>Submit</button>
</form>
As you can see, i ommited action and method because in this alternative we don't want to send the form to the server. What we'll do is, when the button is clicked, we'll capture the content of the form without refreshing the page, and then send it a Backend-as-a-service like Google Firebase.
const submitButton = document.querySelector('#btn-submit');
submitButton.addEventListener('click', (e) => {
/* important! prevents the default behaviour which is to submit the form */
e.preventDefault();
const data = [];
/* do stuff here to retrieve the data from form like: */
const questionInputs = document.querySelector('.question');
const answerInputs = document.querySelector('.answer');
for(let key in questionInputs){
data[key] = {
question: questionInputs[key].value;
answer: answerInputs[key].value;
}
}
sendToFirebase(data);
});
You'd then have to write the sendToFirebase function.
Firebase requires making an account, starting a project by giving a name etc. Then it gives you the code to put in your app and you can read the documentation about how to upload data to the Realtime Database.
I strongly prefer the first option however. Because i think in this case the Firebase Realtime Database would be a bit cumbersome to use compared to just setting up a small backend script that generates json files.
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.
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.
I have table user where id = primary key, lastchange = int with lastchange data (in seconds). And i have frontend page with js script. Also all users placed in div like table by pages. So, items has user id and used changed timevalue in attributes.
I want to request all changed user ids in 1 request (1 http and 1 sql). They can be changed by other user on site.
How can i do this? I dont want check every user in page by timer, there is too many requests.
In my mind it looks like:
js do get request with list of users in page in json format [{"id":1, "lastchange":123123},{"id":2, "lastchange":123123}...
Php does request in mysql like SELECT * FROM `users` WHERE `id` IN (1, 2, 3) AND `lastchange` NOT IN (123459, 123456, 123459); (this not works fine, there is no queue for lastchange, it checks all inside braces and result are wrong)
Php return only ids of different rows [1, 15, 22] etc. to js.
Js check every id separately in other request getting full info about user by id
I can check every user in php separately, but i want to know how can i do it with 1 SQL request
Sorry my bad English.
I think you might want to implement the solution differently as per the first comment.... but, if you want keep your current model the SQL you need would look something like:
SELECT * FROM users WHERE
(id = 1 AND lastchange <> 123123) OR
(id = 2 AND lastchange <> 123123) OR
...
This will keep the id's and the lastchange values that relate to each other being compared properly. It is pretty ugly SQL but not hard to generate in a loop.
Sorry my stupidness. I think i solve this.
Js request api with only user id in page
php response json like id, lastchange
js checking lastchange value and id in page
js request full data about changed user replaces old in page
Thx all for helping
I have an HTML form to update the address in the account that submits to a Java servlet.
The problem is that, the form should not accept free flowing address text. Instead the user should enter the zip code/house number/street name, and hit a search button.
This search needs to go to a webservice, perform authentication and get a list of valid addresses that match the search criteria.
This list of addresses should be displayed to the user in the same form (either unhide a hidden element or use a modal dialog), so the user can pick his address.
Only after the valid address is picked, the user should be able to hit the form submit button which sends the data back to the servlet.
I am not sure how to have these 2 buttons do different actions in the form. I am very new to JavaScript and any pointers or examples are much appreciated.
For your webservice build an output of the values based on a search result (a basic string). Put this data in a JSON statement or just a javascript array.
Return something that looks like this.
['SearchResult1', 'SearchResult2', 'SearchREsult3']
On your search box. Bind a function on change or blur.
$('#SearchBox').bind('change', function(){
var val = $(this).val();
//Please reference the Jquery Ajax function as im typing this from memory and i always mix one or two things up :).
$.ajax({
"type" : "post",
"url" : "yoururlhere",
"data" : { "search":val },
success : function(dataset){
//When it comes back here check to see if its valid data etc etc
//After you validate you can populate a picklist on the page with the values. Or do anything you want with the values like this
for(x in dataset){
$('#DocumentElement').append('<p>'+ dataset[x] +'</p>');
}
}
});
});
This should start you out. After that you can just do more things on the callback, or modify the dom in a way which suits you better :).