Ahmadz Issa Ahmadz Issa - 6 months ago 13
Ajax Question

Can't send element id data using ajax

I'm trying to send id data through ajax, but I always get undefined variable error.
ajax works fine with forms data, but when I try to get the id value this problem occurs.

PHP/ html code

<ul class="sub-menu">
<?php
$get_cats = retrieve_cat();
while($cat_rows = mysqli_fetch_array($get_cats)){

$id = $cat_rows['category_id'];
$title = $cat_rows['category_name'];
echo "<li><a herf='post_category.php' class='abc' data-id='$id' id='$id' data-target='post_category'> $title </a></li>";
}
?>
</ul>


JQuery :

$(".abc").click(function () {
var id = $(this).attr("id");
edit_data(id);

function edit_data(id)
{
$.ajax({
url:"post_category.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
}
});
}
});


And the post_category.php page just to echo the value to test it :

echo $_POST['id'];


The problem I get this error as I said :


Notice: Undefined index: id in C:\xampp\htdocs\unv\post_category.php on line 6



But in success function I get the correct value. I don't know where's the problem!.

This's a picture for more explanation

http://store2.up-00.com/2016-05/1464026786681.png

Answer

Because you're including post_category.php in your page so it'll try to echo the id when it's not there because id will be available just after the click so you have to add a span instead of including the post_category.php page :

<span id="my-id-here"></span>

Then append id to it on success callback :

....
success:function(data){
    $('#my-id-here').append(data);
}

Hope this helps.

Comments