a user checks the type of zones and choose the type of change; this script will load the change description details from a database into a textarea field in html.
Then what I want to happend next is:
the descriptions text gets appended with the different zones the changes will take place within the html description textarea. I do not want the zones to be appended to my description data in my database. The issue is the appending of the different zones to the description field is not working..
I am using javascript to append the text. Can someone advice me why I need to correct my code?
<html>
<head>
<script language="JavaScript" type="text/javascript">
// who says we found anything? Maybe this id does not even exist.
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?change_type='+value;
data_center = [],
data_centers = "";
inputs = document.getElementsByTagName('input');
for (var x = 0, len = inputs.length; x < len; x++) {
{
if (inputs[x].type == "checkbox" && inputs[x].name == 'data_center[]') {
if (inputs[x].checked === true) {
data_center.push(inputs[x].value);
}
}
}
data_centers = (data_center.length > 0 ? ': ' + data_center.join(', ') : '') + '.';
document.getElementById('description').value += data_centers;
document.getElementById('impact').value += data_centers;
}
}
</script>
</head>
<?php
require_once("db_handler.php");
// $_REQUEST is both _GET and _POST
if (isset($_REQUEST['change_type'])) {
$change_type = mysql_real_escape_string($_REQUEST['change_type']);
} else {
$change_type = False;
}
$query = "SELECT `changeID` , `changeName` FROM `change`;";
$exec = mysql_query($query); // You need to be already connected to a DB
if (!$exec) {
trigger_error("Cannot fetch data from change table: " . mysql_error(), E_USER_ERROR);
}
if (0 == mysql_num_rows($exec)) {
trigger_error("There are no changes in the 'change' table. Cannot continue: it would not work. Insert some changeids and retry.", E_USER_ERROR);
}
$options = '';
while($row = mysql_fetch_array($exec))
{
// if the current pageid matches the one requested, we set SELECTED
if ($row['changeID'] === $change_type)
// who says we found anything? Maybe this id does not even exist.
$sel = 'selected="selected"';
else
{
// If there is no selection, we use the first combo value as default
if (False === $change_type)
$change_type = $row['changeID'];
$sel = '';
}
$options .= "<option value=\"{$row['changeID']}\" $sel>{$row['changeName']}</option>";
}
mysql_free_result($exec);
if (isset($_POST['description']))
{
$change_data = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO change ( changeID, description ) VALUE '{$change_type}', '{$change_data}' ) ON DUPLICATE KEY UPDATE description=VALUES(description);";
if (!mysql_query($query))
trigger_error("An error occurred: " . mysql_error(), E_USER_ERROR);
}
$query = "SELECT `changeID` , `changeName` FROM `change`;";
$exec = mysql_query($query); // You need to be already connected to a DB
// abbreviated unchanged code.
$query = "SELECT `description`, `impact` FROM `change` WHERE `changeID`='{$change_type}';";
$exec = mysql_query($query);
if (mysql_num_rows($exec) > 0)
{
// if it does, we're inside a textarea and we directly output the text
$row = mysql_fetch_array($exec);
$textareaDescription = $row['description'];
$textareaImpact = $row['impact'];
} else {
$textareaDescription = '';
$textareaImpact = '';
}
mysql_free_result($exec);
?>
<body bgcolor="white">
<form name="changeform" method="post" action="email_form.php">
<table>
<tr valign="top">
<td><b>Data Center</b></td>
<td><input name="data_center[]" type="checkbox" value="[Zone10]"/>[Zone10]
<input name="data_center[]" type="checkbox" value="[Zone11]"/>[Zone11]
</td>
</tr>
<tr valign="top">
<td><b>Change Type</b></td>
<td><select id="change_type" name="change_type" onChange="getData(this)""><?php print $options; ?></select></td>
</tr>
<tr valign="top">
<td><b>Description</b></td>
<td><textarea name="description" id="description" cols="50" rows="10"><?php print $textareaDescription; ?></textarea></td>
</tr>
<tr valign="top">
<td><b>Service Impact</b></td>
<td><textarea name="impact" id="impact" cols="50" rows="10"><?php print $textareaImpact; ?></textarea></td>
</tr>
<tr valign="top">
<td align="center" colspan="2"><input type="submit" value="submit change" /></td>
</tr>
</table>
</form>
</body>
</html>
The following lines look like there might be something wrong:
for (var x = 0, len = inputs.length; x < len; x++)
{
{
Unless that is syntax that I'm just not familiar with.
Is there any way you could show us the actual code, running? Looking at something like this is a bit hard to digest without being able to see it in action.
Related
I have this quantity (var name: $Quantidade) displayed from a cart and need to add + and - hrefs to make it increase/decrease value.
Quantity:
quantity
Full table:
table
The quantity var always starts at 1.
All my attempts have failed.
Here is some code for the table (works if the + href is removed):
<table class="cart" width=700px cellpadding="0" cellspacing="0" style="border: 1px;" rules="none" align="center">
<tr height=40px align="center">
<td>Product</td>
<td>Price</td>
<td></td>
<td>Quantity</td>
<td></td>
<td>Delete</td>
</tr>
<?php
// Carrinho
$total=0;
foreach($_SESSION['venda'] as $Prod => $Quantidade):
$SqlCarrinho = mysqli_query($conect,"SELECT * FROM produto WHERE id= '$Prod'");
$ResAssoc = mysqli_fetch_assoc($SqlCarrinho);
echo '<tr height=40px align="center">';
echo '<td>'.$ResAssoc['descricao'].'</td>';
echo '<td>'.number_format($ResAssoc['preco'],2,",",".").'€</td>';
echo '<td>-</td>';
echo '<td>'.$Quantidade.'</td>';
echo '<td>+</td>';
echo '<td>x</td>';
$total += $ResAssoc['preco'] * $Quantidade;
echo '</tr>';
endforeach;
echo '<tr height=40px>';
echo '<td colspan="6" align="right">Total: '.number_format($total,2,",",".").'€</td>';
echo '</tr>';
echo'</table>';
Here is some code for the sessions I use:
session_start();
if(isset($_POST['more'])){ $_SESSION['venda'] [$_GET['par']] = $_GET['par'] + 1 ; }
if(isset($_SESSION['venda'])){}
else{ $_SESSION['venda'] = array(); }
if(isset($_GET['par'])){ $_SESSION['venda'] [$_GET['par']] = 1 ; }
if(isset($_GET['del'])){
$Del = $_GET['del'];
unset($_SESSION['venda'][$Del]);
Everything works until I add the + href, then it disformats the table:
broken table
I have confirmed its not a css error, the href is gone with/without css.
You need to remove the # in the link.
<a href="?more=true&par='.$Prod.'>+</a>
instead of
<a href="#?more=true&par='.$Prod.'>+</a>
When sending requests to your server, the browser ignores everything after the first #. Your GET parameters are not sent with the request currently.
Update
Check out the marked line. It resets venda → par every time par is set (which is always the case if you want to increase your value). Maybe you also want this to initialize the var. In this case you need to fix the if statement (if(!isset($_GET['par'])){ /* ... */ }). Venda gets reseted too.
session_start();
if(isset($_POST['more'])){ $_SESSION['venda'] [$_GET['par']] = $_GET['par'] + 1 ; }
if(isset($_SESSION['venda'])){}
else{ $_SESSION['venda'] = array(); }
// This line
if(isset($_GET['par'])){ $_SESSION['venda'] [$_GET['par']] = 1 ; }
if(isset($_GET['del'])){
$Del = $_GET['del'];
unset($_SESSION['venda'][$Del]);
Update 2
I think you want the code like this:
session_start();
// First, check if all vars are initialized
// Init if 'venda' is NOT set
if (!isset($_SESSION['venda'])) {
$_SESSION['venda'] = array();
}
// Init if 'venda['par'] is not set
if (isset($_GET['par']) && !isset($_SESSION['venda'][$_GET['par']])) {
$_SESSION['venda'][$_GET['par']] = 1;
}
// Run the updates/deletions
// Increase if 'more' is set
if (isset($_POST['more']) && isset($_GET['par'])) {
$_SESSION['venda'][$_GET['par']] += 1;
}
// Delete
if (isset($_GET['del'])) {
$Del = $_GET['del'];
unset($_SESSION['venda'][$Del]);
}
I state that I'm very inexperienced with web programming.
I'm trying to write a very simple web server in which suppliers must login to have access to a page that presents a table. In the table there are all the active orders for that supplier. Every row presents a list of fields: most of them are only readable, but the last three are also editable. The request I have to satisfy is that every time a supplier leaves an editable field, an update query runs to the database to update that field. I know, it's inefficient, but this is the request I've received.
My problem is that I've all already ready: the pages, the methods to generate the queries, etc...
...but when the page launches che ajax request to the saving page, nothing happens.
I've tried everything, I also tried to execute some very stupids examples find out on sites like w3school and other. Also the most stupid jquery function that try to call another page doesn't run, and I don't know why.
My questions are two:
is the below code right? I think it is, I'm not able to find out any error, but i'm not sure at this point.
the second one, is there a way to check if it is a problem of the pc, of the web server, or something else that does'nt wirk properly? The machine is not mine, so I'm not authorized to try to install or uninstall to check the status of every component.
Thank you all.
Here the code of the client side page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<TITLE>Orders</TITLE>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
var temp = "";
function saveContext(obj) {
temp = "";
temp = obj.value;
}
function handleCheckbox(obj) {
if (obj.value == 1)
{
obj.value = "0";
}
else
{
obj.value = "1";
}
var values = obj.id.split("//");
updateDB("UPDATE ordini SET " + values[3] + "=\"" + obj.value + "\" WHERE idFornitore=\"" + values[0] + "\" and idOrdine=\"" + values[1] + "\" and codiceArticolo=\"" + values[2] + "\"");
}
// Validates that the input string is a valid date formatted as "aaaa-mm-dd"
function isValidDate(dateString) {
// First check for the pattern aaaa-mm-dd
if(!/^\d{4}-\d{2}-\d{2}$/.test(dateString))
return false;
// Parse the date parts to integers
var parts = dateString.split("-");
var day = parseInt(parts[2], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[0], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
return false;
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
};
function handleNota(obj) {
var values = obj.id.split("//");
updateDB("UPDATE ordini SET " + values[3] + "=\"" + obj.value + "\" WHERE idFornitore=\"" + values[0] + "\" and idOrdine=\"" + values[1] + "\" and codiceArticolo=\"" + values[2] + "\"");
}
function handleData(obj) {
var values = obj.id.split("//");
if(isValidDate(obj.value) == true)
{
updateDB("UPDATE ordini SET " + values[3] + "=\"" + obj.value + "\" WHERE idFornitore=\"" + values[0] + "\" and idOrdine=\"" + values[1] + "\" and codiceArticolo=\"" + values[2] + "\"");
}
else
{
alert("Insert a valid date");
document.getElementById(obj.id)
obj.value=temp;
obj.Focus();
}
}
function updateDB(sql) {
$.ajax({
type: "POST",
url: "/save.php",
data: {
query: sql;
},
success: function(output){
alert(output);
},
error: function(jqxhr, status, exception) {
alert('Exception: ', status);
}
});
}
</script>
</head>
<body>
<?php include "config.php"; $temp=""; ?> <!-- <==import code for database connection -->
<div id="wrap">
<div id="main">
<div id="colonna-1"><img src="immagini/logosx.png" height="123" width="210" alt="Logo">
</div>
<div id="colonna-2" style="text-align:center">
<div id="contenitore">
<div id="utente">
<?php
$user=$_SESSION['idFornitore'];
?>
<table id="enter">
<tr height="123"></tr>
<tr>
<td><img id="user" src="immagini/user.png" height="20" width="20"></td>
<td align="left"> Benvenuto </td>
<td align="letf"><?php echo"$user"." "?></td>
<td align="left">Logout</td>
</tr>
</table>
</div> <!--utente-->
<div id="contenuto">
<?php
$sql = "SELECT * FROM ordini WHERE idFornitore='$user' ORDER BY idOrdine, codiceArticolo ASC";
$result = mysqli_query($conn, $sql);
$numfields = mysqli_num_fields($result);
echo "<table id='elencoordini'><tr>";
for ($i=1; $i < $numfields; $i++)
{
echo '<th>'.ucwords(mysqli_fetch_field_direct($result, $i)->name).'</th>';
}
echo "</tr><br><br><br><br>\n";
$nr = mysqli_num_rows($result);
if ($nr != 0){
for($x = 0; $x < $nr; $x++){
while ($row= mysqli_fetch_array($result))
{
echo "<tr>";
for ($i=1; $i < $numfields-3; $i++)
{
echo '<th><input type="text" value="'.ucwords($row[$i]).'"readonly style="color:DimGrey"></th>';
}
if ($row[$i] == null)
{
echo '<th><input type="text" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i)->name.'" value="" style="font-weight: bold;" onclick="saveContext(this)" onfocusout="handleData(this)"></th>';
}
else
{
echo '<th><input type="text" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i)->name.'" value="'.ucwords($row[$i]).'" style="font-weight: bold;" onclick="saveContext(this)" onfocusout="handleData(this)"></th>';
}
if ($row[$i+1] == 1)
{
echo '<th><input type="checkbox" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i+1)->name.'" name="checkdate" value="1" checked onclick="handleCheckbox(this)"></th>';
}
else
{
echo '<th><input type="checkbox" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i+1)->name.'" name="checkdate" value="0" onclick="handleCheckbox(this)"></th>';
}
if ($row[$i+2] == null)
{
echo '<th><input type="text" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i+2)->name.'" value="" style="width: 400px; font-weight: bold;" maxlength="4000" onfocusout="handleNota(this)"></th>';
}
else
{
echo '<th><input type="text" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i+2)->name.'" value="'.ucwords($row[$i+2]).'" style="width: 400px; font-weight: bold;" maxlength="4000" onfocusout="handleNota(this)"></th>';
}
echo "</tr>\n";
}
}
echo "</table><br><br><br><br>\n";
}
else{
echo "No records found!";
}
// Close db conn
mysqli_close($conn);
?>
</div> <!--contenuto-->
</div><!--contenitore-->
</div><!--colonna2-->
<div id="colonna-3">
</div><!--colonna3-->
</div> <!--main-->
</div> <!--wrap-->
<?php include "footer.inc.php"?>
</body>
</html>
and here is the code of the server side page that, in my intention, has to update the database:
<?php
include "config.php"; //import code for database connection
$query=$_POST['query'];
if (mysqli_query($conn, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
?>
In generell I would do some backtracing basically since you have the echos in your php file you should check wether or not they are in the alert window since you use an ajax post to call the file. If you receive some output in your alert window that is defined in the php file, then you know for sure that your php file is being called correctly maybe you echo out the query that is being sent sometimes an input that contains a quote -> ' can screw up the query.
So basically do some backtracing until you realize that something is not called properly and there you should find the error.
Also I strongly recommend to build a database adapter class and some controllers to handle the functionalities. Having mysql functions inside the html file is a huge no go.
Hey guys I am trying to get a specific name from a table. Here is my code:
$(document).ready(function () {
$("#NotesAccessor").click(function () {
var notes_name = $(this).document.getElementById("#user_table");
alert(notes_name);
run();
});
});
Here is the above this is where I am trying to access the associated username with which table row was click with the #notesAccessor
Table:
.........
<td>
$csvusername
</td>
.........
<td>
";
if ($checkNotes[1] == 'No')
{
echo "None";
}
if ($checkNotes[1] == 'Yes')
{
echo "<a href='#' id='NotesAccessor'>Click to access</a>";
}
echo "
</td>
........
My question is - how do I get the $csvusername of the associated NotesAccessor so I can then send this to a dialog in Jquery and open of the notes of that one person I need to get.
Hope this makes sense.
update:
here is full table:
<table class='results'>
<tr class='firsttr' style='background:gray;'>
<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
<td>Phone</td>
<td>Username</td>
<td>Password</td>
<td>Status</td>
<td>Combined Single Limit</td>
<td>Bodily Injury Each Person</td>
<td>Bodily Injury Each Accident</td>
<td>Property Damage</td>
<td>Address</td>
<td>Notes</td>
<td>#</td>
</tr>"; $j = 0; while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { $val = 1; $csvfirst
= $row; $csvfirstname = $csvfirst['firstname']; $csvlastname = $csvfirst['lastname'];
$csvemail = $csvfirst['email']; $csvphone = $csvfirst['phone']; $csvusername
= $csvfirst['username']; $csvpassword= $csvfirst['password']; $csvstatus
= $csvfirst['status']; $csvnotes = $csvfirst['notes']; $csl = $csvfirst['Combinedlimit'];
$bodyinj = $csvfirst['bodyinjur']; $eachacc = $csvfirst['bodyinjureachacc'];
$propertydmg = $csvfirst['propertydmg']; // Select the current employees
address $psql = "SELECT MailingAdrs FROM insuranceverificationdisclaimer
WHERE TraineeUsername =:user"; $psth= $DBH->prepare($psql); $psth->execute(array(':user'
=> $csvusername )); while ($prow = $psth->fetch(PDO::FETCH_ASSOC)) { $pcheck
= $prow; $address = $pcheck['MailingAdrs']; } if ($csvstatus != "No Longer
Work Here" && $csvstatus == "Confirmed"){ //check to see if notes exist
if (empty($csvnotes)) { $checkNotes = 0; } else { $checkNotes = 1; } $memberfirstnamearray[$j]
= $csvfirstname; $memberlastnamearray[$j] = $csvlastname; $memberemailarray[$j]
= $csvemail; $memberphonearray[$j] = $csvphone; $membercsl[$j] = $csl;
$memberbodyinj[$j] = $bodyinj; $membereachacc[$j] = $eachacc; $memberpropertydmg[$j]
= $propertydmg; $memberstatus[$j] = $csvstatus; $memberaddress[$j] = $address;
$j++; $i++; echo "
<tr>
<td>$csvfirstname</td>
<td>$csvlastname</td>
<td>$csvemail</td>
<td>$csvphone</td>
<td class='user_table'>$csvusername</td>
<td>$csvpassword</td>
<td>$csvstatus</td>
<td>$csl</td>
<td>$bodyinj</td>
<td>$eachacc</td>
<td>$propertydmg</td>
<td>$address</td>
<td>"; if ($checkNotes == 0) { echo "None"; } if ($checkNotes == 1) { echo
"<a href='#' id='NotesAccessor'>Click to access</a>"; } echo "</td>
<td>$i</td>
</tr>"; } }
</table>
You are mixing pure JavaScript with jQuery, you can solve it as follows.
First of all, you can put a class to identify the <td> with $csvusername, like class='td_with_csvusername' and then do this:
$(document).ready(function () {
$(".NotesAccessor").on("click", function () {
var td = $(this).parent().parent().find(".td_with_csvusername");
alert(td.html());
});
});
Posting the output HTML is better than the PhP version but I assume you have HTML similar to this:
<table>
<tbody>
<tr>
<td>UserName</td>
<td><a href='#' id='NotesAccessor'>Click to access</a>"</td>
</tr>
</tbody>
</table>
Then you can look for the previous sibling of the parent of the anchor by using jQuery's parent() and prev(), similar to this:
$(document).ready(function () {
$("#NotesAccessor").click(function () {
var notes_name = $(this).parent().prev().html();
alert(notes_name);
//run();
});
});
DEMO - Looking to the matching username column
If the above HTML is not like that then please post the exact output as it is important for knowing how to traverse to the matching td in the same tr when you click the anchor. Assuming that is what you are trying to achieve.
Edit
Only seen your update now. I know you already have a solution but for completeness I have added to this answer anyway in case it is useful to future users.
In your sample code you already have class on the user-name cell user_table. You can use that to target instead then. Also, given you said you will have several rows with the #NoteAccessor, you should change the id="NoteAccessor" to class="NoteAccessor" as ids have to be unique or it is invalid HTML. In addition jQuery only returns the first element with a matched id.
The script which you end up with is straight forward then using parent() as before but now you can also use prevAll() specifying the class selector:
$(document).ready(function () {
// using class ".NotesAccessor" instead of id "#NotesAccessor"
// as element is repeated in each tr
$(".NotesAccessor").click(function () {
var notes_name = $(this).parent().prevAll('.user_table').html();
alert(notes_name);
});
});
DEMO - Using parent() and prevAll('.user_table')
I'm new to programming language. I want to know can i get value from other field and pass to other field in same form without using javascript ? Can someone explain to me ? Thank u.
This my form page
<form id="leave_form">
<table><tr>
<td width="70"><b>*</b> Date From:</td>
<td width="120"><span id="lv_date_from_btn"><input readonly class="field_required control" onchange="validateLeave('from')" id="lv_date_from" name="date_from" value="<?php echo $start_date?>" size="10" maxlength="10"/> <img src="images/calendar.gif"/></span></td>
</tr>
<tr>
<td width="70"><b>*</b> Date To:</td>
<td width="120"><span id="lv_date_to_btn"><input readonly class="field_required control" onchange="validateLeave('to')" id="lv_date_to" name="date_to" value="<?php echo $end_date?>" size="10" maxlength="10"/> <img src="images/calendar.gif"/></span></td>
</tr>
<?php if ($userid == '609'):?>
<tr>
<td><b>*</b> Relief Staff: </td>
<td>
<select name="userid" id="frm_userid2" class="field_required control" onchange="validateLeave('relief')" >
<?php
$leavefrom = $_REQUEST['from'];
$leaveto = $_REQUEST['to'];
if (empty($leavefrom))
{
echo '<option value="" selected disabled>Select...</option>';
}
else{
echo '<option value="" selected disabled>Select...</option>';
$sql = "
SELECT distinct fullname FROM core_user LEFT JOIN lms_tran ON lms_tran.userid = core_user.userid where core_user.userid NOT IN (SELECT userid FROM lms_tran WHERE date_from BETWEEN '$leavefrom' AND '$leaveto' AND app_status = 'Approved') AND core_user.userid != 609 AND core_user.status = 'Y' ORDER by fullname ASC
";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="'.$row["userid"].'">'.$row["fullname"].'</option>';
}
}?>
</select>
</td>
</tr>
<?php endif; ?>
</table>
</form>
and this is javascript
function validateLeave(type)
{
var days= jQuery('#frm_days').val();
var from = jQuery('#lv_date_from').val();
var to = jQuery('#lv_date_to').val();
var relief = jQuery('#frm_userid2').val();
if (type != 'check')
{
days_incorrect = true;
}
if (type == 'days' || type == 'from')
{
to = '';
relief = '';
}
if (type == 'to')
{
days = '';
}
if (
(
(days == '' ? 0 : 1) +
(to == '' ? 0 : 1) +
(from == '' ? 0 : 1)
) < 2
)
{
days_correct = false;
return;
}
days = parseFloat(days);
jQuery('#frm_days').val(days);
jQuery('.control').attr('disabled', true);
jQuery('#lv_loading').show();
jQuery.post('index.php?_m=lms&_a=leave_validate&from='+from+'&to='+to, {from:from,to:to,days:days}, function(res){
eval('var r = '+res+';');
if (r.status == 'OK')
{
days_incorrect = false;
if (r.to)
{
jQuery('#lv_date_to').val(r.to);
}
if (r.from)
{
jQuery('#lv_date_from').val(r.from);
}
if (r.days)
{
jQuery('#frm_days').val(r.days);
}
}
else if (r.status == 'HOLIDAYERROR')
{
alert('Incorrect leave start date. Leave start date can not fall into Weekend or Public Holidays');
days_incorrect = true;
}
else
{
alert('Incorrect leave period. Please check back Leave Start, Leave End and Leave Days')
days_incorrect = true;
}
jQuery('.control').attr('disabled', false);
jQuery('#lv_loading').hide();
});
}
and i could'nt get the value return in php code as i hv pass value via jQuery.
No, you can't. The only way to do something interactive is to do it with javascript if you the to see it. If it doesn't matter you can do this on the server by assigning the second variable with the value of the first.
I've created a website that uses Google's Currency Convert API to convert currencies that a user selects from a drop down list powered by JavaScript.
After submitting the form I get the following error:
file_get_contents(12gbp=?usd) [function.file-get-contents]: failed to open stream:
This immediately suggests to me that the URL is wrong. I don't feel that this is the case because if copy the above arguments into Google's API directly
http://www.google.com/ig/calculator?h1=en&q=12gbp=?usd
I receive the result that I'm expecting:
Here is the relevant code:
getCurrencyRates.php
<?php
// Feed URL's //
$googleCurrencyApi = 'http://www.google.com/ig/calculator?h1=en&q=';
function currency_convert($googleCurrencyApi, $amount, $master, $slave) {
$result = file_get_contents($googleCurrencyApi . $amount . $master . '=?' . $slave);
$result = str_replace("\xA0", ",", $result);
$expl = explode('"', $result);
if ($expl[1] == '' || $expl[3] == '') {
throw new Exception('An error has occured. Unable to get file contents');
} else {
return array(
$expl[1],
$expl[3]
);
}
}
?>
currency.php
<?php
require 'includes/getCurrencyRates.php';
// Check to ensure that form has been submitted
if (isset($_POST['amount'], $_POST['master'], $_POST['slave'])) {
$amount = trim($_POST['amount']);
$master= $_POST['master'];
$slave = $_POST['slave'];
// Check amount is not empty
if (!empty($amount)) {
// Check amount is higher than 1 inclusive
if ($amount >= 1) {
try {
$conversion = currency_convert($googleCurrencyApi, $amount, $master, $slave);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage();
}
// Check URL has been formed
if ($conversion == false) {
echo 'Sorry, something went wrong';
} else {
echo $conversion[0], ' = ', $conversion[1];
if ($from == $to) {
echo '<p>That was a pointless conversion!</p>';
}
}
} else {
echo 'Number too small. You must enter a number higher than 1 inclusive';
}
} else {
echo 'You must enter a number into amount';
}
}
?>
<body onload="changeList(document.forms['drops'].master)">
<script language="javascript">
var lists = new Array();
// First set of text and values
lists['gbp'] = new Array();
lists['gbp'][0] = new Array(
'usd',
'eur'
);
lists['gbp'][1] = new Array(
'usd',
'eur'
);
// Second set of text and values
lists['usd'] = new Array();
lists['usd'][0] = new Array(
'gbp',
'eur'
);
lists['usd'][1] = new Array(
'gbp',
'eur'
);
// Third set of text and values
lists['eur'] = new Array();
lists['eur'][0] = new Array(
'gbp',
'usd'
);
lists['eur'][1] = new Array(
'gbp',
'usd'
);
</script>
<script language="javascript">
// This function goes through the options for the given
// drop down box and removes them in preparation for
// a new set of values
function emptyList( box ) {
// Set each option to null thus removing it
while ( box.options.length ) box.options[0] = null;
}
// This function assigns new drop down options to the given
// drop down box from the list of lists specified
function fillList( box, arr ) {
// arr[0] holds the display text
// arr[1] are the values
for ( i = 0; i < arr[0].length; i++ ) {
// Create a new drop down option with the
// display text and value from arr
option = new Option( arr[0][i], arr[1][i] );
// Add to the end of the existing options
box.options[box.length] = option;
}
// Preselect option 0
box.selectedIndex=0;
}
// This function performs a drop down list option change by first
// emptying the existing option list and then assigning a new set
function changeList( box ) {
// Isolate the appropriate list by using the value
// of the currently selected option
list = lists[box.options[box.selectedIndex].value];
// Next empty the slave list
emptyList( box.form.slave );
// Then assign the new list values
fillList( box.form.slave, list );
}
</script>
<form name="drops" method="post" action="">
<table border=0 bgcolor="#ffeecc">
<tr>
<td>Amount e.g. 10</td>
<td><input type="text" name="amount" /></td>
</tr>
<tr>
<td>Select from</td>
<td><select name="master" size=1 onchange="changeList(this)">
<option value="gbp">gbp
<option value="usd">usd
<option value="eur">eur
</select>
</td>
</tr>
<tr>
<td>Select to</td>
<td>
<select name="slave" size=1>
<option>Netscape 4 width
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Convert Now" />
</td>
</tr>
</table>
</form>
Is this problem experienced from trying to combine a server side language with a client side one?
Thanks in advance.
Shiplu is right. It may have something to do with variable scope, which really doesn't make much sense. It is not a problem with google at least.