Link to home
Create AccountLog in
HTML

HTML

--

Questions

--

Followers

Top Experts

Avatar of Suneet Pant
Suneet Pant🇮🇳

how on clicking a button content of each row of html table be updated in database table using ajax jquery in php
Hi Chris please help me with the code as things are not coming in my mind how to do it. Lets say database table name is "cart", I want data should be updated onto this table ie. "cart". When a user click on button image, data should be updated on the basis of first hidden column "id". Below is the image of the table Rest of the code is same as above. Please help
User generated image
<?php session_start(); ?>
<?php
include ("dbcon.php");
?>
<!DOCTYPE html>
<html>
 <head>
  <script type="text/javascript">
   $(document).ready(function() {
    $("select[name='ratelist']").change(function() {
     var cost = $("option:selected", this).data('cost');
     var currentRow = $(this).parents('tr'); // get the <tr> that contains the changed <select>
     $("input[name='i-cost']", currentRow).val(cost); // set the value of 'i-cost' in the currentRow only
    });
   });
  </script>
 </head>
<body>
  <div class="hdr-div">
    <div class="btnupdt">	<!-- Update all records back to database -->
      <a href="#"><img src="images/btnupdtcart.jpg" alt="" class="shw_updtbtn" /></a>
  </div>				

  <div class="disp_recs">
    <?php
        $var = 'rahul@xys.com';
	$query = "SELECT user_id FROM user_dtls where u_emailid = '{$var}'";
	$retrv = mysqli_query($connection, $query);
	$retrvarr = mysqli_fetch_array($retrv);
	if (!$retrvarr)
	{ die("Database Query failed." . mysqli_error($connection)); }
	else {$getid = $retrvarr[0];}

	//get details based on id
	$pickrecs = "SELECT t_ordid, DATE_FORMAT(tord_dt,'%d-%m-%Y') as label_date, file_path, file_name FROM utmp_orders where user_id = '{$getid}'";
	$result = mysqli_query($connection, $pickrecs); ?>
        <table id='display'>
          <thead>
	    <tr>
		<th>Labels</th>
		<th>Creation&nbsp;Date</th>
		<th>Total&nbsp;Price (&nbsp;&pound;&nbsp;)</th>
		<th></th>
            </tr>
	  </thead>
	  <?php while($resultarr = mysqli_fetch_assoc($result)){ ?>
	  <tbody>
	    <tr>
		<!--<td style="display:none;"><?php //echo $resultarr["t_ordid"] ?></td>-->
		<td><?php echo $resultarr["t_ordid"] ?></td>
		<td><?php echo $resultarr["label_date"] ?></td>
		<td><?php
		$pickrecs = "SELECT rt_qty, rt_cost FROM rate_mast order by rt_qty";
		$rtlist = mysqli_query($connection, $pickrecs); 
		echo "<select name='ratelist' value='' class='rdd'>";
		while($rtlistarr = mysqli_fetch_assoc($rtlist)){ 
		  echo "<option value = $rtlistarr[rt_qty] data-cost='" . $rtlistarr[rt_cost] . "'>$rtlistarr[rt_qty]</option>";
		}
		echo "</select>";
		?></td>
		<td><input type="text" name="i-cost" value="5.95" readonly class="icost"></td>
	    </tr>
            <?php } ?>
         </table>
	 <?php 
	   mysqli_free_result($retrv);
	   mysqli_free_result($result);
	 ?>
      </div>
   </body>
</html>
<?php
	mysqli_close($connection);
?>

Open in new window

HELP.JPG

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


ASKER CERTIFIED SOLUTION
Avatar of Chris StanyonChris Stanyon🇬🇧

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

Sorry for that. I will remember this.

Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

It means that this jQuery will call data.php to update the database table row by row.

Avatar of Chris StanyonChris Stanyon🇬🇧

Yeah, that's right.

The jQuery will loop through each TR in your HTML page and build an array of the data, containing the IDs and Values for each row. It then POSTs that data to a server-side PHP script (called data.php in my example). That script will then need to loop through the POSTed data, and call an UPDATE statement for each record it finds.

The preferred way to code your PHP script is to use PDO - this is a PHP extension that makes working with databases much easier and more secure. Once you've got the jQuery bit working, I can walk you through the PHP part if needed.

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

in data.php , What do I need to mention in the code shown below in bold numbers ' 1 ' and ' 2 '
<?php
  include ("dbcon.php");
  foreach ($_POST['records'] as $record) {
// update your database, one record at a time:
// for example: "UPDATE yourTable SET someColumn = {$record['value']} WHERE yourID = {$record['id']}"
   $query="update utmp_orders set lbl_qty =' [b]1[/b] ' , lbl_prc=' [b]2[/b] ' where t_ordid = {$record['id']}";
   $result = mysqli_query($connection, $query); 
   if (!$result)
   { die("Selected Record Deletion Failed." . mysqli_error($connection)); }
   echo $record['id'] . "|" . $record['value'] . PHP_EOL;
  }
?>
<?php
  mysqli_free_result($result);
  mysqli_close($connection);
?>

Open in new window


Avatar of Chris StanyonChris Stanyon🇬🇧

You need to build the data in your jQuery script, so whatever you need in your PHP script, you'll need to pass through from your jQuery. If you want Qty, Price and ID, then you'll need to get the correct info. Something like this:

var id =  $("td:nth-child(1)", this).text(); //get the ID from the 1st TD of the current row
var qty = $("select[name='ratelist']", this).val(); // get the qty from the value of the <select>
var price = $("select[name='ratelist'] :selected", this).data("cost"); // get the price from the data-cost attribute of the <select>
// add the id, qty and price to the data array
data[data.length] = {id: id, qty: qty, price: price};

Open in new window


Now in your PHP, your update statement will look something like this:

$query="UPDATE utmp_orders SET lbl_qty = {$record['qty']}, lbl_prc = {$record['price']} WHERE t_ordid = {$record['id']}";

Open in new window


Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

In this statement "$('.btnupdt a').click(function(e)",  is .btnupdt an image button or input type submit button.

B'cause I have taken an Image Button
<div class="btnupdt">	
    <a href="#"><img src="images/btnupdtcart.jpg" alt="" class="shw_updtbtn" /></a> 
</div>				

Open in new window


Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Chris StanyonChris Stanyon🇬🇧

The HTML you've just posted is neither an image button or an input type submit button - it's simply an Anchor <a> containing an image, all wrapped up in a div with a class of btnupdt

$('.btnupdt a').click()

This jQuery will bind the click() event to an <a> element that's contained in an element with a class of btnupdt, which is exactly what your HTML shows.

Avatar of Chris StanyonChris Stanyon🇬🇧

FYI, this is the code for an Image button:

<input type="image" src="images/someImage.jpg" alt="Submit">

Open in new window


And this is the code for a Submit button

<input type="submit" value="Submit">

Open in new window


And of course, you have the standard button:

 <button type="button">Click Me!</button> 

Open in new window


Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

oh ok ok now i remember. sorry for giving you trouble. And thanks once again

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

But html5 doesnot support input type="image". I have just checked that.
How can it be used with :

<a href="#"><img src="images/btnupdtcart.jpg" alt="" class="shw_updtbtn" /></a>

Avatar of Chris StanyonChris Stanyon🇬🇧

HTML5 does support the <input type="image">

Where did you check?? I think your information is wrong.

Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

No I am not wrong. You can check the following links :
Link 1
Link 2

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Chris StanyonChris Stanyon🇬🇧

Sorry, but you are wrong. The first link shows the new INPUT types that have been added to HTML5. These are in addition to the ones that already exist in HTML4. The second link you posted clearly shows the image type. Those tagged with the little '5' icon are again those that are new to HTML5. Those not tagged with the little '5' icon still exist.

Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

Image button is not responding. Pls check my code may be there is something wrong in the code :
<div class="btnupdt">	
	<input type="image" id="btnupdt" src="images/btnupdtcart.jpg" alt="Submit">
</div>

Open in new window


CSS
 .btnupdt{ margin-left:48%; float:left; width: 17%; height: 38px 

Open in new window


Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

Pls reply

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Chris StanyonChris Stanyon🇬🇧

Hey Suneet,

If you've  changed the <a> tag to use an input button instead then you'll also need to change your jQuery selector. You've given your input button an ID (btnupdt) so you can just use that to bind the click() event to:

$('#btnupdt').click(function(e) {
   ...
}

Open in new window


Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

Thanks for replying. It's still very confusing for me. Can you please send the working code for the query you have given to me for updating records. The change that you have seen was done just for testing. Otherwise what I have with me is not working at all. I would be very obliged if you can do this for me. Or if you say I can send to you full code to review.

Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

Please reply I have only one day left . Below is my code, which is not working :
<?php session_start(); ?>
<?php
   include ("dbcon.php");
?>
<!DOCTYPE html>
<html>
 <head>
  <title></title>
  <script type="text/javascript">
    $(document).ready(function() {
       $('.btnupdt a').click(function(e){
          e.preventDefault(); // prevent the A target from being followed
          var data = new Array(); // prepare some data storage
          $('table#display tr').each(function() {
             var id =  $("td:nth-child(1)", this).text(); 
             var qty = $("select[name='ratelist']", this).val(); 
             var price = $("select[name='ratelist'] :selected", this).data("cost"); 
             data[data.length] = {id: id, qty: qty, price: price}
          });
          $.ajax({
            type: 'POST',
            url: 'updtdata.php',
            data: { records: data }
          })
          .done( function(data) {
            console.log(data);
          })
          .fail( function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus);
          });
       });
    });
  </script>
  </head>
  <body>
   <div class="btns">
     <div class="btnupdt">	<!-- Update all records back to database -->
        <a href="#"><img src="images/btnupdtcart.jpg" alt="" class="shw_updtbtn" /></a>
     </div>				
   </div>
   <div class="disp_recs">
    <?php
     ........
     ........
     ........
     ........
    <?php } ?>
    <?php 
      mysqli_free_result($retrv);
      mysqli_free_result($result);
    ?>
  </div>
 </body>
</html>
<?php mysqli_close($connection); ?>

Open in new window


From the code above :
<div class="btnupdt">      <!-- Update all records back to database -->
      <a href="#"><img src="images/btnupdtcart.jpg" alt="" class="shw_updtbtn" /></a>
 </div>

CSS
.btnupdt{ margin-left:48%; float:left; width: 17%; height: 38px }

.shw_imgbtn{ width: 100%; height: 38px; }

Open in new window


Please help....

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Chris StanyonChris Stanyon🇬🇧

Hey Suneet,

I'll do what I can, but as we're all volunteers here, we can't always respond immediately. Not only do we have full-time jobs, we may also be in different time-zones (not to mention, it's the weekend!!)

As I think I mentioned earlier, there are several parts to getting this working. You indicated that the database update isn't working, but then you've posted the jQuery part - this won't update the database - it will just send the data to your PHP script, which will then do the database update.

Here's a PHP script that will update your database for you, based on PHPs PDO extension. For this to work, you'll need to make sure your jQuery is sending the data to the server correctly:

<?php 
// Turn on error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
 
// Set your connection details
$hostname = 'localhost';
$username = 'yourUserName';
$password = 'yourPassword';
$database = "yourDatabase";

try {
	
	// Connect to your database
	$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
	$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

	// Prepare a parameterised UPDATE statement and bind the parameters to variables
	$stmt = $dbh->prepare("UPDATE utmp_orders SET lbl_qty = :qty, lbl_prc = :price WHERE t_ordid = :id");
	$stmt->bindParam(':id', $id);
	$stmt->bindParam(':price', $price);
	$stmt->bindParam(':qty', $qty);
	
	// Intialise a record tracker
	$recordsUpdated = 0;

	// Loop through the POSTed data
	foreach ($_POST['records'] as $record) {
		//Execute the prepared UPDATE statement
		$stmt->execute($record);
		
		// Update the record tracker
		$recordsUpdated++;
	}
	
	// Output a summary to the user
	printf("Records Updated: %d", $recordsUpdated);

} catch(PDOException $pdoEx) {
	// We have a problem
	die($pdoEx->getMessage());
}

Open in new window


When your jQuery script POSTs data to this script, if everything worked, your database will be updated and your jQuery script will receive the 'Records Updated' message back in the 'data' variable. You can then display that to the user.

Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

so sorry for troubling you. I would better be careful next time

Avatar of Chris StanyonChris Stanyon🇬🇧

No worries Suneet. It's no trouble. Just trying to explain how to get the best out of EE. We're always happy to help so keep asking questions - it's the best way to learn :)

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

Thank you very much for replying. Thanks for the code but  I don't have any idea about using PDO so I am continuing with MySqli. After examining the code using console.log I found data is not transfering to the "data.php" file. Pls see the image attach :
User generated image

Avatar of Chris StanyonChris Stanyon🇬🇧

OK. Can you post your HTML file that contains the jQuery. Post it in full, along with your cart.php file. If you have this running on a webserver, also post a link to that so I can test it 'live'. I can't get any relevant information from the image you posted.

We'll get there :)

Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

cart.php itself has <html>....</html> in it. All the data is coming directly from the table
<?php session_start(); ?>
<?php
   include ("dbcon.php");
?>
<!DOCTYPE html>
<html>
 <head>
  <title></title>
  <link rel="stylesheet" type="text/css" href="css/dsgncnv.css">
  <script type="text/javascript">
    $(document).ready(function() {
	
		$("select[name='ratelist']").change(function() {
			var cost = $("option:selected", this).data('cost');
			var currentRow = $(this).parents('tr'); // get the <tr> that contains the changed <select>
			$("input[name='i-cost']", currentRow).val(cost); // set the value of 'i-cost' in the currentRow only
		});
	
       $('.btnupdt a').click(function(e){
          e.preventDefault(); // prevent the A target from being followed
          var data = new Array(); // prepare some data storage
          $('table#display tr').each(function() {
             var id =  $("td:nth-child(1)", this).text(); 
             var qty = $("select[name='ratelist']", this).val(); 
             var price = $("select[name='ratelist'] :selected", this).data("cost"); 
             data[data.length] = {id: id, qty: qty, price: price}
          });
          $.ajax({
            type: 'POST',
            url: 'data.php',
            data: { records: data }
          })
          .done( function(data) {
            console.log(data);
          })
          .fail( function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus);
          });
       });
    });
  </script>
  </head>
  <body>
   <div class="btns">
     <div class="btnupdt">	<!-- Update all records back to database -->
       <a href="#"><input type="image" src="images/btnupdtcart.jpg" alt="Submit" class="shw_updtbtn" /></a>
     </div>				
   </div>
   <div class="disp_recs">
    <?php
      $var = 'rahul@xys.com';
      $query = "SELECT user_id FROM user_dtls where u_emailid = '{$var}'";
      $retrv = mysqli_query($connection, $query);
      $retrvarr = mysqli_fetch_array($retrv);
      if (!$retrvarr)
      { die("Database Query failed." . mysqli_error($connection)); }
      else {$getid = $retrvarr[0];}

     //get details based on id
     $pickrecs = "SELECT t_ordid, tord_dt FROM utmp_orders where user_id = '{$getid}'";
     $result = mysqli_query($connection, $pickrecs); 
	?>
    <table id='display'>
       <thead>
           <tr>
              <th>Creation&nbsp;Date</th>
              <th>Labels</th>
              <th>Total&nbsp;Price (&nbsp;&pound;&nbsp;)</th>
           </tr>
	   </thead>
        <?php while($resultarr = mysqli_fetch_assoc($result)){ ?>
            <tbody>
              <tr>
                <td style="display:none;"><?php echo $resultarr["t_ordid"] ?></td>
                <td><?php echo $resultarr["t_ordid"] ?></td>
                <td><?php
                  $pickrecs = "SELECT rt_qty, rt_cost FROM rate_mast order by rt_qty";
                  $rtlist = mysqli_query($connection, $pickrecs); 
                  echo "<select name='ratelist' value='' class='rdd'>";
                  while($rtlistarr = mysqli_fetch_assoc($rtlist)){ 
                    echo "<option value = $rtlistarr[rt_qty] data-cost='" . $rtlistarr[rt_cost] . "'>$rtlistarr[rt_qty]</option>";
                  }
                  echo "</select>";
                ?></td>
                <td><input type="text" name="i-cost" value="5.95" readonly class="icost"></td>
                <td><a href="#" class="delete" style="color:#FF0000;"><img src="images\cartidel.jpg" alt="" style="width:24px; height:24px"</a></td>					
			  </tr>
			</tbody>
		<?php } ?>
	</table>
	<?php 
		mysqli_free_result($retrv);
		mysqli_free_result($result);
	?>
   </div>
  </body>
</html>
<?php
	mysqli_close($connection);
?>

Open in new window


data.php
<?php
	include ("dbcon.php");
	foreach ($_POST['records'] as $record) {
		// update your database, one record at a time:
		$query="UPDATE utmp_orders SET lbl_qty = {$record['qty']}, lbl_prc = '{$record['price']}' WHERE t_ordid = {$record['id']}";
		$result = mysqli_query($connection, $query); 
		if (!$result)
			{ die("Selected Record Updation Failed." . mysqli_error($connection)); }
		//echo $record['id'] . "|" . $record['value'] . PHP_EOL;
	}
?>
<?php
	mysqli_free_result($result);
	mysqli_close($connection);
?>

Open in new window


Sorry this site is not uploaded on the server yet.
Updated Image :
User generated imageThis error comes when Update Cart is clicked.

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


SOLUTION
Avatar of Chris StanyonChris Stanyon🇬🇧

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.

Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

Thank you very much for all this. And really very sorry for disturbing you again and again.

Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

I am from India and just because of shortage of time I am in touch of you. right now here the time is  3:50 AM. Thank you once again.

Avatar of Member_2_248744Member_2_248744🇺🇸

greetings Suneet Pant, , I looked at all of the comments and code here, and you seem to be having problems. To me , you started out with some PHP and HTML for the <table> rows that were NOT good for the task that you want to do, You need to get three Things back to the sever by ajax, the total price, the quantity, and the Row number (ID). You put these all over the place in a table row, You can easily place ALL three in the select box Option value like -
echo "<option value='".$resultarr['t_ordid']."_".$rtlistarr['rt_qty']."_".$rtlistarr['rt_cost']."' >".$rtlistarr['rt_qty']."</option>";

Open in new window

and get all three in ONE operation for the select value -
$("#selt1").val();

Please look at this next code, I ran it on my server, and it works.
this is your cart.php -
<?php ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
include ("dbcon.php");
?>
<!DOCTYPE html>
<html><head><title>Data AJAX</title>
<style>
body {background:#e3f7ff;
  }
.shw_updtbtn {width:106px; 
  height: 31px; 
  margin-bottom: 5px;
  margin-left: 9em;
  cursor: pointer;
  }
.dx, .px{width: 18px; 
  height:18px; 
  color: #fff; 
  background:#a00; 
  border-radius: 9px; 
  margin: 2px auto; 
  font-family:sans-serif; 
  font-weight: bold;
  text-align: center;
  cursor: pointer;
  }
#dis {background: #eee; border:1px solid #000;}
#dis th {background:#666; color: #eee; padding:1px 5px;}
#dis td {text-align: center;}
.contin {position: relative;}
.pop {position: absolute; top: 2px; left: 2px; width:21em; background:#dfd; border:3px solid #090; display: none;}
.px {margin: 1px auto;}
#title {font-weight: bold; margin-bottom: 5px; padding: 2px; text-align: center; text-size: 120%;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>/* <![CDATA[ */
$(document).ready(function() {
	
$("select[name='ratelist']").change(function() {
	var id = $(this).prop("id");
	var cost = $(this).val();
	cost = cost.split("_");
	$("#in"+id).html(cost[2]);
    });

$('#updateBut').click(function(e){
var ajxOptions = {
    url: "ajaxpost.php",
    type: "POST",
    dataType: "text",
    timeout: 3500}

$("#display").css( "background-color", "#eee" );
var val = [];
$('#orders tr').each(function() {
	val[val.length] = $("#sel"+$(this).prop("id")).val();
    });
  // add the val array to the POST send data string
ajxOptions.data = {vals: val};

// get the Jquery AJAX in aj with $.ajax( )
  var aj = $.ajax(ajxOptions);
        
// the aj.done( ) method is the successful return of AJAX
  aj.done(function( received ) {
  if (received.charAt(0) == '~') { // the received server had no errors
  $('#title').html("Update Sucess for Order");
  var rAry = received.split("^");
  $('#sho').html("Updates for Quantity and Total Price were "+rAry[1]);
  $('#ajaxPop').show();
  $("#display").css( "background-color", "green" );
  }
    $('#ajaxRe').html(received);
	});
	
// the aj.fail( ) method is the UNsuccessful (error) return of AJAX	
  aj.fail(function(xhr, error1, err) {
// xhr is the XMLHttpRequest Object
// error1 is the Jquery guess at what the error was
// err is the reason for jquery ERROR
  if (xhr.status==404) alert("ERROR from Ajax as '404 status' the "+ajxOptions.url+
  " page was NOT on Server, \nCan NOT recover from this ERROR, This operation is NOT available!");
  else {
    alert("Ajax ERROR = \""+error1+"\", with server Status: "+xhr.status+", post-URL: "+ajxOptions.url+
	", \npost-Data: "+ajxOptions.data+", \nerror because: "+err);
    if (aj.responseText) {
    $('#ajaxRe').html(aj.responseText); 
    }else $('#ajaxRe').html("Ajax Received Text is empty");
  }
  });
});// $('#updateBut').click

$('.dx').click(function(e){
alert("this button does Nothing here");
});

$('#xx').click(function(e){
$('#ajaxPop').hide();
});

});// $(document).ready

/* ]]> */</script></head>
<body>
<img id="updateBut" src="images/btnupdtcart.jpg" alt="click me" class="shw_updtbtn" />
<div class="contin">
<?php
$var = 'a1@go.com';
$query = "SELECT user_id FROM user_dtls where u_emailid = '{$var}'";
$retrv = mysqli_query($connection, $query);
$retrvarr = mysqli_fetch_array($retrv);
if (!$retrvarr) die("Database Query failed.".mysqli_error($connection)); 
$pickrecs = "SELECT t_ordid, DATE_FORMAT(tord_dt,'%d-%m-%Y') as label_date FROM utmp_orders where user_id = '{$retrvarr[0]}'";
$result = mysqli_query($connection, $pickrecs); ?>
<table id='dis'><thead>
  <tr>
    <th>Creation&nbsp;Date</th>
    <th>select Quantity</th>
    <th>Total Price (&nbsp;&pound;&nbsp;)</th>
    <th>delete row</th>
  </tr></thead><tbody id="orders"> 
<?php $tracNum = 0;
while($resultarr = mysqli_fetch_assoc($result)){ ?>
  <tr id="t<?php echo $tracNum ?>" data-oid="<?php echo $resultarr["t_ordid"] ?>">
    <td><?php echo $resultarr["label_date"] ?></td>
    <td><?php
		$pickrecs = "SELECT rt_qty, rt_cost FROM rate_mast order by rt_qty";
		$rtlist = mysqli_query($connection, $pickrecs); 
		echo "<select name='ratelist' id='selt".$tracNum."' class='rdd'>";
		$first ='';
		while($rtlistarr = mysqli_fetch_assoc($rtlist)){ 
		if(!$first) $first = $rtlistarr['rt_cost'];
		  echo "<option value='".$resultarr['t_ordid']."_".$rtlistarr['rt_qty']."_".$rtlistarr['rt_cost']."' >".$rtlistarr['rt_qty']."</option>";
		}
		echo "</select>";
		?></td>
    <td id="inselt<?php echo $tracNum; ?>"><?php echo $first ?></td>
    <td><p class="dx" id="lt<?php echo $tracNum; ?>">X</p></td>
  </tr>
<?php ++$tracNum; } 
mysqli_free_result($retrv);
mysqli_free_result($result);
mysqli_close($connection);
?>
</tbody></table>
<div id="ajaxPop" class="pop"><div id="title">Success from Ajax</div><span id="sho">Show this on success.</span>
<p class="px" id="xx">X</p></div>
</div>
<div id="ajaxRe" style="background: #fee;">Ajax Return shown here</div>
</body></html>

Open in new window

Please Notice that I have reduced your many unneeded elements, I have switched to a more robust element access using ID that are numerically advanced. These can be moved to other row locations in development, without changing the javascript to access them.
You have never, ever used any way to show the user any thing from your Ajax response, I show a success pop out.

next is my PHP for the server ajax -
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Change the Type to text/plain
header('Cache-Control: no-cache');
// In AJAX no page is returned just data as text
header('Content-Type: text/plain');

define("DEBUG", true);

include ("dbcon.php");
$sql = 'UPDATE utmp_orders SET lbl_qty = ? , lbl_prc= ? WHERE t_ordid = ?';
if ($stmt = mysqli_prepare($connection, $sql)) {
  mysqli_stmt_bind_param($stmt, "ssi", $qty, $prc, $id);// bind parameters to variables
$idin = '';
foreach ($_POST['vals'] as $vals) {
  $sets = explode("_", $vals);
  if (count($sets) != 3) exit('Post error number: erc7182');
  list($id, $qty, $prc) = $sets;
  $idin .= $id.',';
  mysqli_stmt_execute($stmt);// send variable data to MySQL
  }

mysqli_stmt_close($stmt);// close statement
} else 
  if (DEBUG) exit(mysqli_error($connection)); 
    else exit('Post error number: erp471');

$idin = substr($idin, 0, -1);
$query = 'SELECT t_ordid, lbl_qty , lbl_prc FROM utmp_orders WHERE t_ordid IN ('.$idin.')';
$re = mysqli_query($connection, $query);
$sendBack = '~<b>SUCCESS!</b><br/>';
while($row = mysqli_fetch_assoc($re)){
$sendBack .= 'New Update Row id='. $row['t_ordid'].' qty= '. $row['lbl_qty'].', prc= '. $row['lbl_prc'].'<br />';	
}
$sendBack .= '^made to rows ID of '.$idin;
echo $sendBack;
/*
$query="delete from utmp_orders where t_ordid ='{$varid}'";
	
$query="update utmp_orders set lbl_qty =' [b]1[/b] ' , lbl_prc=' [b]2[/b] ' where t_ordid = {$record['id']}";
*/
?>
Please notice That I have a slight bit of error control, IT is important when using Database contacts to have some type of error IF you query does NOT WORK.
I use the MySQLI prepare and execute for safety from SQL injections.

Please Run my code to see if it works for you.

Open in new window


Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

Chris Stanyon is the best of all the experts I have encountered. Whatever asked he reply promptly and very efficiently. Thanks to him fore helping me lot.

Avatar of Suneet PantSuneet Pant🇮🇳

ASKER

Hi , One last help :
Pop up box

{ Only one day left }
HTML

HTML

--

Questions

--

Followers

Top Experts

HTML (HyperText Markup Language) is the main markup language for creating web pages and other information to be displayed in a web browser, providing both the structure and content for what is sent from a web server through the use of tags. The current implementation of the HTML specification is HTML5.