jQuery update does not work with IE7/8 - php

With the help of members from this post, I converted from prototype to jQuery.
function jsUpdateCart(){
var parameter_string = '';
allNodes = document.getElementsByClassName("process");
for(i = 0; i < allNodes.length; i++) {
var tempid = allNodes[i].id;
var temp = new Array;
temp = tempid.split("_");
var real_id = temp[2];
var real_value = allNodes[i].value;
parameter_string += real_id +':'+real_value+',';
}
var params = 'ids='+parameter_string;
$.ajax({
type: "POST",
url: "http://127.0.0.1/codeigniter_shopping/index.php/welcome/ajax_cart",
data: params,
success: function( r ) {
$('#ajax_msg').html( r );
location.reload( true );
}
});
}
function jsRemoveProduct(id){
var params = 'id='+id;
$.ajax({
type: "POST",
url: "http://127.0.0.1/codeigniter_shopping/index.php/welcome/ajax_cart_remove",
data: params,
success: function( r ) {
$('#ajax_msg').html( r );
location.reload( true );
}
});
}
ajax_cart_remove works in both Firefox and IE, but update works with Firefox, but it doesn't with IE 7/8.
Could anyone give me some suggestions please.
You can see the original prototype code here.
ajax_cart and ajax_cart_remove in controllers are followings.
function ajax_cart(){
$this->MOrders->updateCartAjax($this->input->post('ids'));
}
function ajax_cart_remove(){
$this->MOrders->removeLineItem($this->input->post('id'));
}
And models for MOders are following.
function removeLineItem($id){
$id = id_clean($id);
$totalprice = 0;
$cart = $_SESSION['cart'];
if (isset($cart[$id])){
unset($cart[$id]);
foreach ($cart as $id => $product){
$totalprice += $product['price'] * $product['count'];
}
$_SESSION['totalprice'] = $this->format_currency($totalprice);
$_SESSION['cart'] = $cart;
echo "Product removed.";
}else{
echo "Product not in cart!";
}
}
function updateCartAjax($idlist){
$cart = $_SESSION['cart'];
$records = explode(',',$idlist);
$updated = 0;
$totalprice = $_SESSION['totalprice'];
if (count($records)){
foreach ($records as $record){
if (strlen($record)){
$fields = explode(":",$record);
$id = id_clean($fields[0]);
$ct = $fields[1];
if ($ct > 0 && $ct != $cart[$id]['count']){
$cart[$id]['count'] = $ct;
$updated++;
}elseif ($ct == 0){
unset($cart[$id]);
$updated++;
}
}
}
if ($updated){
$totalprice=0;
foreach ($cart as $id => $product){
$totalprice += $product['price'] * $product['count'];
}
$_SESSION['totalprice'] = $this->format_currency($totalprice);
$_SESSION['cart'] = $cart;
switch ($updated){
case 0:
$string = "No records";
break;
case 1:
$string = "$updated record";
break;
default:
$string = "$updated records";
break;
}
echo "$string updated";
}else{
echo "No changes detected";
}
}else{
echo "Nothing to update";
}
}
The following is the html output of form
<form action="http://127.0.0.1/codeigniter_shopping_copy2/index.php/welcome/checkout" method="post"><table border='1' cellspacing='0' cellpadding='5'>
<tr valign='top'>
<td><input type="text" name="li_id[10]" value="1" id="li_id_10" class="process" size="5" /></td>
<td id='li_name_10'>Dress 1</td>
<td id='li_price_10'>33.95</td>
<td id='li_total_10'>33.95</td>
<td><input type='button' name='delete' value='delete' onclick='jsRemoveProduct(10)'></td>
</tr>
<tr valign='top'>
<td><input type="text" name="li_id[6]" value="2" id="li_id_6" class="process" size="5" /></td>
<td id='li_name_6'>Shoes 1</td>
<td id='li_price_6'>23.95</td>
<td id='li_total_6'>47.90</td>
<td><input type='button' name='delete' value='delete' onclick='jsRemoveProduct(6)'></td>
</tr>
<tr valign='top'>
<td colspan='3'> </td>
<td colspan='2'>81.85
<input type="hidden" name="name" value="total" />
<input type="hidden" name="id" value="total" />
<input type="hidden" name="value" value="81.85" />
</td>
</tr>
<tr valign='top'>
<td colspan='3'> </td>
<td colspan='2'><input type='button' name='update' value='update' onclick='jsUpdateCart()'/></td>
</tr>
<tr valign='top'>
<td colspan='3'> </td>
<td colspan='2'><input type="submit" name="submit" value="checkout" /></td>
</tr>
</table>
</form>

I don't think IE supports document.getElementByClassName("")
Try replacing
allNodes = document.getElementsByClassName("process");
with
allNodes = $(".process");
wich is the JQuery way.

In IE8 just bring up the Web Developer Toolkit and put a break point at this line:
$('#ajax_msg').html( r );
I would also put a break point at the .ajax call here:
var params = 'ids='+parameter_string;
$.ajax({
then see what happens.
This way you can ensure you are getting to it properly, else IE may have a problem before you get here, or, if you get here then you need to see if it goes out to the service and back, which is what the first url will tell you. Then single-step through the success code and see if it jumps out at some point due to an error.
Once you know for a fact that this code is the problem then you can update with what you have learned, but I have used this function in IE7 and 8 so it should work fine.

Related

Getting multiple dynamic html element values using jquery

I have a dynamic table which is created in server side (php), and I'm using jquery to show it in html page.
in this table there are multiple values which I want to edit them and save this edits in mysql.
but I don't know how to get this values the way that I tried is just updating the first value and is not getting other element values :
jquery code :
$('#save_edit').on('click',function() {
$('#edit_test_show').hide();
$('#enable_edit').show();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
var vop_title = $('#result_table').find('[name=op_title]').val();
var vop_descrip = $('#result_table').find('[name=op_descrip]').val();
var vobjects_count = $('#result_table').find('[name=objects_count]').val();
var vobject_val = [];
var vobject_id = $('#result_table').find('[name=object_id]').val();
for(i=0;i<vobjects_count;i++){
vobject_val[i] = $('#result_table').find('[name=object_val]').val();
}
$.post("Requests/OPS.php", //Required URL of the page on server
{ // Data Sending With Request To Server
EDIT_OPS : true,
op_id : vop_id,
op_title : vop_title,
op_descrip : vop_descrip,
objects_count : vobjects_count,
object_id : vobject_id,
object_val : vobject_val
},
function(response){ // Required Callback Function
$("#Response").text(response).css({color: 'green'});
});
});
dynamic table in php :
if($op_objects_count<=0) {
echo "<table class='styled-table' cellspacing = '0' width = '360' border = '1' >
<tr>
<th>
<label for='session_order' style = 'margin-right:10px;color:#595959;float: right;' >اهداف فرآیند : </label >
</th>
</tr>";
while ($objects_row = mysqli_fetch_assoc($op_objects)) {
echo "<tr>
<input name = 'object_id' type='hidden'
value = '" . $objects_row['id'] . "' />
<td>
<input name = 'object_val' style = 'width:340px;height: 36px;margin:0 3px 3px 3px;'
value = '" . $objects_row['object'] . "' />
</td>
<input name = 'objects_count' type='hidden'
value = '".$op_objects_count."' />
</tr>";
}
echo "</table>";
echo "<div class='cleaner h30'></div>";
my php query to update the database :
if($_POST['EDIT_OPS']==true){
$op_id = $_POST['op_id'];
$op_title = $_POST['op_title'];
$op_descrip = $_POST['op_descrip'];
//===================================
$objects_count = $_POST['objects_count'];
$object_id = $_POST['object_id'];
$object_val = $_POST['object_val'];
// print_r($object_val);
$save_edit = $DBM->RunQuery("UPDATE at_ops SET op_title='$op_title' , op_descrip='$op_descrip' WHERE id='$op_id'",true,false);
for($i=0;$i<$objects_count;$i++){
$save_edit = $DBM->RunQuery("UPDATE at_ops_objects SET object='$object_val[$i]' WHERE id='$i' AND ops_id='$op_id' ",true,false);
}
if(isset($save_edit) && $save_edit>0)
echo "success";
else
echo "failure";
}
If you change all names from for example
<input name='object_id'
to
<input name='object_id[]'
you can serialize the form and it will create arrays on the server.
As for getting all values in jQuery, this works for me:
$(function() {
$('#save_edit').on('click', function() {
var vobject_val = [];
$('#result_table').find('[name=object_val]').each(function() {
vobject_val.push(this.value);
});
console.log(vobject_val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class='styled-table' cellspacing='0' width='360' border='1' id="result_table">
<tr>
<th>
<label for='session_order' style='margin-right:10px;color:#595959;float: right;'>اهداف فرآیند :</label>
</th>
</tr>
<tr>
<input name='object_id' type='hidden' value='r1' />
<td>
<input name='object_val' style='width:340px;height: 36px;margin:0 3px 3px 3px;' value='1' />
</td>
<input name='objects_count' type='hidden' value='1' />
</tr>
<tr>
<input name='object_id' type='hidden' value='r2' />
<td>
<input name='object_val' style='width:340px;height: 36px;margin:0 3px 3px 3px;' value='2' />
</td>
<input name='objects_count' type='hidden' value='2' />
</tr>
<tr>
<input name='object_id' type='hidden' value='r3' />
<td>
<input name='object_val' style='width:340px;height: 36px;margin:0 3px 3px 3px;' value='3' />
</td>
<input name='objects_count' type='hidden' value='3' />
</tr>
</table>
<button type="button" id="save_edit">save</button>
I suggest something like this:
<table id="admTable">
<thead style="width:100%;">
<tr>
<th>row</th>
<th>name</th>
<th>username</th>
<th>pass</th>
<th>delete</th>
<th>edit</th>
</tr>
</thead>
<tbody id="adminsTb">
<?php
$i=1;
while( $admins=mysqli_fetch_array($results,MYSQLI_ASSOC))
{
echo '<form action="insert.php" method="post" id="formId">';
echo "<tr>
<td>$i</td><input type='hidden' name='id' value='$admins[id]'/>
<td><input name='adminname' type='text' value='$admins[name]' /></td>
<td><input name='user' type='text' value='$admins[user]'required='required' /></td>
<td><input name='pass' type='password' value='$admins[pass]' required='required' /></td>
<td> <input name='deladmin' type='submit' value='delete' /></td>
<td><input name='updateadmin' type='submit' value='save' /></td>
</tr>";
$i++;
echo " </form>";
}
?>
</tbody>
</table>
insert.php
if(isset($_POST['updateadmin'])){
$results=mysqli_query($dbCnn," update admins set name='$_POST[adminname]', user='$_POST[user]', pass='$_POST[pass]' where id=$_POST[id]");}
//Jquery ajax
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#formId').submit( processForm );
})(jQuery);

Fetch result from Database using Ajax

I want to display info and disable a process button if a certain condition is not met at the point of entering the value(onblur or onkeyup event). I have tried many example but none has given me result. Can someone help me out
The Ajax code:
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("select.custid").change(function () {
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url: "process-loan.php",
data: {
custQual: selectedCustomer,
custid: selectedCustId
}
}).done(function (data) {
$("#qualify").html(data);
});
});
});
</script>
Below is the php page
<th>Customer No:</th>
<td>
<select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php while ($rw = mysqli_fetch_array($get)) { ?>
<option value="<?php echo $rw['custid'] ?>"><?php echo $rw['custid'] ?></option>
<?php } ?>
</select>
</td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td id="qualify"> </td>
<td id="qualify"> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
The process-loan.php script that will respond to the ajax call:
<?php
if (isset($_POST["amt"])) {
include 'includes/session.php';
include 'includes/db_connection.php';
$amt = $_GET["amt"];
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if ($amt !== NULL) {
$gets = "SELECT * FROM tab_customer_dailycontribution WHERE custid='" . $custid . "' AND transactionDate BETWEEN '2015-09-01' AND '2015-09-30'";
$get = mysqli_query($connection, $gets);
$sum = 0.00;
while ($row = mysqli_fetch_array($get)) {
$sum += $row['amountContribute'];
}
if ($sum >= $amt) {
//qualify for loan $ enable the Process Button to save
echo "You are Qualify to Apply";
} else {
//disqualify for loan $ disable the process button until condition is meant.
echo "Insufficient Fund: Unqualify to Apply";
}
//end if condition
}
}
?>
this is for demo so i have commented tour mysql related things:first change your keys in process-loan.php.
your view page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#pButton").hide();
$("#amt").on("blur",function(){
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url:"process-loan.php",
data:{custQual:selectedCustomer,custid:selectedCustId},
success:function(data){
var data=JSON.parse(data);
$("#qualify").html(data.msg);//your message
if(data.status == 0){
$("#pButton").show();//showing button if qualified
}else{
$("#pButton").hide();
}
}
});
});
});
</script>
<th>Customer No:</th>
<td><select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php $i =0; while($i <4){?>
<option value="<?php echo $i?>"><?php echo $i?></option>
<?php $i++;}?></select></td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td ><div id="qualify"></div></td><!-- added div in td to show message it can be outside of your table !-->
<td> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
process-loan.php
<?php
if(isset($_POST["custQual"])){
// include 'includes/session.php';
// include 'includes/db_connection.php';
$amt = $_POST["custQual"];//here use $_POST not $_GET
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if($amt !== NULL){
$sum=100000;//static value for demo
if($sum >= $amt){
//qualify for loan $ enable the Process Button to save
$res["status"]=0;
$res["msg"]="You are Qualify to Apply";
}else{
//disqualify for loan $ disable the process button until condition is meant.
$res["status"]=1;
$res["msg"]= "Insufficient Fund: Unqualify to Apply";
}//end if condition
}else{
$res["status"]=1;
$res["msg"]= "put some amount first";
}
echo json_encode($res);
}

multiple submit on same page with php ajax

<div id="home">
<div class="container">
<form action="" method="post">
<b><font color = "000099"><select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select></font></b>
<b><font color = "000099"><select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select></b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /> </b>
<input type="submit" value="GO"/></font><br>
</form>
<font color = "339933"><b>
</b></font>
<p><div id="body">
<table width="98%" border="1">
<tr></tr>
<tr>
<td><font color = "339933"><b>Name</td>
<td><font color = "339933"><b>E-Mail </td>
<td><font color = "339933"><b>Access</td>
<td><font color = "339933"><b>Update </td>
</tr>
<?php
$read = $_POST['read'];
If($read == 'New'){
$read = '0';
}
If($read == 'Archive'){
$read = '1';
$arc = 'AND date < CURDATE() - INTERVAL 90 DAY';
}
$category = $_POST['category'];
$value = $_POST['value'];
if($category == 'Name'){
$where = " where name like '%$value%' ";
}else if($category == 'E-mail'){
$where = " where Email like '%$value%' ";
}else if($category == 'Employee'){
$where = " where Email like '%$value%' ";
}else if($category == 'Customer'){
$where = " where Email not like '%$value%' ";
}
$select = 'SELECT *';
$from = ' FROM users';
if($where == ''){
$where = ' WHERE TRUE ';
}
$order = " order by id desc limit 100";
if($read == '0'){
$sql = $select . $from . $where . $order ;
}else{
$sql = $select . $from . $where . $arc . $order ;
}
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set)) {
?>
<tr>
<form method="post" name="forms" action="">
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access']; ?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</form>
<?php } ?>
</table>
</div>
</body>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
alert('asfsfsds');
var ID = $(this).attr("id");
var dataString1 = 'msg_id='+ ID;
var mail = $("#remail").val();
var mailid = 'remail='+ mail;
var textcontent = $("#access_rights").val();
var dataString = 'access_rights='+ textcontent;
if(textcontent==''){
alert("Enter some Value..");
$("#access_rights").focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: dataString,mailid,dataString1,
cache: true,
success: function(html){
document.getElementById('access_rights').value='';
$("#access_rights").focus();
}
});
}
return false;
});
});
</script>
</html>
Above is my php ajax code. I want to one field in mysql database by ajax.
There are multiple submit button on the page. Let me explain you properly.
Below code is used for sorting the value on the page. This value retrieve from database. This is working fine. I can get the data from database and it is showing in the same page.
<form action="" method="post">
<b><font color = "000099">
<select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select>
</font></b>
<b><font color = "000099">
<select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select>
</b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /></b>
<input type="submit" value="GO"/></font><br>
</form>
In below code data is showing from database and one text box and submit button will display in table.
<form method="post" name="forms" action="">
<tr>
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access'];?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</tr>
</form>
I want user with special permission can update the value by ajax because there could be multiple rows and it is not good to page get refreshed each time.
At the moment after clicking on update button ajax event not firing.
Can anybody advise me on this. I am not good in ajax.
There may be other issues, but the following line is syntactically incorrect:
data: dataString,mailid,dataString1,
That is not how you concatenate a string in Javascript. Plus, you would need to separate the name=value pairs with ampersands.
Instead of concatenating a string, you can use an object and let JQuery do the concatenating:
data: {
'access_rights': $("#access_rights").val(),
'remail': $("#remail").val(),
'msg_id': $(this).attr("id")
},
UPDATE:
You don't have an element with id="access_rights. You do have an element with id="remail", but you create that element in a loop, so you will have multiple elements with that id.
You need to get the values of the elements that are in the same row as the clicked submit button. You can't do that using id values. Instead, you use .closest('tr') on the button element to get the surrounding row. You can then use .find() on the row element to get the values in that row.
Change:
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
To:
<td><font color="Black" class="remail"><?php echo $row['Email']; ?></td>
Then you can have:
$(".submit_button").click(function() {
var $submitBtn = $(this),
$row = $(this).closest('tr'),
$accessRights = $row.find("input[name=access_rights]"),
accessRights = $accessRights.val();
if (accessRights == ''){
alert("Enter some Value..");
$accessRights.focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: {
'access_rights': accessRights,
'remail': $row.find(".remail").text(),
'msg_id': $submitBtn.attr("id")
},
cache: true,
success: function(html){
$accessRights.val('').focus();
}
});
}
return false;
});
You are also missing the closing </tr> tag.

Getting Array Value from Checkbox in PHP

I am trying to build a list where user can select any checkbox and it can send all select values for the row to the next page.
Here is what I have:
first page:
<table border="0">
<tr>
<td>Check All | Uncheck All</td>
<td>Item Name</td>
<td>Item Description</td>
</tr>
<?php
if ($num_rows == 0) {
return "No Data Found";
}else{
while ($row = dbFetchAssoc($result)) {
$item_id = $row['item_id'];
$item_name = $row['item_name'];
$item_desc = $row['item_desc'];
$item_qty = $row['item_qty'];
$item_upc = $row['item_upc'];
$item_price = $row['item_price'];
$vendor_id = $row['vendor_id'];
?>
<tr>
<td> <input type="checkbox" name="area[]" value="<?=$item_id?>" /></td>
<td><input type="text" name="item_name[]" value="<?=$item_name?>"></td>
<td><input type="text" name="item_desc[]" value="<?=$item_desc?>"></td>
</tr>
<?php
}
}
?>
<tr><td colspan="3"><input type="submit"></td></tr>
</table>
</form>
Next Page:
<table>
<tr><td colspan="3"><?php "Total Item(s) selected: "; echo count($_POST['area']); ?></td></tr>
<?php
if(!empty($_POST['area'])) {
foreach($_POST['area'] as $check) {
echo "<tr><td>".$check."</td><td>".$_POST['item_name']."</td><td>".$_POST['item_name']."</td></tr>";
}
}
?>
</table>
I need to read the item_name and item_desc value as well. How do I get it?
You need the key:
if(!empty($_POST['area'])) {
foreach($_POST['area'] as $key => $check) {
echo "<tr><td>".$check."</td><td>".$_POST['item_name'][$key]."</td><td>".$_POST['item_desc'][$key]."</td></tr>";
}
}
As Marc said in his answer it would probably be better to set key's in your loop creating the input.
<?php
if ($num_rows == 0) {
return "No Data Found";
}else{
$counter = 0;
while ($row = dbFetchAssoc($result)) {
$counter++;
$item_id = $row['item_id'];
$item_name = $row['item_name'];
$item_desc = $row['item_desc'];
$item_qty = $row['item_qty'];
$item_upc = $row['item_upc'];
$item_price = $row['item_price'];
$vendor_id = $row['vendor_id'];
?>
<tr>
<td> <input type="checkbox" name="area[<?=$counter?>]" value="<?=$item_id?>" /></td>
<td><input type="text" name="item_name[<?=$counter?>]" value="<?=$item_name?>"></td>
<td><input type="text" name="item_desc[<?=$counter?>]" value="<?=$item_desc?>"></td>
</tr>
<?php
}
}
?>
foreach($_POST['area'] as $key => $check) {
echo $check . $_POST['item_name'][$key];
}
assuming that there's an exact 1:1 correspondence between your three submitted arrays. Remember that checkboxes which are NOT checked do NOT get submitted with the form, so this is most likely NOT true and this code will not work as written.

Using PHP and Javascript in onblur function

so I have this form:
<form enctype="multipart/form-data" action="cgi-bin/upload.cgi?upload_id=" method="post" onSubmit="return StartUpload(this);" target="xupload">
<table>
<tr>
<td class="first"><span class="right">Upload File: </span></td>
<td class="second"><input name="file_1" type="file" onChange="checkExt(this.value)" accept=".mp4, .avi, .wmv, .mov, .camrec, .flv, .zip, .rar"></td>
<td class="third"><span class="left">(required)</span></td>
</tr>
<tr></tr>
<tr><center><h2>Video Information</h2></center></tr>
<tr></tr>
<tr>
<td class="first"><span class="right">Your Name: </span></td>
<td class="second"><input type="text" name="name"></td>
<td class="third"><span class="left">(preferred)</span></td>
</tr>
<tr>
<td class="first"><span class="right">Series ID: </span></td>
<td class="second"><input id="series_id" type="text" name="series_id" placeholder="You should have been given this by your admin"></td>
<td class="third"><span class="left">(preferred)</span></td>
</tr>
<tr>
<td class="first"></td>
<td class="second"><span id="series_id_check">Enter You're series ID Above and this will change</span></td>
<td class="third"></td>
</tr>
<tr>
<td class="first"><span class="right">Title: </span></td>
<td class="second"><input type="text" name="title"></td>
<td class="third"><span class="left">(preferred)</span></td>
</tr>
<tr>
<td class="first"></td>
<td class="second center"><small>Please use "<span style="color:#9c0000"><br></span>" to make a new line</small></td>
<td class="third"></td>
</tr>
<tr>
<td class="first"><span class="right">Description: </span></td>
<td class="second"><textarea name="desc"></textarea></td>
<td class="third"><span class="left">(preferred)</span></td>
</tr>
<tr>
<td class="first"><span class="right">Guests: </span></td>
<td class="second"><input type="text" name="guests"></td>
<td class="third"><span class="left">(optional)</span></td>
</tr>
<tr>
<td class="first"><span class="right">Additional Tags: </span></td>
<td class="second"><input type="text" name="tags"></td>
<td class="third"><span class="left">(comma separated - optional)</span></td>
</tr>
</table>
<input type="submit" name="submit" value="Upload File">
</form>
Which I use to upload videos to my web hosting server. I want to be able to change the text in the series_id_check span with some javascript that uses PHP arrays... Here's the PHP that I use for populating the arrays from mysql (I KNOW THAT ITS DEPRECIATED BUT FOR MY WEB HOSTING PHP 5.3 IS INSTALLED AND ITS ONLY DEPRECIATED FROM 5.4):
$sql1 = mysql_fetch_assoc(mysql_query("SELECT COUNT cnt FROM series"));
$count = $sql1['cnt'];
$gamearray = array($count - 1);
$namearray = array($count - 1);
$idarray = array($count - 1);
for ($i = 0; $i < $count; $i++)
{
$sql2 = mysql_fetch_assoc(mysql_query("SELECT id,game,name FROM series WHERE id='{$i}'"));
$gamearray[$i] = $sql2['game'];
$namearray[$i] = $sql2['name'];
$idarray[$i] = $sql2['id'];
}
I know it connects to the database fine as I've got a die statement when it tries to connect
The javascript is:
var id = "series_id";
document.getElementById("series_id").onblur = function()
{
var value = document.getElementById(id).value;
var gameArray = new Array(<? echo implode(',', $gamearray); ?>;
var nameArray = new Array(<? echo implode(',', $namearray); ?>;
var idArray = new Array(<? echo implode(',', $idarray); ?>;
if (inArray(value,idArray)
{
var id = parceInt(value);
var game = gameArray.indexOf(id);
var name = nameArray.indexOf(id);
var input= "You've inputted the id for the game: " + game + " for the series: " + name;
document.getElementById("spawn_series_id_check").innerHTML = input;
}
});
function inArray(var input, var array)
{
var count = array.length;
var returnVal = false;
for (var i = 0; i < count; i++)
{
if (array[i] == input)
{
returnVal = true;
}
}
return returnVal;
}
Basically the text in the series_id_check doesn't change. Could you tell me how to fix it
You should consider using JSON to handle these data.
$result = mysql_query("SELECT id,game,name FROM series");
$count = count($result);
$series = array();
while ($row = mysql_fetch_assoc($result)) {
$series[$row['id']] = array('game' => $row['game'], 'name' => $row['name']);
}
And at your JS:
document.getElementById("series_id").onblur = function()
{
var series = '<?php echo json_encode($series); ?>';
var id = parseInt(this.value, 10);
if (undefined !== series[id])
{
var game = series[id]['game'];
var name = series[id]['name'];
var message = "You've inputted the id for the game: " + game + " for the series: " + name;
document.getElementById("spawn_series_id_check").innerHTML = message;
}
});
I haven't tested the code, but this is the way you should go.
Your javascript arrays are incomplete, and will come out like this:
var gameArray = new Array(-1;
try rewriting the array building part of you code to do this for each array:
var gameArray = new Array(<? echo implode(',', $gamearray); ?>);
Notice that the javascript array and line has been closed.
added fix
if (inArray(value,idArray)
{
should be
if (inArray(value,idArray))
{
And another - try changing
function inArray(var input, var array)
{
to
function inArray(input, array)
{
Also - cannot set property of null likley means an issue with the anonymous function.
The second line of your function var value = document.getElementById(id).value
needs to end with a semicolon var value = document.getElementById(id).value;

Categories