Unable to pass AJAX call due to undefined variable - javascript

For whatever reason, when making an AJAX call to the server, the console keeps saying that a variable parameter I've assigned it to is perfectly valid in the previous function I've chained it to. The error I keep getting is:
Uncaught TypeError: Cannot call method 'split' of undefined.
Any help is greatly appreciated.
$("body").on("click", ".edit_tr", function() {
var ID = $(this).attr('id'); //This is valid. It works.
var split = ID.split('_');
$("#first_" + split[1]).hide();
$("#last_" + split[1]).hide();
}).change(function() {
var ID = $(this).attr('id'); //This keeps coming back as undefined.
var split = ID.split('_');
var first = $("#first_input_" + split[1]).val();
var last = $("#last_input_" + split[1]).val();
});
And some relevant PHP/HTML:
<tr id="item_<?php echo $id; ?>" class="edit_tr">
<td>
Delete Record
</td>
<td class="edit_td">
<span id="first_<?php echo $id; ?>" class="text">
<?php echo $firstname; ?>
</span>
<input type="text" value="<?php echo $firstname; ?>" size="8" class="editbox" id="first_input_<?php echo $id; ?>" />
</td>
<td class="edit_td">
<span id="last_<?php echo $id; ?>" class="text">
<?php echo $lastname; ?>
</span>
<input type="text" value="<?php echo $lastname; ?>" size="8" class="editbox" id="last_input_<?php echo $id; ?>" />
</td>
</tr>

Your value of this in the change handler is bounded to the body element. Your body element doesn't have that id. I would either do this:
$(".edit_tr").on("click", function() {
...
}.change( ... );
Or attach the change event on .edit_tr separately.

Related

How can I update any row rather than only the top row with the update button on each side in PHP and AJAX

just starting out so gonna sound like a noob question but how can I use the update button to update individual rows rather than only the top row.
Whenever I use the update button, the request only goes through if it was the top row.
This is the code for the index.php
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<center>
<h3>UPDATE DATA</h3>
<?php
$run = 0;
$conn = new mysqli('localhost', '', '', '');
$sql = "SELECT * FROM moderator";
$result = $conn->query($sql);
while ( $row=mysqli_fetch_assoc($result)) {
$run = $run + 1;
?>
<div>
ID<input type="text" id="id" value="<?php echo $row['id']; ?>">;
Moderator<input type="text" id="mod" value="<?php echo $row['name']; ?>">;
Category<input type="text" id="ctgr" value="<?php echo $row['category']; ?>">;
<button type="submit" id="update" rel="<?php echo $run; ?>">UPDATE</button>
</div>
<?php
}?>
</center>
<script>
$(document).ready(function(){
$("#update").click(function(){
var name=$("#mod").val();
var ctgr=$("#ctgr").val();
var id=$("#id").val();
$.ajax({
url:'update.php',
method:'POST',
data:{
name:name,
ctgr:ctgr,
id:id
},
success:function(response){
alert(response);
}
});
});
});
</script>
</body>
This is the code for the update.php
<?php
$conn = new mysqli('localhost', '', '', '');
$name=$_POST["name"];
$ctgr=$_POST["ctgr"];
$id=$_POST["id"];
$sql="UPDATE moderator set name='$name', category='$ctgr' where id='$id'";
if($conn->query($sql)===TRUE){
echo "DATA updated";
}
?>
You can probably see I'm trying to create an individual variable for each row but I can't figure it out. Sorry, code's very messy too.
I've removed datebase information but the rows display when credentials are inserted.
This is because you have duplicated input ids, you should have only one ID with the same value on html, this is valid some how, you don't get an error, but you will have trouble in javascript when you try to access those id, you will get only the first one.
To fix this you can remove id and put it as class:
<div>
ID<input type="text" class="id" value="<?php echo $row['id']; ?>">;
Moderator<input type="text" class="mod" value="<?php echo $row['name']; ?>">;
Category<input type="text" class="ctgr" value="<?php echo $row['category']; ?>">;
<button type="submit" class="update" rel="<?php echo $run; ?>">UPDATE</button>
</div>
and use this JS:
$(document).ready(function(){
$(".update").click(function(){
var container = $(this).closest('div'); // parent div
var name = container.find('.mod').val();
var ctgr = container.find('.ctgr').val();
var id = container.find('.id').val();
$.ajax({
url:'update.php',
method:'POST',
data:{
name:name,
ctgr:ctgr,
id:id
},
success:function(response){
alert(response);
}
});
});
});
All your rows input elements have same id attribute
Like id of first rows elements are like id, mod, ctgr
Also id of second rows elements are id, mod ctgr
Jquery find first element, if multiple elements of same id there
You can make unique id by apppending a uniqe incremental variable $run to it as
ID<input type="text" id="id"+<?php echo $run; ?> value="<?php echo $row['id']; ?>">; Moderator<input type="text" id="mod"+<?php echo $run; ?> value="<?php echo $row['name']; ?>">; Category<input type="text" id="ctgr"+<?php echo $run; ?> value="<?php echo $row['category']; ?>">; <button type="submit" id="update" rel="<?php echo $run; ?>" onclick="updatetodb( <?php echo $run; ?>);“ >UPDATE</button>
Then create a javascript function with name updatetodb with one argument, and identify row by that argument as
function updatetodb(var run) {
var id=$('#id' +run).value;

Multiple ID's on single button click

HTML + PHP
<?php
for($i=0;$i<5;$i++){
?>
<input readonly class="copyTarget" id="copyTarget<?php echo $i; ?>" value="val<?php echo $i; ?>">
<span>
val<?php echo $i; ?>
</span>
<button class="btn btn-primary" id="copyButton<?php echo $i; ?>" onClick="reply_click(this.id, $('.copyTarget').attr('id'));">Copy</button>
<?php
}
?>
JS
<script>
function reply_click(clicked_id, target_id) {
alert(clicked_id);
alert(target_id);
}
</script>
What i want
I want to get the both values for copyTarget and copyButton as per loop cycle. It means
If current value of $i = 3
then I want alert values like,
clicked_id = copyTarget3
target_id = copyButton3
What i am currently getting is,
If current value of
$i = 3
then I want alert values like,
clicked_id = copyTarget0
target_id = copyButton3
Its taking first value of ID(copyTarget) stored initially. I want current loop cycle value.
Any help would do
Thanks
Why use JS in handler?
Try:
onClick="reply_click('copyButton<?php echo $i; ?>', 'copyTarget<?php echo $i; ?>')"
Also you should store id names (copyButton and copyTarget) in php variable, so you can change them in one place.
You could try something like below. However, I would go by Maxx's answer .. It really depends on what you plan to do with the rest of code etc.
<?php
for($i=0;$i<5;$i++){
?>
<div>
<input readonly class="copyTarget" id="copyTarget<?php echo $i; ?>" value="val<?php echo $i; ?>">
<span>
val<?php echo $i; ?>
</span>
<button class="btn btn-primary" id="copyButton<?php echo $i; ?>" onClick="reply_click(this)">Copy</button>
</div>
<?php
}
?>
<script>
function reply_click(btn) {
var clicked_id = $(btn).attr('id');
var target_id=$(btn).parent().find('span').html();
alert(clicked_id);
alert(target_id);
}
</script>
Try This
<?php
for($i=0;$i<5;$i++){
?>
<input readonly class="copyTarget" id="copyTarget<?php echo $i; ?>" value="val<?php echo $i; ?>">
<span>
val<?php echo $i; ?>
</span>
<button class="btn btn-primary" id="copyButton<?php echo $i; ?>" onClick="reply_click(this.id);">Copy</button>
<?php
}
?>
JS
<script>
function reply_click(clicked_id) {
alert(clicked_id); //clicked id
alert(clicked_id.split('copyButton').join('copyTarget')); // target id
}
</script>

Set value of input element using javascript and get the value using php

Here I have a form and input element:
cart.php
<form id="cartform" action="cart.php?action=update&pd=<?php echo $row['product_id'] ?>" name="form1" method="post">
<?php
$query = "select * from cart where customer_id='$user' ";
$result = mysqli_query($con,$query);$payableamount = 0;$totalsavings = 0;
while($row = mysqli_fetch_array($result))
{
$productid = $row['product_id'];
$query2 = "select * from product where product_id='$productid'";
$result2 = mysqli_query($con,$query2);
while($row2=mysqli_fetch_array($result2))
{
?>
<input tpe="text" name="quantxt[]" id="quantxt" value="<?php echo $qty = $row['quantity']; ?>" onkeyup="showsubmit(<?php echo $row['cart_id'] ?>,<?php echo $row['product_id'] ?>)">
<input type="text" name="s1" id="s1" value=""/>
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;"
type="submit"
name="sub_<?php echo $row['cart_id'] ?>"
id="sub_<?php echo $row['cart_id'] ?>"
value="UPDATE">
</table>
</form>
and the javascript is:
<script>
function showsubmit(id,prodid)
{
alert(id);
alert(prodid);
document.getElementById("sub_"+id).style.visibility ="visible";
document.getElementById("s1").value = prodid;
f = document.getElementById("s1").value;
alert("product id is:"+f);
}
</script>
when i am accessign the value of s1 element in cart2.php it gives nothing.
on next page s1 has no value,while i am expecting the value that is updated using javascript
$prod_id = $_POST['s1'];
echo "product id of clickable product is:".$prod_id."<br>";
this line:
<input type="text" name="s1" id="s1" value=""/>
is inside a loop. can you make sure that the loop only has one row returning? because if not, then you're creating multiple elements with same id which javascript can not catch properly. id is supposed to be unique. in the case of multiple same ids it'll catch the first match and stop.

jQuery set attribute onclick all elements instead of using inline JS

I have some inline JS that I'm having trouble changing over to jQuery. I would like to remove all the inline onclick events and target them all by class.
HTML - checkbox
<td class="center">
<?php if ($product['selected']) { ?>
<input type="checkbox" name="selected[]" id="<?php echo $product['product_id']; ?>_select" value="<?php echo $product['product_id']; ?>" checked="checked" />
<?php } else { ?>
<input type="checkbox" name="selected[]" id="<?php echo $product['product_id']; ?>_select" value="<?php echo $product['product_id']; ?>" />
<?php } ?>
</td>
HTML - inline JS
<input type="text" class="editable" name="<?php echo $product['product_id']; ?>_model" id="<?php echo $product['product_id']; ?>_model" value="<?php echo $product['model']; ?>" size="16" onclick='document.getElementById("<?php echo $product['product_id']; ?>_select").setAttribute("checked","checked");' />
The above code works but when I try to use jQueryversion 1.7.1 it breaks. Here is the code I have tried.
$(document).ready(function() {
$(".editable").live("click", function() {
$("#<?php echo $product['product_id']; ?>_select").attr("checked", "checked");
$("#<?php echo $product['product_id']; ?>_select").checked = true;
});
});
I'm not really familiar with jQuery but I think it's close. Any Ideas?
EDIT:
The problem is with the $("#<?php echo $product['product_id']; ?>_select") it works if hard coded. KevinB was correct even though ive never had this problem before but never used it within here $(element)
.live was deprecated in version 1.7 -- probably explains it. Use .on instead.
$(".editable").on("click", function() {
var name = '<?php echo $product['product_id']; ?>';
console.log("Name: " + name);
var el = $("#" + name + "_select");
console.log(el);
el.prop("checked", "checked");
});

handling multiple buttons with same name and value in one form

I have multiple submit buttons on a site. They used to move elements up and down and I want to be them in one whole form in case of the user changes meanwhile some other values so everything is saved. The Problem now is I need the element ID of the button which was clicked.
So here is the code in the loop :
div class="form-order"><?php echo $elements[$z]['element_order']; ?> </div>
<input type="submit" name="edit_form_operation" value="▲" class="button-primary"
<?php if($elements[$z]['element_order'] == 1) echo 'disabled="disabled"'; ?> /><br />
<input type="submit" name="edit_form_operation" value="▼" class="button-primary"
<?php
$highest_element = $fdb->get_element_highest_order($form[$i]['form_id']);
if($elements[$z]['element_order'] == $highest_element) echo 'disabled="disabled"'; ?> />
And onclick of that specific button in the for loop he should write this code first so I know which element has to be moved
echo '<input type="hidden" name="change_element_id" value="'.$elements[$z]['element_id'].'" >';
I'm also open for another solution of this problem.
Ok I solved it like that now
Here you process the input:
// Select Operation
if(isset($_POST['edit_form_operation_up'])) {
echo "move up id ";
$operation = array_keys($_POST['edit_form_operation_up']);
echo $operation['0'];
}
else if(isset($_POST['edit_form_operation_down'])) {
echo "move down id ";
$operation = array_keys($_POST['edit_form_operation_down']);
echo $operation['0'];
}
And this is in the for loop for infinite Elements the input with same value and name.
<?php $elements = $fdb->get_elements($form[$i]['form_id']);
for($z = 0; $z < sizeof($elements); $z++) {
?>
<tr>
<td><div class="form-order"><?php echo $elements[$z]['element_order']; ?> </div>
<input type="submit" name="edit_form_operation_up[<?php echo $elements[$z]['element_id']; ?>]" value="▲" class="button-primary"
<?php if($elements[$z]['element_order'] == 1) echo 'disabled="disabled"'; ?> /><br />
<input type="submit" name="edit_form_operation_down[<?php echo $elements[$z]['element_id']; ?>]" value="▼" class="button-primary"
<?php
$highest_element = $fdb->get_element_highest_order($form[$i]['form_id']);
if($elements[$z]['element_order'] == $highest_element) echo 'disabled="disabled"'; ?> />
</td>
<td><?php echo $elements[$z]['element_id']; ?> </td>
<td></td>
<td></td>
</tr>
<?php } ?>
In case of somebody finds this topic and want to find a good solution.
Greetings

Categories