I have three variables. Two are server side from a database:
$base_duration = $arr['adzone_buyandsell_duration']
and
$base_price = $price['price']
both are int. The third will be user input: <input type="text" name="duration" value=""> I need to preform a calculation like such: $cal_price = $base_duration / $base_price * user_input I then need to be able to pass $cal_price back to be able to charge the user the correct price. I'm fairly familiar with php, but don't know how to perform this calculation in real time not when the form is submitted.
When the first two values only change when the page is loaded or resfreshed, there is no need for a AJAX call.
Add the following code to your page:
<script>
$('document').ready(function(){
$('#duration').change(function(){
var base_duration = <?= $arr['adzone_buyandsell_duration'] ?>;
var base_price = <?= $price['price'] ?>;
var userInput = $('#duration').val();
var cal_price = base_duration / base_price * userInput;
$('#calPrice').html(cal_price);
});
});
</script>
It will add the calculated result to a div with the id calPrice and you have to give the input field the id duration
I created a jsFiddle for you to see the code in its full glory. I just used dummy data for your php variables.
https://jsfiddle.net/03e3t137/
Make sure you add jQuery on your page by adding the following line in your <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Related
To start off, sorry if this is a duplicate, or explained already. I've read a minimum of 15 other topics that I assumed are similar to mine, yet I haven't had any success in getting it to work.
I currently have a form that is action="submit.php". The form is an order form (see Jfiddle link at bottom of post). Inside submit.php I'm making an array of all $_POST values. That works great. Now the problem:
On the forum page (where user inputs), I have the following JQuery script that calculates totals. There are 3 types of totals (all this is clear in the JFiddle). The 3rd total, called "overallTotal", takes the sum of all "grandTotal"s and as of now, puts in #overallTotal ID. I need that number to be included in the form submission (i.e., so it is accessible by $_POST).
Thanks in advance, and sorry again if this is repetitive.
JSFiddle: http://jsfiddle.net/rc694dzL/
function oninput(e) {
// process this row first
var row = $(e.target).closest("tr");
// explicitly cast to a number
var quantity = +$(e.target).val();
var price = +row.find(".val1").text();
var output = row.find(".multTotal");
var total = price * quantity;
output.text(total);
// now calculate total
var subtotal = 0;
var table = $(e.delegateTarget);
table.find(".multTotal").each(function () {
subtotal += (+$(this).text());
});
table.find(".grandTotal").text(subtotal);
// now calculate overall total
var overallTotal = 0;
$(document).find(".grandTotal").each(function () {
overallTotal += (+$(this).text());
});
$('#overallTotal').text(overallTotal);
Add a hidden input in your form like this
<input type="hidden" name="overallTotal" id="overallTotalInput">
and set the value from javascript like this
$('#overallTotalInput').val(overallTotal);
Now when submitting the form, the value will be stored into $_POST['overallTotal']
Add some hidden fields in the form, and then populate the values with jquery.
Edit: tweaking your Fiddle now with an example: http://jsfiddle.net/dozecnp6/1/
1) Added the hidden input in the form:
<input type="hidden" name="OverallTotal" id="overallTotalField">
2) Added a bit to your oninput() function:
$('#overallTotalField').val(overallTotal);
in this fiddle i can use type="text" you can change it to type="hidden"
check this
fiddle
I'm trying to automate a process.
I have a form when submitted makes a $.post() request to a PHP file and returns the result to the page.
I wanted to know how I could have it send X amount of POST requests depending on what the user sets the amount of requests to and with customized settings to change the settings of the request depending on the last result.
How would this be possible using jQuery/JS/PHP?
Example: http://puu.sh/4kipZ.jpg
You can choose the amount of requests you want and customize parameters (On win, On Loss).
Thanks.
You can define a constant in PHP for the amount of times the request is to be made. Then use it in JQuery
In PHP
define('REQUEST_AMOUNT', X);
IN HTML
<input type='hidden' id='amount', val='<?PHP echo REQUEST_AMOUNT;?>'>
IN JQUERY
var amount = $('#amount').val();
Now amount is the number of times you have to make request
This should give you an idea how to do it. As you can see, AJAX is the key.
Note that $.post() is almost identical to using $.ajax() -- but $.post() has a few settings hard-coded. The structure that I used is usually easiest when starting out, and then move on to the other formats, promise-based, etc.
Sorry, cannot do a jsFiddle for this because AJAX won't work over jsFiddle. However, this answer is completely stand-alone. Just copy/paste it into two files and run:
index.php (or whatever you wish to name it)
your_php_processor.php (if rename file, must also rename it in the ajax code block)
HTML and Javascript/jQuery:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var numrolls, ta;
$('#txtArea').attr({'disabled':'disabled'});
$('#gobutt').click(function() {
numrolls = $('#rollnum').val();
$('#txtArea').html('Results of ' +numrolls+ ' automated rolls:\r\n\r\n');
$.ajax({
type: "POST",
url: "your_php_processor.php",
data: 'rolls=' + numrolls,
success:function(data){
ta = $('#txtArea').val() + '\r\n';
$('#txtArea').val(ta + data);
}
});
});
}); //END $(document).ready()
</script>
</head>
<body>
Number of rolls to automate:<br>
<input type="text" id="rollnum" /><input type="button" id="gobutt" value="Go!" /><br>
<br>
Results:<br>
<textarea id="txtArea" rows="20" cols="30" ></textarea>
</body>
</html>
your_php_processor.php
<?php
$rr = $_POST['rolls'];
$all = '';
for ($i=1; $i<=$rr; $i++) {
$rand = mt_rand(1, 6);
$all .= $rand . "\r\n";
}
echo $all;
For more info/examples re AJAX, see the simple examples in this SO post
You may also find the comments following this article to be of interest as they discuss the legality of using various built-in random number generators.
I try modify plugin of cms and have problem with forms
Actually i have system which generate polls for send votes and all forms are as this :
<div class="sp-poll" id="poll-<?php echo $pollid; ?>">
<p class="sp-question">
<?php echo $question; ?>
</p>
<form method="post" action="<?php echo $postFile; ?>" id="spe_form-<?php echo $pollid; ?>"></form>
</div>
The javascript process:
jQuery(function () {
var $ = jQuery; // Because `$` is easier than using `jQuery`
$('.sp-poll form').submit(formProcess); // Access formProcess() when the poll is submitted
/**
* Form Process
* Process through the form
*
* #param object e
*/
function formProcess(e) {
e.preventDefault();
var poll = $('input[name=poll]').val(),
answer = $('input[name=answer]:checked').val(),
div = $(this).parent(),
action = $(this).attr('action');
$(this).slideUp('slow', function () {
updatePoll(action, poll, answer);
});
}
});
The problem it´s each form have different ID , and the processor only detect the first id , for example if i have 5 forms with differents IDs all time detect only one ID of one form but no the others when launch the process form , i try use :
jQuery(".sp-poll form").attr(id);
But always detect the same number and no detect each ID in each form
PS : I need the send the form ID attribute since the form repeats itself each and every time I create a poll on the page. I want to be able to detect data for each different form using their ID to sort them out.
When using HTML forms, only information stored in FORM FIELDS or the URL are sent back to the server. Element IDs have nothing to do with forms at all - they're for UI manipulation.
If you want to pass the form ID back to the server, use a hidden field.
I have a function that listens for onkeyup event, that onkeyup checks to see if a box has a value and if not blank is supposed pull the value of an elementID which is a phone number called from another page. It takes that value and inserts it in to a snippet of html that gets sent to another elementID. the folowing code is the function and the associated code.
<script language="javascript">
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox");
var cancelPhone = document.getElementById("cancelphoneLabel");
document.getElementById("cancelphonelistLabel").value = cancelPhone; <--gives the is null error
if(mnthchk.value!=""){
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $__ is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label>";
" </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
}
}
</script>
<label id="mnthlychkdiscoLabel"> </label> <---this is where the final data is to be displayed
<label id="cancelphoneLabel">1-800-555-1111</label> <--- this is the phone number pulled from another page,
all the data is pulled together in a single page when loaded but is written in separate page using smarty templates. I keep getting the entitled error and have tried a number of different things to fix it but im stumped any help is greatly appreciated.
here is a jfiddle http://jsfiddle.net/rn5HH/
I think you are trying to access that id before it's created.
Also .value is only for inputs. It looks like you are creating a label, so you'd use innerHTML instead.
Something like this:
<script language="javascript">
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox");
var cancelPhone = document.getElementById("cancelphoneLabel");
if(mnthchk.value!=""){
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $__ is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label></span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone; //<--gives the is null error
}
}
</script>
<label id="mnthlychkdiscoLabel"> </label> <---this is where the final data is to be displayed
<label id="cancelphoneLabel">1-800-555-1111</label> <--- this is the phone number pulled from another page,
I'm not 100% what you are trying to do, so i just tried to make it work. There are many things you could probably simplify in this. It would help if you could create a jsfiddle to show it more clearly.
Edit:
Fixed the fiddle so it works and shows the phone number:
updated fiddle
Is that what it's supposed to do?
How do I reload this input once after 3 seconds has passed after the webpage has loaded. using javascript
<input type="text" name="steamID" id="steamID" value="<?php echo $steamid; ?>">
Try looking at this answer on SO:
Reload random div content every x seconds
If that doesn't work for you, you will have to use ajax to get new content. Look at jQuery's API here:
http://api.jquery.com/jQuery.ajax/
Or if you're not using jQuery, look at this for a tutorial on AJAX:
http://www.w3schools.com/ajax/default.asp
Otherwise, for more help, please post more of your code -- but ajax will have to be used
If you want the PHP in your code to be run again, you need to make you code a little more complicated.
You will need the following components
a php file that will lookup and print $steamid only.
a javascript function that uses AJAX to get the information from the php file, sets the value of your input
call the javascript on page load, then set an interval for 3 seconds and call it again.
But based on this...
The problem i have that the PHP var $steamid are set after the input has been created so all i need todo is reload the input so the $steamid will show.
... I think you just need to re-order your PHP code.
By reset, I am assuming you mean set the value to null.
$(window).load(function(){
setTimeout( function() {
document.getElementById("steamID").value = "";
},3000);
});
EDIT: Based on your further description, wait until steamID is set, then put this on the page:
<script type="text/javascript">
document.getElementById("steamID").value = "<?php echo $steamid; ?>";
</script>
<?php
echo "<script type='text/javascript'>";
$steamid = "testing 1,2,3";
echo " var sID = '".$steamid."';";
?>
function setupRefresh() {
setInterval("refreshVal()", 3000);
}
function refreshVal() {
var e = document.getElementById('steamID');
e.value = sID;
}
</script>