how to fetch values from array input in javascript - javascript

How do I properly fetch values from array in javascript:
<html>
<head>
<script type="text/javascript">
function proc()
{
var cost = document.yoh.coz.value;
var qtybuy = document.yoh.qbuys.value;
var st = cost * qtybuy;
var tbox = document.yoh.subtotal;
if (tbox)
{
tbox.value = st;
}
}
</script>
</head>
<body>
<?php
include('conn.php');
$prodname = $_GET['prodname'];
$result = query_database("SELECT * FROM prod_table WHERE PRODUCT='$prodname'", "onstor", $link);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<form name="yoh" method="get">
Product id: <input type="text" name="prodid" value=""><br/>
Cost: <input type="text" name="coz" value="<?php echo $row['S_PRICE']; ?>"><br/>
Quantity to buy:<input type="text" name="qbuys" value="" onkeyup="proc();"></br>
Subtotal:<input type="text" name="subtotal" value=""></br>
</form>
</body>
<?php } ?>
</html>
As you can see this program will just multiply the 2 values. One of the values would be fetched from the database, and the other comes from the user.
If I do it this way, I don't get any results:
<html>
<head>
<script type="text/javascript">
function proc()
{
var cost = document.yoh.coz[].value;
var qtybuy = document.yoh.qbuys[].value;
var st = cost * qtybuy;
var tbox = document.yoh.subtotal[];
if (tbox)
{
tbox.value = st;
}
}
</script>
</head>
<body>
<?php
include('conn.php');
$prodname = $_GET['prodname'];
$result = query_database("SELECT * FROM prod_table WHERE PRODUCT='$prodname'", "onstor", $link);
?>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<form name="yoh" method="get">
Product id: <input type="text" name="prodid[]" value=""><br/>
Cost: <input type="text" name="coz[]" value="<?php echo $row['S_PRICE']; ?>"><br/>
Quantity to buy:<input type="text" name="qbuys[]" value="" onkeyup="proc();"></br>
Subtotal:<input type="text" name="subtotal[]" value=""></br>
</form>
</body>
<?php } ?>
</html>
Do I need to include the index manually? What do I need to do to achieve the same results when using arrays.

You can use a name value:
cost=document.yoh.elements['coz[]'].value;

You need to iterate through the arrays. To iterate through an array (or object) in JavaScript:
for (key in arr){
// The key will be set to each key in the array (arr)
// The value at that key will be arr[key] (like always)
}
I'm not entirely sure what your goal is, but in general, know that the "[]" syntax is PHP only, JavaScript treats it as any other name (and possibly as a syntax error).

Related

PHP associative array null in Javascript function

I have a PHP webpage containing 6 textboxes as given below:
<html>
<script type="text/javascript">
function add()
{
//PHP associative array not storing properly in JS array
var array = JSON.parse(<?php echo json_encode($elementsindex); ?>);//getting array
//JS array elements not printing
for(var i in array)
{
alert("key = "+i+" and value = "+array[i]);
}
for(var key in array)
{
if(array[key]===null || array[key]===0)//for loop not executing
{
var valtoadd = 5;
array[key] = valtoadd;//add value to index IN ARRAY
var textbox = document.getElementById(key);
textbox.value = valtoadd;//add value to textbox
}
}
}
</script>
<body>
<form method="POST" action="">
<div id="operation">
<input type="text" id = "5E" name="5E" value="">
<input type="text" id = "4E" name="4E" value="" >
<input type="text" id = "3E" name="3E" value="">
<input type="text" id = "2E" name="2E" value="">
<input type="text" id = "1E" name="1E" value="">
<input type="text" id = "0E" name="0E" value="">
</div>
....rest of the code
</form>
..php code
I have a PHP code in the same page that invokes the Javascript function add() on a particular buttonclick() which is working perfectly:
<?php
include 'footer.php';
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['PUSH']))
{
//I am creating an associative array
$elementsindex = array("0E"=>0 ,"1E"=>0,"2E"=>0, "3E"=>0, "4E"=>0, "5E"=>0);
echo '<script type="text/javascript">';
echo 'add();'; //invoking JS function
echo '</script>';
}
?>
However in the Javascript function add(), the PHP array is not getting stored in var array. Also, the array elements are not printing in the alert box and the code never executes the for(var key in array) loop.
I am sure that the associative array is being passed correctly (the Javascript function is invoked successfully), but maybe not being received at the JS function because initially all the values in the key-value pair are zero (required for the project).
This code stores the $a into an object variable. I simply change the way to obtain the value.
var obj = <?php echo json_encode($a); ?>;
for (var i in obj)
{
alert("key = " + i + " and value = " + obj[i]);
}

how to get two dynamic textbox value in jquery

Thanks in advance, Actually i have a form with two hidden textbox fields one is <input type="hidden" name="item_name" class="course_name" value="<?php echo $cartData['exam'];?>"> and the other is <input type="hidden" name="amount" class="amount" value="<?php echo $priceTotal;?>">, the the value is taken inside the hidden field dynamically from PHP code through loop. So how can i get the dynamic values of "item_name" textbox field and "amount" textbox field in comma seperated using Jquery when clicking the image button with id="placeOrder".
For example like this : for amount-->200,300 and for course name -->PMP,CAPM . I have written some code it will take the values within the jquery each loop but i have to pass through ajax as json format like this data : {cname:course_name,priceBox:textboxVal} so value with comma seperated value should pass through course_name & textboxVal.
My Page is
<html>
<head>
<title></title>
<script>
$(document).ready(function(){
var myArray = [];
$('.amount').each(function(){
var textboxVal = $(this).val();
//alert(textboxVal);
});
var myCourse = [];
//dynamic course name
$('.course_name').each(function(){
var course_name = $(this).val();
//alert(course_name);
});
if(textboxVal!="")
{
$.ajax({
type : "POST",
url : "/invl_exams/cart",
cache : "false",
data : {cname:course_name,priceBox:textboxVal},
success : function(result){
console.log(result);
}
});
}
});
</script>
</head>
</html>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<td>
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="shopbusiness#myshop.com">
<input type="hidden" name="upload" value="1">
<?php
if(isset($cartDatas))
{
$itm_no = 1;
$amt = 0;
foreach($cartDatas as $key=> $cartData)
{
$prices = $cartData['price'];
$prd_price = ltrim($prices,'$');
$priceTotal = number_format((float)$prd_price, 2, '.', '');
?>
<input type="hidden" name="item_number" value="<?php echo $itm_no++;?>">
<input type="hidden" name="item_name" class="course_name" value="<?php echo $cartData['exam'];?>">
<input type="hidden" name="amount" class="amount" value="<?php echo $priceTotal;?>">
<input type="hidden" name="shipping" value="shipping Address">
<input type="hidden" name="quantity" value="<?php echo $cartData['orders'];?>">
<?php
$price = ltrim($prices,'$');
$orders = $cartData['orders'];
$amt_Total = $price * $orders;
$amt += $amt_Total;
$amt_Total = number_format((float)$amt, 2, '.', '');
///$amt_Total = round($price * floatval( $orders ),2);
}
?>
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="amount" value="<?php echo $amt_Total;?>">
<?php
}
?>
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but03.gif" name="submit" id="placeOrder">
</td>
</form>
You can do something like following:
$(function(){
var amount = [];
var course = [];
$('.amount').each(function(){
amount.push($(this).val());
});
$('.course_name').each(function(){
course.push($(this).val());
});
console.log(amount.join(',')); //comma seperated value
console.log(course.join(',')) //comma seperated value
});
DEMO
You can use jQuery and attribute selectors to get the value:
var item_name = $('input[name=\'item_name\']').val();
var amount = $('input[name=\'amount\']').val();
var result = item_name + ',' + amount;
Now you can put this in your click handler.
If your inputs are enclosed within form element you can use this serialize the form input values to json object and then pass it to ajax call.
var postData = $("#enclosing_form_elm").serializeObject();
and in your script add reference to serialize object function after jquery
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Just a demo https://plnkr.co/edit/7maJAUSdakDuvVqXhnzi?p=preview
Thanks to Convert form data to JavaScript object with jQuery

How to insert values of dynamic fields into database using PHP ,MySqL and JQuery

I am trying to make a country -state selector in Jquery which should submit values in db using PHP. Here is the script:
<script type="text/javascript">
var state_arr=new Array("Jammu and Kashmir","Delhi","Uttar Pradesh","Tamil nadu","Maharashtra","Karnataka","West Bengal","Punjab","Haryana");
var s_a = new Array();
s_a[0]="";
s_a[1]="Srinagar|Jammu";
s_a[2]="New Delhi";
s_a[3]="Lucknow|Kanpur|Ghaziabad|Noida|Varanasi";
s_a[4]="Chennai";
s_a[5]="Mumbai|Pune|Aurangabad|Thane";
s_a[6]="Bangalore|Mysore";
s_a[7]="Kolkata";
s_a[8]="Chandigarh|Mohali";
s_a[9]="Gurgaon|Chandigarh";
function print_state(state){
//given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(state);
option_str.length=0;
option_str.options[0] = new Option('Select State','');
option_str.selectedIndex = 0;
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
function print_city(city, selectedIndex){
var option_str = document.getElementById(city);
option_str.length=0;
option_str.options[0] = new Option('Select City','');
option_str.selectedIndex = 0;
var city_arr = s_a[selectedIndex].split("|");
for (var i=0; i<city_arr.length; i++) {
option_str.options[option_str.length] = new Option(city_arr[i],city_arr[i]);
}
}
Here is the PHP code which displays the selector:
<?php if (!isset($_POST['submit_val3'])) { ?>
Select the State:
<select onchange="print_city('city',this.selectedIndex);" id="state" name ="state"></select>
<br />
City:
<select name ="city" id ="city"></select>
<script language="javascript">print_state("state");</script>
<input type="submit" name="submit_val3" value="Submit" />
<?php } ?>
Here is PHP code for submission:
if(isset($_POST['submit_val3']))
{
$city=$_POST['city'];
$state=$_POST['state'];
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME);
$query="UPDATE register_emp SET state='$state',city='$city' WHERE ID = '" . $_SESSION['ID'] . "'";
mysql_query($query,$dbc) or die('query failed');
mysql_close();
}
My problem is that on clicking on Submit button,no values are being submitted to database.Where am I wrong here ?
Please add a form tag and action , thats why its not submitting to php page.
<?php if (!isset($_POST['submit_val3'])) { ?>
<form method="post" action="yourphppage.php"> <!-- form tag and action page -->
Select the State:
<select onchange="print_city('city',this.selectedIndex);" id="state" name ="state">
City:
<select name ="city" id ="city">
<script language="javascript">print_state("state");
<input type="submit" name="submit_val3" value="Submit" />
</form>
<?php } ?>

Posting JavaScript Variable to MySQL using PHP

I am trying to send a JavaScript variable to PHP but not exactly sure how to do it, a few things have said Ajax but I've never used it before and can't get my head around it. Does anyone know what the easiest way to do this would be? The column which I am attempting to populate in my DB is called 'cogs'.
I have the following JavaScript code:
<script>
$(document).ready(function() {
$('#duration-select').change(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#request').removeClass('hidden');
$('#duration-value').text('Total cost for this duration = ' + (y) + ' cogs');
if($(this).val() !== '') {
} else {
$('#duration-value').text('');
}
});
$('#request').click(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#total').text(y);
});
});
</script>
And the following HTML code:
<label id="total"></label>
Here is where I am trying to post the data, everything else is posting except for the $cost:
<form name="form" method="post">
<div class="modal-footer">
<?php
if ($row3['availability'] === 'Available') {
if (isset($_POST['request'])) {
$to_id = $row3['customerid'];
$from_id = $_SESSION['customerid'];
$time_sent = date('Y-m-d H:i:s');
$subject = 'Request for ' . $row3['title'];
$title = $row3['title'];
$listingid = $listingid;
$cost = $_POST['total']; //posting 0
$message = $customer_data['first_name'] . ' ' . $customer_data['last_name']
$request = mysql_query("INSERT INTO messages (to_id, from_id, listing_id, time_sent, subject, message, cogs, messagenumber, title, msgrand) VALUES ('$to_id', '$from_id', '$listingid', '$time_sent', '$subject', '$message', '$cost', '1', '$title', '$randomString')") or die(mysql_error());
}
}
?>
<input type="submit" class="btn btn-success" name="request" value="Yes" />
<input type="submit" class="btn btn-danger" data-dismiss="modal" value="No" />
</div>
</form>
Then I am trying to post the value of the label id=total to my db or the JavaScript variable (y). The problem is that 0 is always being sent to the DB when it should instead be the value that is in the label where the id is total.
Use name parameter for hidden variable and it will be automatically passed to PHP .
<label id="total"></label>
<input type="hidden" name="total" id="nameID"/>
in javascript below $('#total').text(y); write $('#nameID').val(y); . Everything will work properly.
You used total label , but $_POST recognizes only input type so use input type=.... instead of a label,divs etc.
IF YOU REAllY NEED ANSWER REPLY HERE
you have make an input type and its value is to be set by that javascript and then you'll be able to get that $cost value in php code
<input type="hidden" value="" name="total" id="total">
..................
$("#total").val(y);
You can use this to send the variables....
<input type="text" id="name" class="name" placevalue="Enter you name" required /><br><br>
<input type="text" id="email" class="email" placevalue="Enter you name" required /><br><br>
<button id= "det_submit" onclick="submit_det()"> Submit </button>
<script>
function submit_det() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(name != "" && email != "") {
$.post(
'xx.php',
{
name : document.getElementById("name").value,
email1 : document.getElementById("email").value,
},
function(data){
alert(data);
});
} else {
alert("empty");
}
}
</script>
here is xx.php
<?php
if(isset($_POST['name']) && isset($_POST['email1'])) {
$name = $_POST['name'];
$email = $_POST['email1'];
//code to insert into your database......
}
?>
Use a ID and Name for hidden parameter like this
<label id="total"></label
<input type="hidden" name="name" id="name"/>
and in jQuery edit the code like this
$('#total').text(y);
$('#nameID').val(y);
hope that it will work

php javascript change innerHTML with select value from table

I've got a form with a input field(FIELD1). When the user types in FIELD1 it filters values in FIELD2. Then they click on FIELD2 and it display's the value selected via javascript (this tutorial: http://www.tizag.com/javascriptT/javascript-innerHTML.php). The problem I'm having is that the value of FIELD2 is the companyID in the table - how do I include the javascript to lookup the company name from the table. Picture attached.
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('cv_bus').value;
document.getElementById('boldStuff2').innerHTML = userInput;
document.getElementById('filterTxt').innerHTML = userInput;
}
</script>
<table style="width:500px;border:1px solid #000;">
<tr><td>2</td><td>Type in the box below to narrow the list of names:</td></tr>
<tr><td></td><td><input type="text" name="filterTxt" id="filterTxt" tabindex="2" style="width: 400px"></td></tr>
<tr><td></td><td><p>SELECTED: <font color=red><b id='boldStuff2'>NONE</b> </p></font></td></tr>
<tr><td></td><td>Select the apropriate name:</td></tr>
<tr><td></td><td><select autocomplete="off" id="cv_bus" name="cv_bus" size=15 tabindex="2" style="width: 400px" onclick="changeText2()">
<?php
include 'cv_con.php';
$get = mysqli_query($con,"SELECT * FROM cv_companies order by compname");
$result = mysqli_query($con,"SELECT * FROM cv_companies order by compname");
//$option = '';
while($row = mysqli_fetch_array($result)) {
$option .= '<option value = "'.$row['id'].'">'.$row['compname'].'</option>';
}
?>
<?php echo $option; ?></select>
var el = document.getElementById('cv_bus');
var text = el.options[el.selectedIndex].innerHTML;
Try this example, first get the ID then access to the options label.
replace this
var userInput = document.getElementById('cv_bus').value;
with
var userInput = cv_bus.options[cv_bus.selectedIndex].text;
another way is pass this in function:
<select autocomplete="off" id="cv_bus" name="cv_bus" size=15 tabindex="2" style="width: 400px" onclick="changeText2(this);">
function changeText2(selObj){
var userInput = selObj.options[selObj.selectedIndex].text;
document.getElementById('boldStuff2').innerHTML = userInput;
document.getElementById('filterTxt').innerHTML = userInput;
}

Categories

Resources