I made custom plugin and done crud operation, display all data in admin page, used ajax and jquery. Data successfully deleted but not inserted or updated. Data successfully pass through ajax but not inserted. Also What I saw if input block is empty and I put some data and updated it. It got first row data.
Error- https://prnt.sc/wnzqjr
ajax for insert data
<tr>
<td><?php echo $q ?></td>
<td>
<input type="text" name="question" class="question" value="<?php echo $print->question ?>" ></td>
<td>
<input type="text" name="answer" class="answer" value="<?php echo $print->answer ?>" > </td>
<td>
<input type="button" value="Insert" id="insert" data-id = "<?php echo $print->id ?>" name="insert" class="ins_btn">
</td>
<td>
<input type="button" value="Update" id="update" data-id = "<?php echo $print->id ?>" name="update" class="upd_btn">
</td>
<td>
<input type="button" value="Delete" id="delete" data-id = "<?php echo $print->id ?>" name="delete" class="del_btn">
</td>
</tr>
jQuery('.ins_btn').click(function(){
var id = jQuery(this).attr('data-id');
var question = jQuery('#question').val();
var answer = jQuery('#answer').val();
// alert(id);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'insert_records',
insert_record : id,
insert_question: question,
insert_answer: answer
},
success: function( data ){
alert("Records are successfully insert");
location.reload();
}
});
});
insert query
function insert_records(){
global $wpdb;
$id = $_POST['insert_record'];
$question = $_POST['insert_question'];
$answer = $_POST['insert_answer'];
$db_inserted = $wpdb->insert( $wpdb->prefix.'faqq',
array( 'ID' => $id,
'question' => $question,
'answer' => $answer)
);
}
add_action( "wp_ajax_insert_records", "insert_records" );
add_action( "wp_ajax_nopriv_insert_records", "insert_records" );
ajax for update the data
jQuery('.upd_btn').click(function(){
var id = jQuery(this).attr('data-id');
var question = jQuery('#question').val();
var answer = jQuery('#answer').val();
alert(question);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'update_records',
update_record : id,
update_question : question,
update_answer : answer
},
success: function( data ){
alert("Records are successfully updated");
location.reload();
}
});
});
update query
function update_records(){
global $wpdb;
// $table_name = $wpdb->prefix.'faqq';
$id = $_POST['update_record'];
$question = $_POST['update_question'];
$answer = $_POST['update_answer'];
$db_updated = $wpdb->update( $wpdb->prefix.'faqq',
array('question' => $question,
'answer' => $answer, array( 'ID' => $id ) )
);
}
Here are some errors. 1)Getting error when update the data through ajax- https://prnt.sc/wnymkx, https://prnt.sc/wnyos5, https://prnt.sc/wnyuhk
The problem might be that your loop which is creating the list for displaying on admin page is causing multiple elements to have the same id, when id attributes must be unique within the DOM. To fix this use common classes on the elements within the loop, then DOM traversal to find them when the button is clicked.
Change the code block for display like this:
$mysql = Database::DBCon()->prepare('SELECT * FROM table_name');
$mysql->execute();
while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC)){
$html = '<tr>
<td><input type="text" value="'. $fetch['question'] .'" class="question"></td>
<td><input type="text" value="'. $fetch['answer'] .'" class="answer"></td>
<td>
<button type="button" class="btn btn-danger insert-btn" data-id="'. $fetch['ID'] .'">Insert</button>
<button type="button" class="btn btn-warning update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
</tr>';
//echo $html;
}
Then change implementation of function to something like this:
$(document).ready(function() {
$(document).on('click', '.update-btn', function() {
var $row = $(this).closest('tr');
var id = $(this).data('id');
var question= $row.find('.question').val();
var answer = $row.find('.answer').val();
// ajax request here...
});
})
i think you forgot to enqueue your script file where jQuery is written. that's it is showing script called incorrectly
you suppose to register your script by admin_enque_script hook
Don't need id field for inserting data, So I remove it. I use classes for question and answer fields.
jQuery('.ins_btn').click(function(){
var question = jQuery(this).closest('tr').find('.question').val();
var answer = jQuery(this).closest('tr').find('.answer').val();
// alert(question);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action : 'insert_records',
insert_question : question,
insert_answer : answer
},
success: function( data ){
location.reload();
}
});
});
Same as for update function, only add reference id field. Because for updating the data, reference Id is important.
jQuery('.upd_btn').click(function(){
var id = jQuery(this).attr('data-id');
var question = jQuery(this).closest('tr').find('.question').val();
var answer = jQuery(this).closest('tr').find('.answer').val();
$.ajax({
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
data:{
action: 'update_records',
update_record : id,
update_question : question,
update_answer : answer
},
success: function( data ){
location.reload();
}
});
});
And in update query, I added parenthesis at wrong position.
function update_records(){
global $wpdb;
// echo "<pre>"; print_r($_POST);
// die();
// $table_name = $wpdb->prefix.'faqq';
$id = $_POST['update_record'];
$question = $_POST['update_question'];
$answer = $_POST['update_answer'];
$db_updated = $wpdb->update( $wpdb->prefix.'faqq',
array('question' => $question,
'answer' => $answer
),
array( 'ID' => $id )
);
// $wpdb->query($wpdb->prepare("UPDATE $table_name SET question = '$question', answer = '$answer' WHERE id = $id"));
}
add_action( "wp_ajax_update_records", "update_records" ); //update_records is action
add_action( "wp_ajax_nopriv_update_records", "update_records" );
Related
From the database, I have a dynamic table like this:
<table>
<?php
$query = ....;
foreach ($query as $row) {
echo '<tr>';
echo '<td>' . ' <span class="bName">' . $row['brand_name'] . '</span>'.
'<input name="product_id" type="number" value="' . $row['product_id'] . '">'.
'<input name="company_id[]" type="number" value="' . $row['company_id'] . '">'.
'<button name="exchange" type="button">Click Me!</button></td>';
echo '</td>';
echo '</tr>';
}
?>
</table>
It returns say 4 rows with brand_name inside the <span> and product_id inside an <input>. The exchange button on click calls an ajax request that query another random brand_name and returns the query as JSON like this:
{product_id: '2206', brand_name: 'New name', company_id: '234' }
The script for ajax is
<script>
$(document).ready(function() {
$('button[name="exchange"]').click(function() {
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$('.bName').html(data.brand_name); // Problem is here
$('.company_id').html(data.company_id); // and here
console.log(data);
},
});
});
});
</script>
My target is to change the brand_name inside class bName and company_id value with the new values from ajax response for that specific row. But my problem is it changes all the spans with bName class and all the inputs with class company_id. What should be the best approach to change the specific row of that table from the ajax data?
Store a reference to the cell that the button that was actually clicked exists in so you can find within that cell the specific elements.
Also note that the company_id value is in an input thaat you ned to use val() on and you need to give it a class name
$('button[name="exchange"]').click(function() {
// cell this button instance is in
const $cell = $(this).closest('td');
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$cell.find('.bName').html(data.brand_name); // Problem is here
$cell.find('.company_id').val(data.company_id); // and here
console.log(data);
},
});
});
Unable to test using AJAX but perhaps this might help. Use the event of the click function to find the parentNode and from that use querySelector to target the particular elements in the table row.
$(document).ready(function() {
$('button[name="exchange"]').click(function(e) {
let tr=e.target.parentNode;
let span=tr.querySelector('span.bName');
let pid=tr.querySelector('input[name="product_id"]');
let cid=tr.querySelector('input[name="company_id[]"]');
console.info( span.textContent, cid.value, pid.value)
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
span.textContent=data.brand_name;
cid.value=data.company_id;
pid.value=data.product_id;
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="bName">Womble</span>
<input name="product_id" type="number" value="23">
<input name="company_id[]" type="number" value="88">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Bagpuss</span>
<input name="product_id" type="number" value="39">
<input name="company_id[]" type="number" value="12">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Clanger</span>
<input name="product_id" type="number" value="47">
<input name="company_id[]" type="number" value="91">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
</table>
I've been trying to make a table with a list of users for a school project.
I'm doing this with jquery, php and mysql.
I'm retrieving all data from the mysql database and printing it out in a table.
now i'm trying to add an update button to i can easily update data for each specific row.
This however is not working as expected. It only selects the data from the same row. While the data-id value is different. Could anyone tell me why this is happening? I'll leave my code below for clearance
JS:
$(document).ready(function () {
$(document).on('click', '#update-btn', function () {
var id =$("[id='update-btn']").attr('data-id');
var username = $('#username').val();
var dob = $('#dob').val();
var address = $('#address').val();
$.ajax({
url: 'ajax/update.php',
method: 'POST',
data: {
ID: id,
username: username,
dob: dob,
address: address
},
success: function (data) {
if (data){
console.log(data);
swal({
title: 'Update successful',
icon: 'success',
text: 'User with ID ' + id + ' updated.'
});
setTimeout(function () {
window.location = 'medewerkers.php';
}, 5000)
}
else if (data === "update_failed"){
}
}
});
});
});
PHP:
public static function loadMedewerkers(){
$mysql = Database::DBCon()->prepare('
SELECT * FROM medewerkers
');
$mysql->execute();
while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC))
{
$html = '<tr>
<td><input type="text" value="'. $fetch['username'] .'" id="username"></td>
<td><input type="text" value="'. $fetch['dob'] .'" id="dob"></td>
<td><input type="text" value="'. $fetch['address'] .'" id="address"</td>
<td><button type="button" class="btn btn-danger" id="delete-btn" data-id="'. $fetch['ID'] .'">Delete</button>
<button type="button" class="btn btn-warning" id="update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
</tr>';
echo $html;
}
}
The problem is because your loop is causing multiple elements to have the same id, when id attributes must be unique within the DOM. To fix this use common classes on the elements within the loop, then DOM traversal to find them when the button is clicked.
public static function loadMedewerkers()
{
$mysql = Database::DBCon()->prepare('SELECT * FROM medewerkers');
$mysql->execute();
while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC))
{
$html = '<tr>
<td><input type="text" value="'. $fetch['username'] .'" class="username"></td>
<td><input type="text" value="'. $fetch['dob'] .'" class="dob"></td>
<td><input type="text" value="'. $fetch['address'] .'" class="address"</td>
<td>
<button type="button" class="btn btn-danger delete-btn" data-id="'. $fetch['ID'] .'">Delete</button>
<button type="button" class="btn btn-warning update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
</tr>';
echo $html;
}
}
$(document).ready(function() {
$(document).on('click', '.update-btn', function() {
var $row = $(this).closest('tr');
var id = $(this).data('id');
var username = $row.find('.username').val();
var dob = $row.find('.dob').val();
var address = $row.find('.address').val();
// ajax request here...
});
});
Note the use of data() to retrieve the data attribute. Also note that you could put the data-id attribute itself on the tr instead of each button to DRY up the HTML slightly.
You are using ID in your buttons when returning
ID is unique for each object in the screen
try using class
something like this:
$(document).ready(function () {
$(document).on('click', '.update-btn', function () {
var id =$(this).data('id');
var username = $(this).closest('tr').find('.username').val();
var dob = $(this).closest('tr').find('.dob').val();
var address = $(this).closest('tr').find('.address').val();
$.ajax({
url: 'ajax/update.php',
method: 'POST',
data: {
ID: id,
username: username,
dob: dob,
address: address
},
success: function (data) {
if (data){
console.log(data);
swal({
title: 'Update successful',
icon: 'success',
text: 'User with ID ' + id + ' updated.'
});
setTimeout(function () {
window.location = 'medewerkers.php';
}, 5000)
}
else if (data === "update_failed"){
}
}
});
});
});
public static function loadMedewerkers(){
$mysql = Database::DBCon()->prepare('
SELECT * FROM medewerkers
');
$mysql->execute();
while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC))
{
$html = '<tr>
<td><input type="text" value="'. $fetch['username'] .'" class="username"></td>
<td><input type="text" value="'. $fetch['dob'] .'" class="dob"></td>
<td><input type="text" value="'. $fetch['address'] .'" class="address"</td>
<td><button type="button" class="btn btn-danger delete-btn" data-id="'. $fetch['ID'] .'">Delete</button>
<button type="button" class="btn btn-warning update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
</tr>';
echo $html;
}
}
same goes for your delete button
and use .data() instead of attr()
Also, in other columns for getting the username, dob and address you have to use class instead of id.
I have list with several inputs
<input type="hidden" id="elevens_id_ea" value="<?php echo $_GET['elev_id']; ?>" />
<input type="hidden" id="arskursen_ea" value="<?php echo $arskursen; ?>" />
<?php
if ($extraanpassning_hamta['atgard'] == true){
?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-red btn-sm" value="Ja">
<?php } else { ?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-green btn-sm" value="Nej">
<?php } ?>
The main problem is how to "catch" the value in the two latest inputs with:
id="knapp[<?php echo $amnets_id['amne_id']; ?>]"
If knapp[4] -> how do I get the 4?
The code above is a part of a button that changes value when the user presses it (without refreshing the page).
The JS
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var extraanpassningVal = $(this).attr("value");
var amne_id_ea = $(this).attr("id");
var elevens_id_ea = $("#elevens_id_ea").val(); //värdet av elev_id
var arskursen_ea = $("#arskursen_ea").val(); //värdet av elev_id
$.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
});
});
</script>
EDIT:
The main problem is how to get the key from a input with an id like knapp[4].
How do get the key within knapp[]?
Update (thanks to user:SpYk3HH)
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajax) this.ajax.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajax = $.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
})
});
</script>
I think I get it? You want the key when calling the button in JS? So like say: key = this.id.replace(/knapp|\[|\]/g, '')
Update, I didn't see the brackets before
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajx) this.ajx.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajx = $.ajax({/* options */});
})
Does that help?
FYI, $(this).attr("id") and this.id are the same thing
$('[name=test]').each(function(i) { $('#bob').text(this.id.replace(/knapp|\[|\]/g, '')) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="knapp4" name="test" value='my id is "knapp[4]"' />
<hr />
key: <span id="bob"></span>
Try this.
var amne_id_ea = "knapp[4]",
value = amne_id_ea.substring(amne_id_ea.lastIndexOf("[")+1,amne_id_ea.lastIndexOf("]"));
alert(value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Hope you are expecting this.
here i want to passing the product_id value into addcart.php file through the jQuery Function.here 'Add Cart' button generated dynamically by php while loop. every button set as a invidual product id, there is fine until this..
what's my problem is All Button pass the same value to addcart.php file when i clicked each one...i want to pass the value of individual one(button)..
Please Give me a Solution... addcart.php just contain code like
"echo $_POST['pid']; only"
<?php
include('includes/db-config.php');
$shop_id=$_GET['sid'];
$get_product_q = mysql_query("select product from shops where sid = $shop_id");
$get_product_f = mysql_fetch_array($get_product_q);
$product_id = explode(',', $get_product_f['product']);
$count_product_id = count($product_id);
for($i=0;$i<$count_product_id;$i++){
$get_product_q = mysql_query("select * from products where pid = $i");
$get_product_f = mysql_fetch_array($get_product_q);
$product_id = $get_product_f['pid'];
?>
<script>
$(document).ready(function(){
$('.but').click(function(){
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : '<?php echo $product_id?>'},
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
<?php
$product_name = $get_product_f['name'];
$product_description = $get_product_f['description'];
$product_price = $get_product_f['price'];
echo $product_name;
echo '<br>';
echo $product_description;
echo '<br>';
echo $product_price;
echo '<br>';
echo '<input class="but" type="button" value="Add Cart" />';
echo '<br><br>';
}
?>
<div id="div1"></div>
You are repeating the entire Javascript for every product. Move the Javascript out of the loop and set the product ID as a data-productid attribute on the button:
echo '<input class="but" type="button" value="Add Cart" data-productid="' . htmlspecialchars($product_id) . '" />';
Then when you make the ajax call (on click), read the product ID and set it as the POST data:
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : $(this).data('productid') },
success:function(result){
$("#div1").html(result);
}
});
Try this :
replace : echo '<input class="but" type="button" value="Add Cart" />'; by this : echo '<input class="but" type="button" rel="'.htmlspecialchars($product_id).'" value="Add Cart" />';
and your script :
<script>
$(document).ready(function(){
$('.but').click(function(){
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : $(this).attr('rel'),
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
The problem is that you're binding it to a click on all elements with the class ".but", if you on the other hand gave the button an id like
echo '<input data-pid="'. sha1($product_id) . '" class="but" type="button" value="Add Cart" />';
and then in your jquery function would do the following (outside the loop):
<script>
$(document).ready(function(){
$('.but').click(function(){
$.ajax({
type: 'POST',
url:"addcart.php",
data : $(this).data(),
success:function(result){
$("#div1").html(result);
}
});
});
});
</script>
Then you would get around the problem, as it then listens for the click event on each element, but the data is varying on each element.
I hope this helps.
in you loop ,.but was bind an function each time,so the last bind one works .try to give the .but elements an unique id such as "id=$product_id";
and you can bind the function once (outside the loop).this simply like:
$(document).ready(function(){
$('.but').click(function(){
var data = $(this).attr("id");
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : data},
success:function(result){
$("#div1").html(result);
}});
});
});
be lucky.
I can't figure it out how I can update the database with this textarea. Can somebody help?
The ajaxcall
$$('.btn').addEvent('click', function() {
var request = new Request( {
url: '<?php echo $baselink;?>',
method: 'post',
onSuccess:function(responseText) { alert(responseText);},
data: {
'name' : this.id,
'value' : this.value,
'tmpl':'component',
'format':'raw',
'ajax' : 1
}
}).send();});
**//Form//**
$s6=$item['Select6'];
$id=$item['items_id'];
print '<form method="post" class="formulier">
<input maxlength="250" NAME="name" class="name" id="'.$id.'" value="'.$s6.'" SIZE="50">
<input type="submit" value="Click me" class="btn"/></form>';
Query
if(JRequest::getVar('ajax') ) {
$state=JRequest::getInt('value','oeps');
$id=JRequest::getVar('name','');
if ( $id ) {
$state=(int)$state;
$query="UPDATE #__dataitems set `Select6`='".$state."' where `items_id`=".$id;
$db->query();
echo ' Bijgwerkt naar '.$state.' '.$id;
exit;}
You are currently listening on the radio button click and send the event when it does.
You need to add a button/href to your form and bind an click event to it, and then once it is clicked, just collect the data from the radio button and the textarea and send it:
HTML:
<input type="button" value="Click me" class="btn"/>
JS:
$$('.btn').addEvent('click', function(){
var radioId = ...//get radio id
var radioVal = ...//get val
var textarea = ... //get textarea val
var request = new Request( {
url: '<?php echo $baselink;?>',
method: 'post',
onSuccess:function(responseText) { alert(responseText);},
data: {
'volgorde' : radioId,
'check' : radioVal,
'textarea' : textarea ,
'tmpl':'component',
'format':'raw',
'ajax' : 1
}
}).send();});
I'm guessing you are using prototypejs (because of the $$), i don't know it very well so i can't help you with how to get the elements id and values, but this is the direction.