I'm able to delete one entry at a time using AJAX. Now I've made the possibility to select entries using a checkbox and delete them all simultaneously, this works great without AJAX. Now I'm trying to delete multiple entries using AJAX. This is what I have so far:
the ajax:
`$(function() {
$(".checkbox_button_del").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parents('tr:first');
var notice = '<div class="notice">'
+ '<div class="notice-body">'
+ '<img src="core/displays/notify/delete-icon.png" alt="" />'
+ '<h3>Deleted item</h3>'
+ '<p>The item has been succesfully deleted.</p>'
+ '</div>'
+ '<div class="notice-bottom">'
+ '</div>'
+ '</div>';
$ny( notice ).purr(
{
usingTransparentPNG: true
}
);
$.ajax({
type: "POST",
url: "core/actions/delete_multiple.php",
data: dataString,
cache: false,
success: function()
{
parent.fadeOut('300', function() {$(this).remove();});
$("#load_tasklist").load("core/statistics/stats_brackets.php")
$("#load_tweets").load("response.php")
$("#load_mod_day_summary").load("core/displays/mod_day_summary.php")
$("#load_mod_task_selector").load("core/displays/mod_task_selector.php")
}
});
return false;
});
});`
the external deleting script:`
include('../../core/additional/connect-db.php');
for($i=0;$i<count($_POST["chkDel"]);$i++)
{
if($_POST["chkDel"][$i] != "")
{
$strSQL = "DELETE FROM players ";
$strSQL .="WHERE id = '".$_POST["chkDel"][$i]."' ";
$objQuery = mysql_query($strSQL);
}
}
header('Location: ' . $_SERVER['HTTP_REFERER']);`
and the result list with the delete button: `
<form name="frmMain" id="myForm" method="post" OnSubmit="return onDelete();">
<?php
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
$result = mysql_query("SELECT * FROM players WHERE (userid = '$username' AND done = '0' AND measure = 'task' AND day = '$user_mydate') ORDER BY id DESC")
or die(mysql_error());
echo '<div id="checkbox_button_div">
<input class="checkbox_button_del" type="submit" id="buttondel" value="Delete" />
<input class="checkbox_button_done" type="submit" id="buttondone" value="Done" />
<input class="checkbox_button_done" type="submit" id="buttonfavorite" value="Favorite" />
<input class="checkbox_button_done" type="submit" id="buttonmove" value="+1 day" />
</div>';
echo '
<table id="tableOne" cellpadding="0" cellspacing="0" width="760" border="0" class="yui">
<thead>
<tr>
<th>Task</th>
<th>Minutes</th>
<th>Time</th>
<th>Category</th>
<th> <input type="checkbox" class="check" value="check all" /></th>
</tr>
</thead>
<tbody> ';
$i = 0;
while($row = mysql_fetch_array( $result )) {
$i++;
include ('core/additional/params_tasks.php');
echo '
<tr class="handcursor" onmouseover="' .($mouseover). '" onmouseout="' .($mouseout). '">
<td class="editable" id="' .($id). '" width="180">' .($task). ' </td>
<td class="editable" id="' .($id). '">' .($minutes). '</td>
<td onClick="' .($onclick). '">' .($hours_start). '.' .($minutes_start). ' - ' .($hours_due2). '.' .($minutes_due2). ' </td>
<td onClick="' .($onclick). '">' .($categorie). ' </td>
<td align="center"><input type="checkbox" class="cb-element" name="chkDel[]" id="chkDel<?=$i;?>" value="' .($id). '"></td>
</tr> ';
}
// close table>
echo '</tbody>
<tfoot>
<tr style="display:none;">
<td style="border: 0px;" colspan="4">
No matching results..
</td>
</tr>
</tfoot>
</table>
';
?>
<input type="hidden" name="hdnCount" value="<?=$i;?>">
</form>`
I think the AJAX script should pass the "$i" values as well, but I don't know how to do this. Please tell me if the problem isn't clear to you. Looking forward to your answer!
yout jquery would be somthing like this.
$("#Submit1").click(function () {
var arr = new Array();
$("input:checked").each(function () {
arr.push($(this).attr("id"));
}); //each
$.ajax({
type: "POST",
url: "core/actions/delete_multiple.php",
data: arr ,//pass the array to the ajax call
cache: false,
success: function()
{ }
});//ajax
}); //each
}); //click
since the PHP function will get a JSON object. you will need to do a JSON decode to ge the array.... see JSON decode... use this array to create your query like..
delete from SalesLT.Customer
where CustomerID in (1,2,3,4);
Related
I'm trying to get the value of span, after selecting an item the total price will go to span and I cant get it right. I'm trying to use ajax but I'm really new to it I'm struggling to get it right. when I'm trying to run e it will say Undefined index: totalprice. How can i get the value of totalprice correctly?
try.php
<thead>
<tr>
<th>Component</th>
<th>Item Name</th>
<th>Price </th>
</tr>
</thead>
<tbody>
<tr>
<td>CPU</td>
<td>
<?php
//Retrieving CPU table
$query = $conn->query("SELECT * FROM cpu");
echo '<select name="cpu" class="cpu" onChange = $("#cpuprice").val($(this).find("option:selected").attr("cpuprice"))>';
echo '<option></option>';
while ($obj = mysqli_fetch_assoc($query)) {
echo '<option cpuprice = ' . $obj['price'] . ' value=' . $obj['cpuname'] . ' >' . $obj['cpuname'] . '</option> /n';
}
echo '</select>';
?>
</td>
<td>
<output id="cpuprice" disabled value="">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>GPU</td>
<td>
<?php
//Retrieving GPU table
$query = $conn->query("SELECT * FROM gpu");
echo '<select name="gpu" class ="gpu" onChange = $("#gpuprice").val($(this).find("option:selected").attr("gpuprice"))>';
echo '<option></option>';
while ($obj = mysqli_fetch_assoc($query)) {
echo '<option gpuprice = "' . $obj['price'] . '" value = "' . $obj['gpuname'] . '">' . $obj['gpuname'] . '</option>';
}
echo '</select>';
?>
</td>
<td>
<output id="gpuprice" disabled value="">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>CPU COOLER</td>
<td>
<?php
//Retrieving CPU Cooler table
$query = $conn->query("SELECT * FROM cpucooler");
echo '<select name = cpuc class = cpuc onChange = $("#cpucprice").val($(this).find("option:selected").attr("cpucprice"))>';
echo '<option></option>';
while ($obj = mysqli_fetch_assoc($query)) {
echo '<option cpucprice = "' . $obj['price'] . '" value = "' . $obj['cpucname'] . '" >' . $obj['cpucname'] . '</option>';
}
echo '</select>';
?>
</td>
<td>
<output id="cpucprice" disabled value="">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>
</td>
<td>
</td>
<td>
<span class="totalprice" name="total" Value="">
<script>
$('select').change(function() {
//get value from cpu slect box check if attr there else take value 0
var cpu_price = $(".cpu").find('option:selected').attr('cpuprice') ? $(".cpu").find('option:selected').attr('cpuprice') : 0
$('#cpuprice').val(cpu_price)
//get value from gpu slect box check if attr there else take value 0
var gpu_price = $(".gpu").find('option:selected').attr('gpuprice') ? $(".gpu").find('option:selected').attr('gpuprice') : 0
$('#gpuprice').val(gpu_price)
//get value from cpucooler slect box check if attr there else take value 0
var cpuc_price = $(".cpuc").find('option:selected').attr('cpucprice') ? $(".cpuc").find('option:selected').attr('cpucprice') : 0
$('#cpucprice').val(cpuc_price)
var total = parseInt(cpu_price) + parseInt(gpu_price) + parseInt(cpuc_price);
$('.totalprice').text('₱' + total);
})
</script>
</td>
</tr>
</tbody>
<script>
$("#total").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "trying.php",
data: {
'totalprice': totalprice
},
dataType: "json",
success: function(data) {
},
});
});
</script>
</table>
<input class="submit" type="submit" />
</form>
trying.php
<?php
if (isset($_GET['cpu']) !== '' && isset($_GET['gpu']) !== '' && isset($_GET['gpuc']) !== '' && isset($_GET['total']) !== '' && isset($_GET['totalprice']) !== '') {
$cpu = $_GET['cpu'];
$gpu = $_GET['gpu'];
$cpuc = $_GET['cpuc'];
$total = ($_GET['totalprice']);
$conn = mysqli_connect("localhost", "root", "", "userregistration");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qstr = $conn->prepare("INSERT INTO trycombuild (cpuname,gpuname,cpucname,total) VALUES (?,?,?,?)");
$qstr->bind_param("ssss", $cpu, $gpu, $cpuc, $total);
$qstr->execute();
$qstr->close();
echo 'succesfull';
} else {
echo 'error';
}
<span class="totalprice" name="total"></span>
Remove value tag from span and also change this javascript line
$('.totalprice').text('₱' + total);
to
$('.totalprice').html('₱' + total);
And change the ajax call like this:
<script>
$("#total").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "trying.php",
data: {
'totalprice': $('.totalprice').html()
},
dataType: "json",
success: function(data) {
},
});
});
</script>
for my dissertation I need to categorize images. The image links are stored in table "ocr". In my search page I am showing all the images in rows. Using AJAX I am searching Table "diss_kategorien" and showing the results in a dropdown in the table OCR. Now I need to update table ocr with the results, but I do not know how to pass the variable from the row with the current image which I am processing
This is my search page:
<div class="card-body">
<table width="95%" class="table table-bordered tablehover">
<tr>
<th width="40">ID</th>
<th>Image</th>
<th width="200">Hauptgegenstand</th>
<th width="130">Save</th>
<th width="137">Löschen</th>
<th width="137">Update</th>
</tr>
<?php
foreach($result as $r)
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="application/x-www-form-urlencoded">
<tr>
<td><input readonly name="id" type="text" class="form-control input-sm" value="<?php echo($r->id); ?>" id="id" /></td>
<td width="232"><img style="max-width: 400px" src="uploads/<?php echo($r->file_name);?>"></td>
<td>
<input type="text" name="search" id="search" autocomplete="off" placeholder="Gegenstand suchen">
<div id="output"></div>
</td>
</div>
<td><input type="submit" class="btn btn-primary" name="submit"></td>
<td><input type="submit" class="btn btn-primary" name="delete"></td>
<td width="5%">Update </td>
</tr>
</form>
<?php }?>
</table>
</div>
Here is the AJAX Code:
<script type="text/javascript">
$(document).ready(function(){
$("#search").keyup(function(){
var query = $(this).val();
if (query != "") {
$.ajax({
url: 'ajax-db-search.php',
method: 'POST',
data: {query:query},
success: function(data){
$('#output').html(data);
$('#output').css('display', 'block');
$("#search").focusout(function(){
$('#output').css('display', 'none');
});
$("#search").focusin(function(){
$('#output').css('display', 'block');
});
}
});
} else {
$('#output').css('display', 'none');
}
});
});
</script>
And here is my ajax-db-show.php
$conn=mysqli_connect($servername,$username,$password,$dbname);
mysqli_query($conn,"SET CHARACTER SET 'utf8'");
mysqli_query($conn,"SET SESSION collation_connection ='utf8_unicode_ci'");
if(!$conn){
die('Could not Connect MySql Server:' .mysql_error());
}
if (isset($_POST['query'])) {
$val = '%' . $_POST['query'] . '%';
$stmt = $conn->prepare("SELECT * FROM diss_kategorien WHERE ebene_1_txt LIKE ? OR ebene_2_txt LIKE ? or ebene_3_txt like ?");
$stmt->bind_param("sss", $val, $val, $val);
$stmt->execute();
$result = $stmt->get_result();
if (mysqli_num_rows($result) > 0) {
while ($user = mysqli_fetch_array($result)) {
// echo "Ebene 1: " . $user['ebene_1_txt']. "Ebene 2: " . $user['ebene_2_txt'] . "Ebene 3: ". $user['ebene_3_txt'] ."<br/>";
print "<td><a href='show_ocr_files_mainitem.php?param1=" . $user['ebene_1_nr'] . "¶m2=" . $user['ebene_2_nr'] . "¶m3=" .$user['ebene_3_nr']. "¶m4=" .$_POST['id']."'>ID: " . $_POST['id'] . " Ebene 1: " . $user['ebene_1_txt']. " Ebene 2: " . $user['ebene_2_txt'] . " Ebene 3: ". $user['ebene_3_txt'] . "<br/></a></td>";
}
} else {
echo "<p style='color:red'>Nichts gefunden..</p>";
}
When I type in a Search Term into field "Hauptgegenstand" I generate an hyperlink which should pass the Variables to the search page to update the table OCR:
print "<td><a href='show_ocr_files_mainitem.php?param1=" . $user['ebene_1_nr'] . "¶m2=" . $user['ebene_2_nr'] . "¶m3=" .$user['ebene_3_nr']. "¶m4=" .$_POST['id']."'>ID: " . $_POST['id'] . " Ebene 1: " . $user['ebene_1_txt']. " Ebene 2: " . $user['ebene_2_txt'] . " Ebene 3: ". $user['ebene_3_txt'] . "<br/></a></td>";
When I use ID of the search result for the update, then it is wrong, because I need the ID of the OCR table
I tried with
data: {query:query, id: <?php echo $r->id; ?>},
But the shown ID is 470 instead of 111. I do not get the ID of the OCR Field where I am doing the Search, I only get the ID of the last entry in the search of the OCR table. I have limited the search to 50 and so the last ID is 470
So I am getting the correct search results, but I am not aware how to pass the ID of the Table OCR to the Ajax file and from there back to the search page to update the table OCR.
Thank you for your help and advice how to solve this.
All the best,
Stefan
You cannot use same id for mutiple elements instead use class . So , change id="search" to class="search" and id="output" to class="output" . Then , you can use $(this).closest("tr").find("input[name=id]").val() to get the id of row where you are performing search currently.
Demo Code :
$(document).ready(function() {
$(".search").keyup(function() {
var $this = $(this); //for refering `this` inisde success fn
var selector = $(this).closest("tr"); //get closest tr
var query = $(this).val();
var id = $(this).closest("tr").find("input[name=id]").val(); //get id
console.log("Id -- " + id)
if (query != "") {
/*$.ajax({
url: 'ajax-db-search.php',
method: 'POST',
data: {
query: query,
id:id
},
success: function(data) {*/
//selector.find(".output").html(data);
selector.find(".output").html("somethinfsfsfsf"); //just for demo..
selector.find(".output").css('display', 'block');
$this.focusout(function() {
selector.find(".output").css('display', 'none');
});
$this.focusin(function() {
selector.find(".output").css('display', 'block');
});
/* }
});*/
} else {
selector.find(".output").css('display', 'none');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-body">
<table width="95%" class="table table-bordered tablehover">
<tr>
<th width="40">ID</th>
<th>Image</th>
<th width="200">Hauptgegenstand</th>
<th width="130">Save</th>
<th width="137">Löschen</th>
<th width="137">Update</th>
</tr>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="application/x-www-form-urlencoded">
<tr>
<td><input readonly name="id" type="text" class="form-control input-sm" value="1" id="id" /></td>
<td width="232"><img style="max-width: 400px" src="uploads/<?php echo($r->file_name);?>"></td>
<td>
<input type="text" name="search" class="search" autocomplete="off" placeholder="Gegenstand suchen">
<div class="output"></div>
</td>
<td><input type="submit" class="btn btn-primary" name="submit"></td>
<td><input type="submit" class="btn btn-primary" name="delete"></td>
<td width="5%">Update </td>
</tr>
</form>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="application/x-www-form-urlencoded">
<tr>
<td><input readonly name="id" type="text" class="form-control input-sm" value="2" id="id" /></td>
<td width="232"><img style="max-width: 400px" src="uploads/<?php echo($r->file_name);?>"></td>
<td>
<input type="text" name="search" class="search" autocomplete="off" placeholder="Gegenstand suchen">
<div class="output"></div>
</td>
<td><input type="submit" class="btn btn-primary" name="submit"></td>
<td><input type="submit" class="btn btn-primary" name="delete"></td>
<td width="5%">Update </td>
</tr>
</form>
</table>
</div>
<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.
For my application, I have several hundred text inputs inside a table, each with their own submit buttons. Each text field needs to be able to be submitted to MySQL separately. How would I go about accomplishing this?
$(document).ready(function() {
$(".toggler").click(function(e) {
e.preventDefault();
$('.cat' + $(this).attr('data-prod-cat')).toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table>
<tr>
<td>Product</td>
<td>Price</td>
<td>Destination</td>
<td>Updated on</td>
</tr>
<tr>
<td>Oranges</td>
<td>100</td>
<td>
<button class="toggler" data-prod-cat="1">+ On Store</button>
</td>
<td>22/10</td>
</tr>
<tr class="cat1" style="display:none">
<td style="white-space: nowrap">Enter Amount:
<input type="text" maxlength="4" name="quantity" class="input" /> Submit
</td>
</tr>
<tr>
<td>Apples</td>
<td>100</td>
<td>
<button class="toggler" data-prod-cat="2">+ On Store</button>
</td>
<td>22/10</td>
</tr>
<tr class="cat2" style="display:none">
<td style="white-space: nowrap">Enter Amount:
<input type="text" maxlength="4" name="quantity" class="input" /> Submit
</td>
</tr>
</table>
<?php
$con = mysql_connect("site_url","id","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cis_id", $con);
$sql="INSERT INTO table (price)
VALUES
('$_POST[price]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
One way to submit an input is to create a form but since in your case creating a form will be one hell of a work. so i would go with calling a ajax function and passing a value("quantity") to your page.
$('.submit').click(function(e){
e.preventDefault();
var me = $(this);
$.ajax({
type:"post",
data: {price : me.closest('.input').val()},
url: "link/to/your/mysql/function/"
}).done(function(html){
alert(success);
});
});
PHP
echo $_POST[price]; //should give you the price
Use an AJAX call submitting only the field you need. Like this:
$.ajax({
type: POST, url: http:/yourdomain.com/yourajaxpage.php
data: {
fieldToSubmit: $('#field).val()
}
}).done(function( res ) {
// whatever you want to do on return;
});
on PHP the field on "data" will be available in $_POST
Your sql is wrong in php, the query is taking brackets as a string. Use the code below in php file
<?php
$con = mysql_connect("site_url","id","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cis_id", $con);
$var = $_POST[price];
$sql="INSERT INTO table (price)
VALUES
('$var')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Hope this helps you
I do have a dynamic grid that shows items from MySQL table using PHP. I have a icon that is supposed to get data from MySQL based in the id of the current register and fill the fields in the form with related information:
PHP/HTML grid
$output .='<tr id="'.$id.'">';
$output .='<td>'.$description.'</td>';
$output .='<td>'.$description_pt.'</td>';
$output .='<td align="right">US$'.number_format($price, 2, '.', ',').'</td>';
$output .='<td align="center">'.$a_c.'</td>';
$output .='<td align="center">'.$note.'</td>';
$output .='<td align="center">'.$note_pt.'</td>';
$output .='<td align="center" class="icon_grid"><a class="editar" title="Open the register." href="#"><img src="images/Write2.gif" width="16" height="16" /></a></td>';
$output .='<td align="center" class="icon_grid"><a class="delete" title="Delete the register." href="#"><img src="images/Trash.gif" width="16" height="16" /></a></td>';
$output .='</tr>';
The HTML form:
<div id="edita_cadastro">
<form name="form3" id="form3" method="post" action="" >
<table width="50%" border="0" cellspacing="2" cellpadding="0">
<tr>
<td colspan="2"><h3>Edit the current register</h3></td>
</tr>
<tr>
<td align="right"><label for "edt_description"><img src="images/usa.jpg" width="18" height="15" />Description:</label></td>
<td><input type="text" name="edt_description" id="edt_description" size="45" /></td>
</tr>
<tr>
<td align="right"><label for "edt_description_pt"><img src="images/brazil.jpg" width="18" height="15" />Description:</label></td>
<td><input type="text" name="edt_description_pt" id="edt_description_pt" size="45" /></td>
</tr>
<tr>
<td align="right"><label for "edt_price">Price:</label></td>
<td><input type="text" name="edt_price" id="edt_price" size="35" placeholder="ex.: 1.00" /></td>
</tr>
<input type="hidden" name="pack_id" id="pack_id" value="<?php echo $pack_id; ?>" />
<td><input type="hidden" name="editar" value="editar" /></td>
<td><input type="submit" name="submit" id="submit" value="Save" /></td>
</tr>
</table>
</form>
</div>
Now, the PHP get_prices.php
include '../connect_to_mysql.php';
$item_id = $_POST['pk_id']; // Selected item Id
$query = "SELECT * from packages_prices WHERE id='$item_id'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result, MYSQL_ASSOC);
$description = $row['description'];
$description_pt = $row['description_pt'];
$price = $row['edt_price'];
$arr = array( 'edt_description' => $description, 'edt_description_pt' => $description_pt, 'edt_price'=> $price);
echo json_encode( $arr );
Finally, the jQuery script:
$(document).ready(function(e) {
$("#tabela tr[id]").on("click", ".editar", function () { // Tabela is the table's id
var obj = $(this).closest("tr[id]");
$.ajax({
type: "POST",
url: 'get_prices.php',
data: { pk_id: obj.attr("id")},
dataType: "json",
success: function(data, evt) {
if (data.success == "true") {
$("#edt_description").val(data.edt_description);
$("#edt_description_pt").val(data.edt_description_pt);
$("#edt_price").val(data.edt_price);
} else {
alert('error');
}
}
});
});
So, I don't know what may be wrong. The data is not coming and, of course, not filling the fields.
Does anyone knows what is going on?
Thank you
You have a syntax error , your forgot }); at the end of your script , so may it's the reason why it's not working:
<script>
$(document).ready(function(e) {
$("#tabela tr[id]").on("click", ".editar", function () { // Tabela is the table's id
var obj = $(this).closest("tr[id]");
$.ajax({
type: "POST",
url: 'get_prices.php',
data: { pk_id: obj.attr("id")},
dataType: "json",
success: function(data, evt) {
if (data.success == "true") {
$("#edt_description").val(data.edt_description);
$("#edt_description_pt").val(data.edt_description_pt);
$("#edt_price").val(data.edt_price);
} else {
alert('error');
}
}
});
});
});
</script>