using jquery each method with ajax - php

I'm trying to display a list of players with a edit button next to each one. When edit is pressed, then the user can edit that player. I'm trying to do this using ajax. The problem: The table will display for a split second then it's a blank screen.
<?php foreach($players as $player): ?>
<tr>
<td><?= $player['first_name']; ?></td>
<td><?= $player['last_name']; ?></td>
<td><?= $player['email']; ?></td>
<td align="center" >
<form action="" method="post" id="edit_player">
<input type="hidden" name="user_id" value="<?= player['user_id']; ?>">
<input type="submit" value='Edit' name='submit'>
</form>
</td>
</tr>
<?php endforeach;?>
Here is my jquery/ajax code. I made some changes from earlier. I think it's better, but it's still not working.
$(document).ready(function() {
var contents = $('#teamMain');
$('.edit_player').each(function(index, value) {
var formData = $(this).attr('user_id');
$.ajax({
url: 'views/team_nav.php',
type: 'POST',
cache: false,
data: formData,
success: function(data){
contents.html(data);
}
});
});
});

Related

Deleting a Record from MySQL Using Ajax

There's something wrong with my codes and I'm unable to run it successfully. When I debug my Ajax code using Google Developer tools, Ajax data parameter has the value of the primary key (uid) but it seems it doesn't send POST request to delete.php. I've no idea what the problem is.
Thanks for your helps and suggestions in advance!
index.php: Press Delete Button to Fire Ajax Code
<tbody>
<!--Populate HTML Table-->
<?php if(!empty($records)) {
foreach ($records as $record) {
?>
<tr>
<td data-target="rowNum"></td>
<td data-target="userId" style="display: none;">
<?php echo $record['uid']; ?>
</td>
<td data-target="firstname"><?php echo $record['first_name']; ?></td>
<td data-target="lastname"><?php echo $record['last_name']; ?></td>
<td data-target="emailaddress"><?php echo $record['email_address']; ?></td>
<td>
<button class="btnEdit">Edit</button>
<!--Press Delete Button to Fire Ajax Code-->
<button class="btnDelete">Delete</button>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
Ajax Code: Send userId (Table Primary Key) as Data to Delete.php
$(document).ready(function(){
$(".btnDelete").click(function(){
var userId = $(this).closest("tr").children("td[data-target=userId]").text();
$.ajax({
url: "delete.php",
type: "POST",
data: userId
});
});
});
delete.php:
<?php
include 'database.php';
$conn->query("DELETE FROM Users WHERE uid = '$_POST['userId']'");
?>
You pass your data like this:
$.ajax({
url: "delete.php",
type: "POST",
data: userId
});
userId value is probably just a scalar without key that you're trying to use in delete.php. So change this code to:
$.ajax({
url: "delete.php",
type: "POST",
data: { userId: userId }
});
and it should work.
this might help, you are send data as text.
$(document).ready(function(){
$(".btnDelete").click(function(){
var userId = $(this).closest("tr").children("td[data-target=userId]").text();
$.ajax({
url: "delete.php",
type: "POST",
contentType: 'text/plain'
data: {userId:userId}
});
});
});
You can probably get it to run the way you are trying to but here's a way that makes a bit more sense to me:
<tbody>
<!--Populate HTML Table-->
<?php if(!empty($records)) {
foreach ($records as $record) {
?>
<tr>
<td data-target="rowNum"></td>
<td data-target="firstname"><?php echo $record['first_name']; ?></td>
<td data-target="lastname"><?php echo $record['last_name']; ?></td>
<td data-target="emailaddress"><?php echo $record['email_address']; ?></td>
<td>
<button class="btnEdit">Edit</button>
<!--Press Delete Button to Fire Ajax Code-->
<form class="deleteForm" method="POST">
<input type="hidden" name="userId" value="<?= $record['uid'] ?>" />
<button type="submit" class="btnDelete">Delete</button>
</form>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
Then in JavaScript
$(document).ready(function(){
$(".deleteForm").on('submit', function(){
var data = $(this).serialize(); // Let jQuery prepare the data
$.ajax({
url: "delete.php",
type: "POST",
data: data
});
return false; // Cancel default
});
});
Lastly:
<?php
include 'database.php';
$userId = filter_input(INPUT_POST, 'userId', FILTER_VALIDATE_INT); //Assuming an ID is an int, in general be cautions of SQL injection.
if ($userId) {
$conn->query("DELETE FROM Users WHERE uid = '$_POST['userId']'");
} else {
http_response_code(400); // Missing the input
die();
}
?>

How to send multiple same name input fields value via ajax post method

I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display

multiple select with checkbox in php

i am making a website in which i am to embbed the functionality of delete using multiple checkbox. here is my code. my problem is
1. Ajax call is not working.
2. how can i make search from database for array .
<?php
if(isset($_POST['Delete']))
{
$array=$_POST['check_box'];
}
?>
<form method="post" id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while($selectnumberarr=mysql_fetch_array($selectnumber))
{
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" id="<?php $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}?>
<input type="submit" name="Delete" id="delete">
</table>
</form>
and below is my ajax and javascript code.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
any help would be appriciated
your code is almost correct. You need to remove `onChange="show()" for input checkbox, because if you have jquery then you don't need to put events on HTML elements.
Use jquery 'on' method for compatibility for latest php library.
Replace your jquery code with following jquery code :-
<script>
$(document).ready(function(){
$('#delete').on('click',function()
{
var cat_id = $('.check_box:checked').map(function() {
return this.id;
}).get().join(',');
console.log(cat_id);
$.ajax({
type: "POST",
url: "checkbox.php",
data: { "kw ":cat_id },
datatype:'json',
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
Use ".check_box" instead of "element" in jquery to prevent checks for all checkboxes, instead of desired ones.
Hope it helps.
Why you don't use an array for sending the checkboxes like:
HTML part:
<?php
if (isset($_POST['check_box'])) {
var_dump($_POST['check_box']);
echo "ajax call is working";
}
?>
<form id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while ($selectnumberarr = mysql_fetch_array($selectnumber)) {
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" value="<?php echo $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}
?>
</table>
<input type="button"name="delete" id="delete" value="Delete" />
</form>
JQuery part:
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
So you can easily get an array of the selected checkboxes in php with:
$idsArray = $_POST["check_box"];
this looks now like:
array(
"1", "2","etc.."
);
so this array contains all the ids of the selected checkboxes for delete.

Get the value of text box using jquery

I have the following script :
<script>
$(document).ready(function() {
$('#edit').click(function (){
//get
employee_id = $('#employee_id').val();
alert(employee_id);
html='';
$.ajax({
type: "GET",
url: "<?php echo base_url();?>administrator/admin/get_employee_details/"+employee_id,
dataType: "json",
success: function(response) {
console.log(response);
$( '#fname' ).val(response[0].f_name);
alert(response[0].amount);
$( '#sname' ).val(response[0].l_name);
$( '#lname' ).val(response[0].other_name);
$( '#expiry_date' ).val(response[0].id_no);
$( '#quantity_available').val(response[0].dob)
$( '#gender' ).val(response[0].gender);
$( '#maritalstatus').val(response[0].marital_status)
$( '#sex' ).val(response[0].gender);
},
error: function(data){
}
})
});
});
</script>
The script is supposed pick the employee_id value from the table below :
<tbody>
<?php foreach($employee_details as $employee ):?>
<tr class="odd gradeX">
<td><?php echo $employee['employee_name'];?></td>
<td ><?php echo $employee['id_no'];?></td>
<td><?php echo $employee['dob'];?></td>
<td><?php echo $employee['gender'];?></td>
<td ><?php echo $employee['marital_status'];?></td>
<td><?php echo $employee['phone_no'];?></td>
<td><?php echo $employee['email'];?></td>
<td ><?php echo $employee['date_added'];?></td>
<td><?php echo $employee['residence'];?></td>
<td ><?php echo $employee['next_of_kin_name'];?></td>
<td><?php echo $employee['next_of_kin_relation'];?></td>
<td><?php echo $employee['next_of_kin_phone_no'];?></td>
<td ><?php echo $employee['is_active'];?></td>
<td><?php echo $employee['department_name'];?></td>
<td><?php echo $employee['employee_class'];?></td>
<td><a class="edit" href="#edit_details" id="edit">Edit </a></td>
<td> <a class="delete" href="#delete_details" id="delete" > Delete Employee</a></td>
<input type="text" name="employee_id" id="employee_id" value="<?php echo $employee['employee_id'];?>"/>
</tr>
<?php endforeach;?>
</tbody>
which is a hidden text field (employee_id) in the table when I click the Edit button. But when I click the link , I get an empty result with no employee_id yet I can see the employee id in the text box. How can I get the employee id from the text box for each specific row?
Id of an element must unique, so inside the loop use class instead of id, also move the employee_id field to a td element
<td>
<a class="edit" href="#edit_details">Edit </a>
</td>
<td>
<a class="delete" href="#delete_details" > Delete Employee</a>
<input type="text" name="employee_id" value="<?php echo $employee['employee_id'];?>" />
</td>
then
$(document).ready(function () {
$('.edit').click(function () {
//get
var employee_id = $(this).closest('tr').find('input[name="employee_id"]').val();
alert(employee_id);
html = '';
$.ajax({
type: "GET",
url: "<?php echo base_url();?>administrator/admin/get_employee_details/" + employee_id,
dataType: "json",
success: function (response) {
console.log(response);
$('#fname').val(response[0].f_name);
alert(response[0].amount);
$('#sname').val(response[0].l_name);
$('#lname').val(response[0].other_name);
$('#expiry_date').val(response[0].id_no);
$('#quantity_available').val(response[0].dob)
$('#gender').val(response[0].gender);
$('#maritalstatus').val(response[0].marital_status)
$('#sex').val(response[0].gender);
},
error: function (data) {
}
})
});
});
The id attribute must be unique in your web page. You can't have 2 elements with the same id.
So for your links and your inputs, you must generate a different id for each row. For example you can try id="employee_id-<?php echo $employee['employee_id'];?>".
But you can keep the same classes for each link and input, and use it in your javascript script code.
Then you must change your code :
$('.edit').click(function() {
var employee_id = this.closest('tr').find('.employee_id').val();
});
Use class attribute instead of id because id cant be repeated.
<input type="text" name="employee_id" class="employee_id" value="<?php echo $employee['employee_id'];?>"/>
$('.edit').click(function() {
var id = this.closest('tr').find('input.employee_id').val();
});
In Id you will be able to get employee id

Get Ajax variable from the PHP foreach loops

I have a simple ajax (jquery version) script and very short php function and they works fine without problem.
When I submit the value from the form input are, the ajax will work to send and get result from
the php script, in this case to get a total amount of the book order.
The Ajax script and html section are as follows:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get field value
var qtyVal = $('#qty').val();
// use HTTP GET get ajax
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
//get xml value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
<body>
Total price:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<form>
<p>
<label>quantity: </label>
<input type="text" id="qty" name="qty"/>
<br/>
<input type="submit" value="submit">
total price:</p>
<p> </p>
</form>
And the following php script serving as xml also works fine with above ajax request:
<?php
// XML document
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
echo "<?xml version=\"1.0\" ?>";
echo "<datetime>";
echo "<qty>" . $qty*100 . "</qty>";
$total=$qty*100;
if ($total==0)
echo "<caution>"."please input number!"."</caution>";
else if ($total<=500)
echo "<caution>"."you shoud buy more!"."</caution>";
echo "";
echo "</datetime>";
?>
However when I combine the above scripts with my shopping cart foreach loops, it doesn't work and the ajax script failed to get variables from the form input area. I don't know if it is a variable scope issue (globals or local)? or anything else?
The following is the total script I would like to fixed with:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get value from the form
var qtyVal = $('#qty').val();
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<table border="1" align="center">
<tr>
<th>no</th>
<th>name</th>
<th>price</th>
<th>qty</th>
<th>update</th>
</tr>
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<form action="sessionCartUpdate.php">
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" id="qty" name="qty" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="submit" name="qty"
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
</form>
<?php
}
?>
<tr><td colsan="5">total amount:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div></td></td>
</table>
<p>continue to shop
<p>Put your order
</body>
</html>
I would be very grateful if anyone can offer kind or possible suggestion or advice?
My goal is to put different number (variables) in the "input area" (name or id as "qty") throught the using of ajax to get a total amount of price and show the result in the div box (id="result" or "result1").
You should replace the id attribute with class because id is supposed to be unique in the dom and using class you can do a loop to get all quantities of the items in the cart
Another thing i have noticed that you have made the an individual form foreach item in the cart there should be one form having the multiple fields,also remove this line <input type="submit" name="qty" it doesent makes sense
<form action="sessionCartUpdate.php">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
<?php
}
?>
</form>
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
var qtyVal =0;
$( ".qty" ).each(function() {
qtyVal =qtyVal + parseInt($(this).val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.

Categories