GRFF
GRFF

Reputation: 67

I am geting "undefined" with this javascript. Why?

I have been digging around for 4 hours now and I decided to ask, as I can't get my head around this.

I have the following in one page:

support.php:

<div id="userID"><?= $dataOwner =></div>
<a class="nav-link" href="JavaScript:void(0);" id="showOpen">Open</a>
<script src="js/tickets.js></script>

In the above page (support.php), $dataOwner returns a value correctly. When clicked, the link must call the "js/tickets.js" script in which I have the following:

tickets.js:

$("#showOpen").click(function(){ 
    $.ajax({
        type: "POST",

        url: 'https://[redacted]/load_tickets.php?user='+$('#userID').val(),
            success:function(data) {
                document.getElementById('openTickets').innerHTML = data;
            }
    });
});

but the value of #userID is always undefined. Why is this and what am I doing wrong?

Upvotes: 1

Views: 65

Answers (1)

treyBake
treyBake

Reputation: 6558

firstly, don't use shorthand in php - might cause errors when moving servers at any point.

secondly.. no inline JS!!!

and lastly, you're using url params for a post method.

How I'd do it (and how I'd recommend):

[support]

<div id="customer" data-id="<?php echo $dataOwner; ?>">
    <?php echo $dataOwner; ?>
</div>

<a href="#" class="nav-link" id="showOpen">Open</a>

<script>
    $(document).ready(function()
    {
        $('#showOpen').on('click', function()
        {
            $.ajax({
                data: {user: $('#customer').data('id')},
                dataType: 'json',
                type: 'post',
                url: '/your/path/to/load_tickets.php',
                success: function(data)
                {
                    $('#openTickets').html(data)
                }
            });
        });
    });

then no need for tickets.js (in this case)

this will post the data to the file as $_POST (array) where you can use $_POST however you want :)

Upvotes: 1

Related Questions