AJAX Image Upload from an array [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I need some help with a multiple upload form. I'm using AJAX to upload an image (without a submit button) and display the image after it has loaded. However, my form is repeated multiple times (table rows) so that only the first form works. My php code:
<table class="datatable tablesort selectable paginate full">
<thead>
<tr>
<th>Part</th>
<th>Price</th>
<th>Upload Image</th>
<th>Categories</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Part</th>
<th>Upload Image</th>
<th>Price</th>
<th>Categories</th>
</tr>
</tfoot>
<tbody>
<?php
$breaker_id = $_SESSION['breaker_id'];
$sql = "SELECT * FROM stock where VehicleID='$vehicle' and breaker='$breaker_id'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
?>
<tr id="<?php echo $row['id']; ?>" class="edit_tr">
<td class="edit_td"><span id="first_<?php echo $row['id']; ?>" class="text"><?php echo $row['stock_item']; ?></span><input type="text" value="<?php echo $row['stock_item']; ?>" class="editbox" id="first_input_<?php echo $row['id']; ?>"/></td>
<td class="edit_td"><span id="last_<?php echo $row['id']; ?>" class="text">£<?php echo $row['price']; ?></span><input type="text" value="<?php echo $row['price']; ?>" class="editbox" id="last_input_<?php echo $row['id']; ?>"/></td>
<td>
<div class='preview'>
</div>
<form class="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image
<div class='imageloadstatus' style='display:none'><img src="images/load.gif" alt="Uploading...."/></div>
<div class='imageloadbutton' >
<input type="file" name="photoimg" class="photoimg" />
<input type="text" name="photoimgid" value="<?php echo $row['id']; ?>">
</div>
</form>
<td><?php echo $row['Item_Specifics_Type']; ?> | <?php echo $row['Item_Specifics_SubType']; ?> </td>
</tr><?php } ?>
</tbody>
</table>
And the javascript:
<script type="text/javascript" >
$(document).ready(function() {
$('.photoimg').die('click').live('change', function() {
//$("#preview").html('');
$(".imageform").ajaxForm({target: '.preview',
beforeSubmit:function(){
console.log('v');
$(".imageloadstatus").show();
$(".imageloadbutton").hide();
},
success:function(){
console.log('z');
$(".imageloadstatus").hide();
$(".imageloadbutton").show();
},
error:function(){
console.log('d');
$(".imageloadstatus").hide();
$(".imageloadbutton").show();
} }).submit();
});
});
</script>

You use duplicated id's. Every time you search (in jQuery) e.q. #imageform or #preview it returns the first element that it found with this id!
$("#imageform").ajaxForm({ // Wrong, catch only first #imageform
$(".imageform").ajaxForm({ // Correct, loop over all elements with .imageform class
You have to change it in whole JS code.
-- edit --
Now you run ajaxForm plugin for every .imageform but target is the same in every execution as well as toggled elements in beforeSubmit, success and error functions.
$('.photoimg').die('click').live('change', function () {
var id = $(this).closest('tr').attr('id');
$(this).closest(".imageform").ajaxForm({
target: '#' + id + ' .preview', // type of hack, don't have plugin source ;)
beforeSubmit: function () {
console.log('v');
$(this).find(".imageloadstatus").show();
$(this).find(".imageloadbutton").hide();
},
success: function () {
console.log('z');
$(this).find(".imageloadstatus").hide();
$(this).find(".imageloadbutton").show();
},
error: function () {
console.log('d');
$(this).find(".imageloadstatus").hide();
$(this).find(".imageloadbutton").show();
}
}).submit();
});

Related

Javascript function stops after first while loop in PHP

I have some javascript that creates a datetime picker on each row of a table. The function only works on the first row. I understand that the reason for this is that the datepicker shares the same ID on every row. How can I adjust my code to fix this?
<script type="text/javascript">
$(document).ready(function (){
$('#duedate').datetimepicker({
controlType: 'select',
timeFormat: 'hh:mm tt'
});
});
</script>
<?php $txtJob = $_GET['pickjob']; ?>
<?php
$query2 = "Select Work_Center, Sequence, Est_Total_Hrs from V_schedule WHERE job = '" . $txtJob . "'";
$results2 = sqlsrv_query($connPpp, $query2);?>
<form id="frmpromiseddate" name="frmpromiseddate" action="schedule_job_submit.php" method="POST">
<table class='table table-bordered table-condensed table-striped'>
<tr>
<td>Sequence</td>
<td>Work Center</td>
<td>Due Date</td>
</tr>
<?php while ($row2 = sqlsrv_fetch_array($results2)) {?>
<tr>
<td><?php echo $row2['Sequence']?></td>
<td><?php echo $row2['Work_Center']?></td>
<td><input type="text" name="duedate" id="duedate" value="" /> </td>
</tr>
<?php ;} //End of while ?>
</table>
Jquery treats idas unique identifier and apply on only one element at a time, where as it treats class as a group-identifier and can apply to multiple element at a time so change id to class both in html and Jquery code:-
<td><input type="text" name="duedate" class="duedate" value="" /></td>
And
$('.duedate').datetimepicker({
Use class(.) instead of id(#) for date picker
Javascript code :
$('.duedate').datetimepicker()
HTML code: making id unique
<?php $i=0;
while ($row2 = sqlsrv_fetch_array($results2)) {?>
<tr>
<td><?php echo $row2['Sequence']?></td>
<td><?php echo $row2['Work_Center']?></td>
<td><input type="text" name="duedate" class="duedate" id="duedate_<?php echo $i;?>" value="" /> </td>
</tr>
<?php $i++; } //End of while ?>

Click function showing div elements when not clicked out

I have an admin panel that I am creating. I have a left panel section and then the right side which shows the div when the panel button is clicked. I created a fiddle to show what it looks like and to help me explain this...
https://jsfiddle.net/jq8c51c9/
In the Fiddle it works just like it should, but I took out all of my php. The problem is around the Announcements div, it shows the div for the League Dues under it. Also once you click on announcements and then click on another panel button, if I click on Announcements again the only thing that will show up is this..
Announcements Current Announcements
League Dues
Again this is NOT doing this in the Fiddle.
Here is the full code for the area that the issue resides in. I have been stuck on this forever and cannot figure out why I am having difficulties with only these two divs.
Does anyone see what it is that I am doing wrong?
Announcements
try {
//Prepare
$con = mysqli_connect("localhost", "", "", "");
if ($user_stmt = $con->prepare("SELECT `id` FROM users")) {
$user_stmt->execute();
$user_stmt->bind_result($user_id);
if (!$user_stmt) {
throw new Exception($con->error);
}
$user_stmt->store_result();
$user_result = array();
//while ($user_row = $user_stmt->fetch()) {
?>
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
<textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
</label>
</form>
<?php
if ($announcements_stmt = $con->prepare("SELECT * FROM announcements")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id, $announcements_user_id, $announcements_messages, $announcements_date);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
$announcements_stmt->store_result();
$announcements_result = array();
?>
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
</table>
<?php
}
}
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}
?>
</div>
<div id='dues'>League Dues</div>
</div>
You have an error when building the announcement-table.
The closing </table> tag is inside the while loop, so the html will be screwed up, making everything after the closed table disappear.
So change the while loop to:
....
<?php
while ($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
</table>
<?php
....
Anyway, I recommend to build your html first in a variable and echo it out later alltogether. That makes cleaner code and reduces risk of inconsitency of html tags. When using with HEREDOC you even don't have to bother about quotes.
In your case that could for example look like that:
<?php
$table_head = <<<EOT
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
EOT;
$table_content = "";
while ($row = $stmt->fetch()) {
$table_content.= <<<EOT
<tr>
<td>$announcements_id</td>
<td>$announcements_username</td>
<td>$announcements_messages</td>
<td>$announcements_date</td>
</tr>
EOT;
}
$announcement_table = "<table>".$table_head.$table_content."</table>";
echo $announcement_table;

Add Rows dynamically having unique input id's in td

The code below displays the 10 rows having three columns. the input id's are type_1,type_2,type_3,type_4,type_5 (and same for the rest two columns room_1 to room_5, quantity_1 to quantity_5).
<table id="dgsv_admin" style="width:950px; height:460px;">
<thead>
<tr>
<th>Type</th>
<th>Room</th>
<th>Qty</th>
</tr>
<?php for($i=1;$i<=5;$i++)
{?>
<tr>
<td><input id="type_<?php echo $i ?>" style="width:64px;" class="easyui-validatebox" data-options="required:true" /></td>
<td><input id="room_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" required="true" /></td>
<td><input id="quantity_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" data-options="required:true" /></td>
</tr>
<?php }?>
</thead>
</table>
Now My question is that I have a button ADD 5 ROWS.I want to generate the above rows dynamically each time the button is clicked and at the same time I want to handle the id's of the input like on first click the id's of first column will be type_1 to type_5 and on second click they should be type6 to type_10.
<button class="btn btn-success">ADD 5 ROWS</button>
You shoudl use ajax for such process.
PHP Script:
if( isset($_POST['send_row_request']) )
{
// process the request
$base_id = $_POST['base_id'];
$_SESSION['next_request_base_id'] = $base_id + 5; // setting this for the next request.
// get the data from DB. You have already written the function for you to get
// 5 rows of DB based on a base id give,
$result_array = get_db_data($base_id);
echo json_encode($result_array)
/***
Or if you are not comfortable with JSON you can loop through array and echo them
on each iteration
***/
}
And HERE is the jQuery AJAX :
$(document).ready(function(){
var base_id = $('#base_id').val();
$('myButton').click(function(){
$.ajax({
url : 'url_to_your_php_script',
data : ({send_row_request : 'true', 'base_id' : base_id});
success : function(msg)
{
// do the stuff here and don't forgot to update base_is hidden field on the last record process
}
})
});
});
And here is a simpel HTML. Note that you should save your last row's id of your first five-records into a hidden input with the id of for example #base_id. This value also should be changed on each use click on the button.
<input type='hidden' value='<?php echo $base_id; ?>' id='base_id' />
You can use the php session variable to dynamically create rows among page request:
<?php
session_start();
if(isseet($_POST['your_button_id']))
{
if(isset($_SESSION['row_id']))
$_SESSION['row_id']=$_SESSION['row_id']+1;
else
$_SESSION['row_id']=1;
}
?>
<table id="dgsv_admin" style="width:950px; height:460px;">
<thead>
<tr>
<th>Type</th>
<th>Room</th>
<th>Qty</th>
</tr>
<?php if(isseet($_POST['your_button_id']))
{
$row =$_SESSION['row_id'];
for($i=$row;$i<=$row+4;$i++)
{
?>
<tr>
<td><input id="type_<?php echo $i ?>" style="width:64px;" class="easyui-validatebox" data-options="required:true" /></td>
<td><input id="room_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" required="true" /></td>
<td><input id="quantity_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" data-options="required:true" /></td>
</tr>
<?php } $_SESSION['row_id']=$_SESSION['row_id']+4; } ?>
</thead>
</table>

in php how can i generate dynamic id for each input textbox created in while loop

how to get the selected textbox id generated in while loop for updating the field as in phpmyadmin
<?php
while($fet=mysql_fetch_assoc($sql1))
{
?>
<tr>
<td><input type=text id='hello' name='hello' data-id="<?php echo $fet['username']?>" onchange='loadXMLDoc(this);' value=<?php echo $fet['username']?>>
<td><input type=text id='uid' name='uid' onchange='loadXMLDoc(this).' value=<?php echo $fet['id']?>>
</tr>
<?php
}
?>
Just append i and increment it till your while loop goes on..
<?php
$i=1;
while($fet=mysql_fetch_assoc($sql1))
{
echo '
<tr>
<td>
<input type="text" id="hello'.$i.'" name="hello'.$i.'" data-id="'.$fet['username'].'" onchange="loadXMLDoc(this.value,'.$i.')" value='.$fet['username'].' >
</td>
</tr>';
here write ur code for other fields
$i++;
}
?>
<script>
function loadXMLDoc(a,i)
{ var d= document.getElementById("hello"+i).value; }
</script>
Don't use foreach as bellow way.
foreach($sql1 as $value){
// don't generate html here
}
Because it may brake the html
Use foreach bellow way.
<?php
foreach($sql1 as $value):
?>
<tr>
<td><input type=text id='hello' name='hello' data-id="<?php echo $value['username']?>" onchange='loadXMLDoc(this);' value=<?php echo $value['username']?>>
<td><input type=text id='uid' name='uid' onchange='loadXMLDoc(this).' value=<?php echo $value['id']?>>
</tr>
<?php endforeach() ?>
use the uniqid() function
$str=uniqid("uid") it will make some thing like ti uid1hq7266
and print it in the input

Updating input form after updating a table using jquery or ajax

I have this table i've built with jquery and ajax (watching some tutorials, so i'm not an advanced programmer). Well, what i do is i insert some values in a table and i need to get all the sum of this values in an input form.
I can do that, but what i need is to get the sum without refreshing the page, so anytime i enter:
200 in the Value column, the Sum should become :
Sum + 200
Please i need some help with what to do, i've searched for datagrid, but sincerely i don't know how can i do it.
Thanks
Php code of the input :
<table class="vlera">
<tr id="<?php echo $id; ?>" class="edit_tr">
<td class="edit_td">
<span id="first_<?php echo $id; ?>" class="text"><?php echo $kodi; ?></span>
<input type="text" value="<?php echo $kodi; ?>" class="editbox" id="first_input_<?php echo $id; ?>" />
</td>
<td class="edit_td">
<span id="last1_<?php echo $id; ?>" class="text"><?php echo $pershkrimi_pjeses; ?></span>
<input type="text" value="<?php echo $pershkrimi_pjeses; ?>" class="editbox" id="last_input1_<?php echo $id; ?>"/>
</td>
<td class="edit_td">
<span id="last_<?php echo $id; ?>" class="text"><?php echo $vlera; ?></span>
<input type="text" value="<?php echo $vlera; ?>" class="editbox" id="last_input_<?php echo $id; ?>"/>
</td>
<td class="edit_td">
<span id="last2_<?php echo $id; ?>" class="text"><?php echo $kosto; ?></span>
<input type="text" value="<?php echo $kosto; ?>" class="editbox" id="last_input2_<?php echo $id; ?>"/>
</td>
</tr>
<?php
}
?>
</table>
<?php
$sql_shuma="SELECT SUM(vlera) AS shuma FROM servis_pjeset_perdorura WHERE random=$random";
$resultshuma = odbc_exec($connection, $sql_shuma) or die(odbc_error());
while( $rowshuma = odbc_fetch_array($resultshuma ) ) {
$total1 = $rowshuma['shuma'];
}
?>
<label for='shuma'>Shuma:</label>
<input id="shuma" name="shuma" type="text" value=" <?php echo $total1;?>" size="20" />
the code you posted doesn't really show the full format (what the inputs look like)... but if you do something like:
$(".values").keyup(function() {
var sum = 0;
$(".values").each(function(){
sum += Number($(this).val());
});
$("#shuma").val(sum)
});
and each of your text inputs you want to go towards the total sum has a class of "values" on it, it should work. http://jsfiddle.net/NNbtk/
try this code... This code get the value of the text box when value enter and add it to the sum.
$(document).ready(function(){
$('#shuma').keyup(function(){
var val=$('#shuma').val();
sum=sum+val;
});
});
just put this code inside another php file...say abc.php
<?php
$sql_shuma="SELECT SUM(vlera) AS shuma FROM servis_pjeset_perdorura WHERE random=$random";
$resultshuma = odbc_exec($connection, $sql_shuma) or die(odbc_error());
while( $rowshuma = odbc_fetch_array($resultshuma ) ) {
$total1 = $rowshuma['shuma'];
}
echo $total1;
?>
Then from the main page do the following call on a button lets say button1
$(document).ready({
setInterval(function(){
$.ajax({
url: 'abc.php',
type: "POST",
success: function(contents){
$('#shuma').val(contents);
}
});
}, 1000);
});
Now the explanation:
In the main page when document gets ready, setInterval method of javascript will be called which takes 2 parameters, code and delay time in ms. this code will call the abc.php after every 1 sec and check the db for the new value and return it and put it in the field.
Hope that was what you were looking for.

Categories

Resources