Currency converter PHP echo in pop-up - php

I don't know how I can do popup with result in my currency converter with API http://api.nbp.pl/. This is my code:
<?php
if (isset($_POST['kwota']) && isset($_POST['waluta']) && is_numeric($_POST['kwota']) && is_numeric($_POST['waluta'] )){
switch ($_POST['waluta']) {
case 1:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/usd/'))->rates[0]->mid;
break;
case 2:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/eur/'))->rates[0]->mid;
break;
case 3:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/jpy/'))->rates[0]->mid;
break;
case 4:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/gbp/'))->rates[0]->mid;
break;
case 5:
$przelicznik = json_decode(file_get_contents('http://api.nbp.pl/api/exchangerates/rates/a/aud/'))->rates[0]->mid;
break;
default:
$przelicznik = 1;
}
$wynik = $_POST['kwota']/$przelicznik;
echo $wynik;
}
?>

The API is public, so you tecnically don't need PHP to do so, you can fetch the exchange rate and show the results using javascript/jQuery directly.
Here's an example on how to do so using jQuery:
<form id="exchange">
<input type="text" name="price" title="price">
<select name="currency" title="currency">
<option value="1">USD</option>
<option value="2">EUR</option>
<option value="3">JPY</option>
<option value="4">GBP</option>
<option value="5">AUD</option>
</select>
<input type="submit" value="calculate">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('#exchange').on('submit',function(e){
e.preventDefault();
var value = $(this).find('[name="price"]').val();
if(!value) {
alert("Insert a valid value");
return false;
}
switch ($(this).find('[name="currency"]').val()) {
case "1":
$link = 'http://api.nbp.pl/api/exchangerates/rates/a/usd/';
break;
case "2":
$link = 'http://api.nbp.pl/api/exchangerates/rates/a/eur/';
break;
case "3":
$link = 'http://api.nbp.pl/api/exchangerates/rates/a/jpy/';
break;
case "4":
$link = 'http://api.nbp.pl/api/exchangerates/rates/a/gbp/';
break;
case "5":
$link = 'http://api.nbp.pl/api/exchangerates/rates/a/aud/';
break;
default:
alert('Error');
return false;
}
console.log($link);
$.getJSON($link,function(result){
alert(value/result.rates[0].mid);
});
});
</script>

Related

Switch or if elseif statement in success :function(data) ajax

$status = $row->status;
switch ($status){
case "1":
$status = '<span class="badge badge-danger">Open</span> ';
break;
case "2":
$status= '<span class="badge badge-secondary">On Hold</span> ';
break;
case "3":
$status= '<span class="badge badge-success">In Progress</span> ';
break;
case "4":
$status= '<span class="badge badge-info">Closed</span> ';
break;
}
This is my switch statement in my php code ; How do i do the same insite ajax success : function(data)
This is my ajax function
success: function(response){
//console.log(response);
$('.sub').html(response.sub);
$('.msg').html(response.msg);
//value = $(this).val(response.status); //Get the value from db;
// if elseif or swithch statetment here//
$('.sts').html('<span class="badge badge-danger">Open</span>'); //post it to html div;
}
What can be done ?? is there any way to do it here or do i have to do it before encoding json?
You can also use switch case just like you use it in your php code like so:
success: function(response){
//console.log(response);
$('.sub').html(response.sub);
$('.msg').html(response.msg);
var status = response.status; //Get the value from db;
// if elseif or swithch statetment here//
switch (status) {
case "1":
$('.sts').html('<span class="badge badge-danger">Open</span>');
break;
case "2":
$('.sts').html('<span class="badge badge-secondary">On Hold</span>');
break;
case "3":
$('.sts').html('<span class="badge badge-success">In Progress</span>');
break;
case "4":
$('.sts').html('<span class="badge badge-info">Closed</span> ');
break;
default:
$('.sts').html('<span class="badge badge-danger">Open</span>');
}
}

PHP inside Jquery

I am developing a wordpress theme and now I am working on the theme options page. I added an option with "select" method to give the user the option to change the slider's fx. Now... this is the output of a text input that sets the fx duration <?php echo get_option('wis_fx_speed'); ?> and works fine! My problem is that <?php echo $fxSample ?> don't work.
Tried everything I knew and imagined (syntax, order, put the switch inside the jquery script etc) , searched the web but found nothing... Could you help me? Thanks in advance!
<?php
switch (get_option('wis_fx_slider')) {
case "opacity":
$fxSample = "opacity : 'toggle',";
break;
case "width":
$fxSample = "width : 'toggle',";
break;
case "opawidth":
$fxSample = "opacity : 'toggle', width : 'toggle',";
break;
case "blink":
$fxSample = "opacity : 'show',";
break;
}
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$("#photo-rotator").tabs({fx:{<?php echo $fxSample ?>
duration: <?php echo get_option('wis_fx_speed'); ?> }}).tabs("rotate", 2000);
});
</script>
OUTPUT:
<
script type="text/javascript">
jQuery(document).ready(function($){
$("#photo-rotator").tabs({fx:{ duration: 3000 }}).tabs("rotate", 2000);
});
</script>
EDIT
Works if I make it with radio.
When I need to pass some data to JavaScript, I find it helpful to build a PHP array first, then use json_encode to convert it to JavaScript. This avoids a lot of potential issues:
<?php
$tab_options = array(
'duration' => get_option('wis_fx_speed'),
'fx' => array()
);
switch (get_option('wis_fx_slider')) {
case 'opacity':
$tab_options['fx']['opacity'] = 'toggle';
break;
case 'width':
$tab_options['fx']['width'] = 'toggle';
break;
case 'opawidth':
$tab_options['fx']['opacity'] = 'toggle';
$tab_options['fx']['width'] = 'toggle';
break;
case 'blink':
$tab_options['fx']['opacity'] = 'show';
break;
}
?>
<script type="text/javascript">
var tabOptions = <?php echo json_encode($tab_options); ?>;
jQuery(document).ready(function($) {
$('#photo-rotator').tabs(tabOptions).tabs('rotate', 2000);
});
</script>
Benefits:
Much cleaner code (easier to read).
You don't have to worry about getting the commas, quotes, and other syntax right for all the possible cases. For example, as other people have mentioned, you don't have a default case. This approach will at least generate valid JavaScript if an option value is invalid.
To safely output any PHP value into a JavaScript value, use json_encode.
...{fx:<?php echo json_encode($fxSample); ?>, duration: <?php echo json_encode(get_option("wis_fx_speed")); ?>}...
Note also that you are missing a , and have an extra } in your code. Always look at the generated result to look for syntax errors.
You need a semicolon after each php line
...
$("#photo-rotator").tabs({fx:{<?php echo $fxSample; ?>
...
What about a default case value?
Try to debug doing a
var_dump(get_option('wis_fx_slider'));
var_dump($fxSample);
Maybe is it a scope problem? Try defining
$fxSample = "";
at the beggining, before the switch
Is get_option('wis_fx_slider') returning one of the options in the switch case?
You haven't sepcified a "default" so $fxSample will go undefined.
<?php
switch (get_option('wis_fx_slider')) {
case "opacity":
$fxSample = "opacity : 'toggle',";
break;
case "width":
$fxSample = "width : 'toggle',";
break;
case "opawidth":
$fxSample = "opacity : 'toggle', width : 'toggle',";
break;
default: // blink or anything else
$fxSample = "opacity : 'show',";
}
?>
Is your duration a string or number? If it's a string you need quotes like
duration: '<?php echo get_option('wis_fx_speed'); ?>' }}).tabs("rotate", 2000);
What happens when you view source? Is the PHP laying out the dynamically generated javascript correctly? Can you post the output?
Also, formatting
<?php
switch (get_option('wis_fx_slider')) {
case "opacity":
$fxSample = "opacity : 'toggle',";
break;
case "width":
$fxSample = "width : 'toggle',";
break;
case "opawidth":
$fxSample = "opacity : 'toggle', width : 'toggle',";
break;
case "blink":
$fxSample = "opacity : 'show',";
break;
}
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$("#photo-rotator").tabs({
fx: {
<?php echo $fxSample ?>
duration: <?php echo get_option('wis_fx_speed'); ?>
}
}).tabs("rotate", 2000);
});
</script>

How do I retrieve the value from a textbox in this example below

In my code below I am trying to INSERT VALUES into a database. I am using a switch statement where if a textbox equals one of the cases, then it matchs with one of the ‘OptionType’ rows in the database and from that display the ‘OptionId’ which matches the ‘OptionType’.
The problem though is that while doing a var_dump on the $optionquery, it shows that it is not retireving the value from the textbox. How can I get $selected_option from the query to retrieve the value from the textbox ($_POST[‘gridValues’])?
At the moment I am trying to use the case statement to retrieve the values from the textbox. E.g. If the textbox contains the number '4', then case '4' should be triggered.
Now below is the code of the textbox which is appended into a new table row in the application:
<script>
function insertQuestion(form) {
var context = $('#optionAndAnswer');
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $options = $("<td class='option'></td>");
var $questionType = '';
$('.gridTxt', context).each( function() {
var $this = $(this);
var $optionsText = $("<input type='text' class='gridTxtRow maxRow' readonly='readonly' />").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val())
$options.append($optionsText);
$questionType = $this.val();
});
$tr.append($options);
$tbody.append($tr);
</script>
<form id="QandA" action="insertQuestion.php" method="post" >
<table id="optionAndAnswer" class="optionAndAnswer">
<tr class="option">
<td>Option Type:</td>
<td>
<div>
<input type="text" name="gridValues" class="gridTxt maxRow" readonly="readonly" />
</div>
</td>
</tr>
</table>
</form>
Below is the php code where all the database stuff happens:
$insertquestion = array();
$options = $_POST['gridValues'];
switch ($options){
case "3":
$selected_option = "A-C";
break;
case "4":
$selected_option = "A-D";
break;
case "5":
$selected_option = "A-E";
break;
default:
$selected_option = "";
break;
}
$optionquery = "SELECT OptionId FROM Option_Table WHERE (OptionType = '"
. mysql_real_escape_string($selected_option)."')";
$optionrs = mysql_query($optionquery);
$optionrecord = mysql_fetch_array($optionrs);
$optionid = $optionrecord['OptionId'];
foreach($_POST['questionText'] as $question)
{
$insertquestion[] ="' ". mysql_real_escape_string( $optionid ) . "'";
}
$questionsql = "INSERT INTO Question (OptionId)
VALUES (" . implode('), (', $insertquestion) . ")";
echo($questionsql);
var_dump($optionquery);
mysql_close();
You need to loop around your switch (based on your var_dump):
$option_array = array();
foreach( $options as $i )
{
switch( $i )
{
case '1':
if( !empty( $i ) ){ $option_array[] = $selected_option; }
break;
//so on, and so forth for all of your field data...
}
}
Now that you have all of your field values re-worked and stored in the $option_array, you can loop through:
foreach( $option_array as $i )
{
//do whatever mysql jazz you need to do to get your data
}

Image not flashing

I have a PHP script that displays an image(according to the current time) and I want it to flash the image so I tried adding a script to do so but its some what not working. Please have a look. I would be thankful for your help. Thanks in advance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload="startit();">
<?php
$hour = date('H', time()); // Returns the hours of the server time, from 0 to 23.
switch ($hour) {
case '0':
$img = '0.jpg';
break;
case '1':
$img = '0.jpg';
break;
// ... and so on...
default:
$img = '1.jpg';
}
?>
<img src="<?php echo $img; ?>" id="mydiv" />
<script language=javascript>
/*This script written by Chris Stahl*/
/*It may be used and modified by */
/*webmaster's for private use. */
function startit() {
window.setInterval("changecolor()",100);
}
function changecolor() {
var rndred=Math.floor(256*Math.random());
var rndgreen=Math.floor(256*Math.random());
var rndblue=Math.floor(256*Math.random());
var colorarray=[rndred, rndgreen, rndblue];
var hexcolor="#";
for(i=0;i<3;i++) {
hexcolor=hexcolor +""+ converttohex(Math.floor(colorarray[i]/16));
hexcolor=hexcolor +""+ converttohex(colorarray[i]%16);
}
document.getElementById("mydiv").style.color=hexcolor;
}
function converttohex(num) {
switch (num) {
case 10: return "A";
case 11: return "B";
case 12: return "C";
case 13: return "D";
case 14: return "E";
case 15: return "F";
default: return num;
}
}
</script>
</body>
</html>
This will work
http://jsfiddle.net/mplungjan/9Kdh5/
<body>
<div id="myDiv"><img src="http://rd.cas.de/tim/native/image.png" id="myImg" /></div>
</body>
<script type="text/javascript>
/* This script written by Chris Stahl */
/* It may be used and modified by */
/* webmaster's for private use. */
window.onload=function() {
window.setInterval(changecolor,100);
}
function changecolor() {
var rndred=Math.floor(256*Math.random());
var rndgreen=Math.floor(256*Math.random());
var rndblue=Math.floor(256*Math.random());
var colorarray=[rndred, rndgreen, rndblue];
var hexcolor="#";
for(i=0;i<3;i++) {
hexcolor=hexcolor +""+ converttohex(Math.floor(colorarray[i]/16));
hexcolor=hexcolor +""+ converttohex(colorarray[i]%16);
}
document.getElementById("myDiv").style.backgroundColor=hexcolor;
}
function converttohex(num) {
switch (num) {
case 10: return "A";
case 11: return "B";
case 12: return "C";
case 13: return "D";
case 14: return "E";
case 15: return "F";
default: return num;
}
}
</script>

element in form is empty in IE

The following code is working in FF but not in IE. There is no value of document.myform["parameters"].value in IE.
The code:
function form_elements()
{
if(document.myform.elements["parameters"].value == '')
{
myform_values = ......
}
}
<form method="post" name="myform">
<div id="parameters_info">
<select id="parameters" name="parameters" onfocus="e =form_elements();" >
<?php
foreach($params_name as $name)
{
if($name == $param_posted)
{
echo "<option selected>$name</option>";
}
else
{
echo "<option>$name</option>";
}
}
?>
</select>
</div>
</form>
I tried also document.myform["parameters"].value but the value is empty.
My options are like:
<option>1234</option>
<option>234a</option>
And i want that the value of the option will be in the function.
10x,
Ronny
You need to give a value to each option. Also, you cannot get the selected option using the value of the select tag. You need to use:
var selectedOption = document.myform.parameters.options[document.myform.parameters.options.selectedIndex].value;
<option>1234</option>
1234 - is a text of an option.
<option value="1234">1234</option>
Now 1234 - is a text and value.
That should be:
document.forms["myform"].elements["parameters"].options[document.forms["myform"].elements["parameters"].selectedIndex].text
...or you can use a function like this, which returns an array of values from any field type:
function getFieldValueArray(fld, frm) {
// fld may be a field object or a field name
// frm may be an index or a name, defaults to document.forms[0] when needed and not supplied
//function returns an array of values
var form = frm ? document.forms[frm] : document.forms[0];
var field = (typeof(fld) == "object") ? fld : form.elements[fld];
var valueArray = new Array();
var multinode = (field.length>1) ? true : false;
var type = field.type;
if (!type) {
type = field[0].type;
}
switch(type) {
case "radio": //fall-through intentional
case "checkbox":
if (multinode) {
for (i=0; i<field.length; i++) {
if (field[i].checked) {
valueArray.push(field[i].value);
}
}
}
else {
if (field.checked) {
valueArray.push(field.value);
}
}
break;
case "select-one": //fall-through intentional
case "select-multiple":
var options = field.options;
for (i=0; i<options.length; i++) {
if (options[i].selected) {
valueArray.push(options[i].value ? options[i].value : options[i].text);
}
}
break;
case "text": //fall-through intentional
case "file":
valueArray.push(field.value);
break;
case "hidden":
valueArray = field.value.split(";");
break;
case "textarea":
valueArray = field.value.split("\n");
default:
alert("Field not found -- atGetField(" + fld.toString() + ")");
}
return valueArray;
}
The function comes in rather handy when you can't be certain what type the field may be (for instance, if the field is an editable type under some circumstances and hidden under others), but once written it's an easy fallback, particularly for selects, radios and checkboxes.

Categories