Cannot echo HTML string in PHP using POSTed variable - php

Context:
using PHP to echo HTML.
Issue:
Echoed HTML does not display unless I've hard-coded $n (i.e. $n = 2;).
Trouble-shooting:
-I've confirmed that I'm receiving the POST data via echo,var_dump,print_r.
-I've confirmed that the for loop works by substituting hard-coded numbers for $n.
-I've made sure that the string being received via POST is an integer.
<?php
$n=intval($_POST["a"]);
for($count=1;$count<=$n;$count++)
{
echo '<li>foo ' . $count . ':<input type="text" name="bar' . $count . '" value="baz ' . $count . '"></li>';
};
?>
EDIT: The PHP gets POST from AJAX (see below)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#formid").change(function(){
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( response ) {
alert( response );
}
});
$("#div1").load("load.php");
});
});
</script>

Edit: As per your originally posted question
You are missing a ' after value="baz
value="baz . $count . '"></li>
^ // right there
Full echo should be:
echo '<li>foo ' . $count . ':<input type="text" name="bar' . $count . '" value="baz' . $count . '"></li>';
This has bitten me before, and what I usually do to concatenate long strings is after each period, I hit enter and create a new line.
Remember, PHP is white-space insensitive so feel free to separate lines all you'd like.

It's unclear as to what your expected result should be, yet using the (fixed) code that follows, produced the following in HTML source:
<li>foo 1:<input type="text" name="bar1" value="baz1"></li>
<li>foo 2:<input type="text" name="bar2" value="baz2"></li>
<li>foo 3:<input type="text" name="bar3" value="baz3"></li>
<li>foo 4:<input type="text" name="bar4" value="baz4"></li>
<li>foo 5:<input type="text" name="bar5" value="baz5"></li>
PHP (using 5 as a number)
Sidenote: I added . "\n" at the end of the code for clarity.
<?php
// $n=intval($_POST["a"]);
$n=intval(5);
for($count=1;$count<=$n;$count++)
{
echo '<li>foo ' . $count . ':<input type="text" name="bar' . $count . '" value="baz' . $count . '"></li>' . "\n";
};
?>
Edit
Successful test with form included:
<?php
if(isset($_POST['submit'])){
// $n=intval(5);
$n=intval($_POST["a"]);
for($count=1;$count<=$n;$count++)
{
echo '<li>foo ' . $count . ':<input type="text" name="bar' . $count . '" value="baz' . $count . '"></li>' . "\n";
};
}
?>
<form method="post" action="">
Number:
<input type="text" name="a">
<br>
<input type="submit" name="submit" value="Submit">
</form>
Sidenote:
Just to test both methods - one with and one without (intval), $n=$_POST["a"]; also worked.

Related

Pass a value to my function in php

I have a list of products in a table extracted from my DB.
Each product have a field with ALIQUOTA (= VAT, Tax).
I want to have the possibility to modify the aliquote value assigned to single products.
I did a drop menu next to the actual aliquote that contains all the allowed value from an aliquote table of my database. (that values are 0.00, 4.00, 10.00, 20.00).
Once selected, that value will be inserted in a readonly input text field with id "aliquota_XXX" (where XXX is the id that correspond to the product).
Then i want to save that value pressing the button CONFIRM VAT that activate the function save_modify (this function already exists in the project).
This is the code:
<select class="piccolo elemento_modulo_obbligatorio" id="aliquota_dropdown_<?php echo $row['rid']; ?>" name="aliquota_dropdown">
<?php
$aliquote = "SELECT aliquota,id AS aid FROM aliquote ORDER BY aliquota ASC";
$result_aliquote = mysql_query($aliquote) or die("Invalid query: " . mysql_error());
while ($row_aliquote = mysql_fetch_array($result_aliquote)) {
echo '<option onclick=\'';
?>
$("#aliquota<?php echo $row['rid']; ?>").val("<?php echo $row_aliquote['aliquota']; ?>");
<?php
echo ';\' value="' . $row_aliquote['aid'] . '">' . $row_aliquote['aliquota'] . '</option>';
}
?>
</select>
<input autocomplete="off" type="text" class="class12" id="aliquota<?php echo $row['rid']; ?>" name="aliquota" readonly="readonly" value="" />
<input type="button" onclick="save_modify("aliquota",document.getElementById('aliquota_<?php echo $row['rid']; ?>').value,<?php echo number_format($row['aliquota'],2,".",","); ?>);" value="CONFIRM VAT" />
The function save_modify is that:
function save_modify(cosa, valore_nuovo, valore_vecchio) {
$.ajax({
type: "GET",
url: "ajax_salva_modifica_valore.php",
data: "id_documento=" + <? php echo $_GET['id_documento']; ?> +"&cosa=" + cosa + "&id=" + id + "&valore_nuovo=" + valore_nuovo + "&valore_vecchio=" + valore_vecchio,
cache: false,
success: function(data) {
$("#sezione_messaggi").html("Succesfully modified!");
},
beforeSend: function() {
$("#sezione_loading").html("<img src='../images/ajax-loader.gif' />");
},
complete: function() {
$("#sezione_loading").html("");
post_modifica(id);
carica_righe();
}
});
}
And the part of ajax_salva_modifica_valore.php that interest that is:
<?php
session_start();
$cosa = $_GET['cosa'];
$array_id = split("_",$id);
$id_riga = $array_id[1];
$valore_nuovo = $_GET['valore_nuovo'];
$valore_vecchio = $_GET['valore_vecchio'];
if($cosa == "aliquota") {
$modifica = "UPDATE righe_documenti
SET aliquota = '" . $valore_nuovo . "'
WHERE id = " . $id_riga;
$result = mysql_query($modifica) or die("Invalid query: " . mysql_error());
}
?>
I don't know where is the problem, because the parameter passed to the function are correct, but the modify it's not applied...
Someone can help me to fix it or try another solution?
The save_modify and ajax_salva_modifica_valore.php are not made by me, so i suppose that them are correct (and they works for the edit of other products information...)
Thanks!
The main problem is that number_format() formats number as a string and should be enclosed in double quotes (") in your case.
<input type="button" onclick="save_modify("aliquota",this.id,$("#aliquota<?php echo $row['rid']; ?>").val(),"<?php echo number_format($row['aliquota'],2,",","."); ?>");" value="CONFIRM ALIQUOTA" />
However by looking at the rest of your code, it seems you don't need number_format() at all:
<input type="button" onclick="save_modify("aliquota",this.id,$("#aliquota<?php echo $row['rid']; ?>").val(),<?php echo $row['aliquota']; ?>);" value="CONFIRM ALIQUOTA" />

PHP Rand() resetting in maths game

I'm using PHP's Rand() function to generate two random numbers that I can compare against the user's, and echo out a success message if the user's answer equals (1st random number + 2nd random number.) However, I'm running into problems.
I suspected that the form was re-generating the numbers every time the form POSTED and the input was collected, so I tried using sessions instead to keep those numbers persistent. It's a mess to say the least.
I found this existing post: Problems with guess a number game , but the solution didn't remedy my problem.
<?php
if(empty($_POST))
{
$_SESSION['$number1'] = Rand(0, 100);
$_SESSION['$number2'] = Rand(0, 100);
}
if($_POST["submit"])
{
$input = $_POST['input'];
if($input == ($_SESSION['$number1'] + $_SESSION['$number2']))
{
echo "Correct! ";
}
else
{
echo "Incorrect! ";
}
}
echo "<hr><br> What is... <b>" . $_SESSION['$number1'] . " + " . $_SESSION['$number2'] . "</b>";
?>
<form action="" method="post">
<input type="text" name="input">
<input type="submit" name="submit">
</form>
<?php
echo "<b>DEBUG ANSWER: </b> " . ($_SESSION['$number1'] + $_SESSION['$number2']);
?>
Any help would be appreciated!
I changed a few things, personally, I wouldn't use the session, rather user hidden inputs. (if you're worried about security.. you shouldn't be.. numbers game, not banking site)
<?php
//Create a function to generate the random numbers (So we can re-use it)
function generateNumbers()
{
$one = Rand(0, 100);
$two = Rand(0, 100);
//Now return the random numbers
return array('number1' => $one, 'number2' => $two);
}
//Check if the submit button has been clicked
if($_POST["submit"])
{
$input = $_POST['input'];
if($input == $_POST['number1'] + $_POST['number2'])
{
echo "Correct! ";
}
else
{
echo "Incorrect! ";
}
}
//Now we create the numbers
$numbers = generateNumbers();
echo "<hr><br> What is... <b>" . $numbers['number1'] . " + " . $numbers['number2'] . "</b>";
?>
<form action="" method="post">
<input type="text" name="input">
<input type="submit" name="submit">
<!-- Personally I would rather use hidden inputs, than use the session -->
<input type="hidden" name="number1" value="<?php echo $numbers['number1'] ?>" />
<input type="hidden" name="number2" value="<?php echo $numbers['number2'] ?>" />
</form>
<?php
echo "<b>DEBUG ANSWER: </b> " . ($numbers['number1'] + $numbers['number2']);
?>

How can I see data loaded from a script dynamically?

Okay the following script is functional but not very good.
I am posting data in array and in bulk to a exec command.
Everything works and after some time I get an array back with my results. This is the problem it takes a very long time.
I would prefer to see the results as they are fetched so I would like to see the array come together line by line in my PHP script instead of one big block of data.
This is my code:
<html>
<body>
<form method="post">
<div align="center">
<textarea name="mp" cols="60" rows="10">0|1|2</textarea>
<br />
Delim:
<input type="text" name="delim" value="|" size="1" />
data1:
<input type="text" name="mail" value="0" size="1" />
data2:
<input type="text" name="prx" value="1" size="1" />
<input type="submit" value=" send " name="btn-submit" />
</div>
</form>
</body>
</html>
<?php
putenv("PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs");
if (isset($_POST['mp'], $_POST['delim'], $_POST['btn-submit'], $_POST['mail'], $_POST['prx'])) {
$mps = preg_split('/\r\n|\r|\n/', $_POST['mp']);
// Create an array to store results
$result_data = array();
// Iterate over requests
foreach ($mps as $mp) {
$mp = explode($_POST['delim'], $mp);
// Store the account details in variables
$email = $mp[$_POST["mail"]];
$proxy = $mp[$_POST["prx"]];
// Prepare a reusable string
$result_string = "/usr/local/bin/casperjs test.js \"" . $email. "\" \"" . $proxy . "\" 2>&1";
// Add result to the array
$result_data[] = $result_string;
}
// Store of results complete. We now display them.
if (count($result_data)) {
foreach ($result_data as $result_data_entry) {
echo exec($result_data_entry);
}
echo "</ul>";
}
}
?>
How can I do this?
You can't do this in PHP. PHP is executed all server-side, not client side. That means that the results are all found before sending it to the user. You could, however, use Javascript to do this. I'm not sure how you would do it, but there's probably a way to dynamically see the results of a query.
You can use the Symfony Process component which supports incremental output.
Example:
foreach ($mps as $mp) {
// ...
$result_string = new Process("/usr/local/bin/casperjs test.js \"" . $email. "\" \"" . $proxy . "\" 2>&1");
$result_data[] = $result_string;
}
// Store of results complete. We now display them.
if (count($result_data)) {
while (count($result_data_entry) > 0) {
foreach ($result_data_entry as $i => $process) {
if (!$process->isStarted()) {
$process->start();
continue;
}
echo $process->getIncrementalOutput();
if (!$process->isRunning()) {
unset($result_data_entry[$i]);
}
}
sleep(1);
}
}
Have you tried using
flush();
after
echo exec($result_data_entry);
?

calculate total score in percentage

<?php
$value1 = rand (1,10);
$value2 = rand (1,10);
?>
<form action="mathq.php" method="post">
<input type="text" name="input1a" value="<?php echo $value1; ?>" class="value" />
<input type="text" value="x" class="equa" />
<input type="text" name="input2a" value="<?php echo $value2; ?>" class="value" />
<input type="text" value="=" class="equa" />
<input id="answer" type="text" name="answer" value="" class="answer" /><br /><br />
<input type="submit" value="Submit answer" class="submit">
<INPUT TYPE="RESET" VALUE="Clear all fields of this form">
</form>
<?php
if(isset($_POST['input1a']) && isset($_POST['input2a']) && isset($_POST['answer'])) {
$result = $_POST['answer'];
$input1a = $_POST['input1a'];
$input2a = $_POST['input2a'];
if (!empty($input1a) && !empty ($input2a) && !empty($result)) {
//echo '<span class="success">Success! ';
}
if ($result == $input1a * $input2a)
{
print($input1a . ' x ' . $input2a . ' = ' . '<span class="correct">' . $result . '</span>' . '<br />Correct!');
}
else
{
print($input1a . ' x ' . $input2a . ' = ' . '<span class="incorrect">' . $result . '</span>' . '<br />Wrong!<br /> The correct answer was: ' . '<span class="correct">' . $input1a * $input2a . '</span>');
}
}
?>
I was wondering how i could calculate total score of right answers after the user hits the submit button? How could i create a loop that would go through the rand number of problems and after it goes through once it exits and outputs the person score as percentage of right or wrong answers. I'm stuck on this part.
I was also thinking of another way i could tackle this problem.
A user goes through the rand number of math problems once he is done with practices problem he or she hits Done button and it outputs his score. Can you give me guidance how i can do this? Thanks.
You need a place to store data whilst questions are in progress.
This would commonly be done in Session data, or in a local database. It could be done in cookies, but not advisable. It could also be done in a flat text file.
You'd need to count how many questions done, how many right answers, and you can then derive the resulting % to feed back to the user.
Without somewhere to store the intermediate data, you cannot do this.

PHP/Ajax collect and pass form data

I need to collect an input ('x_amount') with a php form, then post it to a page that generates a hash and then posts it to a third party site. I don't want the customer to have a two step process, so can this be done with ajax and php? Here's what I have so far, but it needs to be ajaxified (i think?)
<form action="https://globalgatewaye4.firstdata.com/pay" method="POST">
<?php
$x_login = "xxx-xxx"; // Take from Payment Page ID in Payment Pages interface
$transaction_key = "xxxxxxx"; // Take from Payment Pages configuration interface
$x_currency_code = "CAD"; // Needs to agree with the currency of the payment page
srand(time()); // initialize random generator for x_fp_sequence
$x_fp_sequence = rand(1000, 100000) + 123456;
$x_fp_timestamp = time(); // needs to be in UTC. Make sure webserver produces UTC
// The values that contribute to x_fp_hash
$hmac_data = $x_login . "^" . $x_fp_sequence . "^" . $x_fp_timestamp . "^" . $x_amount . "^" . $x_currency_code;
$x_fp_hash = hash_hmac('MD5', $hmac_data, $transaction_key);
echo ('<label>x_login</label><input name="x_login" type="hidden" value="' . $x_login . '">' );
echo ('<label>x_amount</label><input name="x_amount" type="hidden" value="' . $x_amount . '">' );
echo ('<label>x_fp_sequence</label><input name="x_fp_sequence" type="hidden" value="' . $x_fp_sequence . '">' );
echo ('<label>x_fp_timestamp</label><input name="x_fp_timestamp" type="hidden" value="' . $x_fp_timestamp . '">' );
echo ('<label>x_fp_hash</label><input name="x_fp_hash" type="hidden" value="' . $x_fp_hash . '" size="50">' );
echo ('<label>x_currency_code</label><input name="x_currency_code" type="hidden" value="' . $x_currency_code . '">');
?>
<input type="hidden" name="x_show_form" value="PAYMENT_FORM"/>
<input type="hidden" name="x_test_request" value="FALSE"/>
Enter Payment Amount:<br>
<input type="text" name="x_amount"/>
<input type="submit" value="Pay with Payment Pages"/>
</form>
In other words, can I collect the x amount, generate the hash and then post it to the third party with just one click of the submit button? How can I accomplish this?
Ok, so I saw that firstdata.com actually suggests you to do that. I've managed to make something for you.
You have to use ajax, post to same page the amount the client entered, process it and return to form. Sumbit form only when data is processed.
I made you entire script because it was getting frustrating at some point figuring out how to do it.
test.php
<?php
if(isset($_POST['amount']) && ($_POST['amount'] != '')){
$x_amount = $_POST['amount'];
$x_login = "xxx-xxx"; // Take from Payment Page ID in Payment Pages interface
$transaction_key = "xxxxxxx"; // Take from Payment Pages configuration interface
$x_currency_code = "CAD"; // Needs to agree with the currency of the payment page
srand(time()); // initialize random generator for x_fp_sequence
$x_fp_sequence = rand(1000, 100000) + 123456;
$x_fp_timestamp = time(); // needs to be in UTC. Make sure webserver produces UTC
// The values that contribute to x_fp_hash
$hmac_data = $x_login . "^" . $x_fp_sequence . "^" . $x_fp_timestamp . "^" . $x_amount . "^" . $x_currency_code;
$x_fp_hash = hash_hmac('MD5', $hmac_data, $transaction_key);
$values = array('login' => $x_login, 'amount' => $x_amount, 'sequence' => $x_fp_sequence, 'timestamp' => $x_fp_timestamp, 'hash' => $x_fp_hash, 'currency' => $x_currency_code);
echo json_encode($values);
die;
}
?><html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
var processed = false;
function makeProcessed(type){
processed = type;
}
function prepareForm(){
$('#submitPayment').val('Please wait ...');
var processPayment = $.ajax({
type: 'POST',
url: "test.php",
data: {"amount": $('#x_my_amount').val()},
dataType: 'json',
async: false,
success: function(data) {
$('#x_login').val(data.login);
$('#x_amount').val(data.amount);
$('#x_fp_sequence').val(data.sequence);
$('#x_fp_timestamp').val(data.timestamp);
$('#x_fp_hash').val(data.hash);
$('#x_currency_code').val(data.currency);
if(data.hash){
makeProcessed(true);
}
}
});
return processed;
};
</script>
</head>
<body>
<form action="https://globalgatewaye4.firstdata.com/pay" method="POST" id="payment" onsubmit="return prepareForm();">
<input type="hidden" name="x_show_form" value="PAYMENT_FORM"/>
<input type="hidden" name="x_test_request" value="FALSE"/>
<input name="x_login" id="x_login" type="hidden" value="">
<input name="x_amount" id="x_amount" type="hidden" value="">
<input name="x_fp_sequence" id="x_fp_sequence" type="hidden" value="">
<input name="x_fp_timestamp" id="x_fp_timestamp" type="hidden" value="">
<input name="x_fp_hash" id="x_fp_hash" type="hidden" value="" size="50">
<input name="x_currency_code" id="x_currency_code" type="hidden" value="">
Enter Payment Amount:<br>
<input type="text" name="x_my_amount" id="x_my_amount" />
<input type="submit" id="submitPayment" value="Pay with Payment Pages" />
</form>
</body>
</html>
I think you can do this by creating ajax-request on blur event with "x_amount" field.
if generating hash requires php then it will look like this:
form:
Enter Payment Amount:<br>
<input type="text" name="real_amount" id="real-amount"/>
<input type="hidden" name="x_amount" id="x-amount" />
javascript:
$('#real-amount').on('blur', function() {
$.ajax({
....
success: function(data) {
// returned hash should be put in x_amount field here
$('#x-amount').val(data);
}
});
});

Categories