Rimsha Miraj
Rimsha Miraj

Reputation: 23

Ajax Call in Javascript Function On Button Click

I am getting an error in this code which says Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick.I cannot figure out where i am going wrong. Here is my code which contains a while loop which fetches data from the database and $xyz goes to the javascript function called myFunction().

Here is my file:

if($rs->num_rows>0)
{
while($row=$rs->fetch_object())
{

            $xyz=$row->judged_id;

            $my="SELECT DISTINCT first_name,picture from user1 where id='$xyz'";

            $hj=$con->query($my);

            if($hj->num_rows>0)
            {
                while($rz=$hj->fetch_object())
                {
                    echo $name=$rz->first_name;

                    $pic=$rz->picture;


                    echo"<img src='$pic' height=100 width=100>";

                    ?>
                    <button type='button' class='egf' onClick="myFunction('xyz')">Chat</button>
                    <br><br>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

  <script>
  var xyz=<?php echo $xyz; ?>;

  function myFunction('xyz')
   { 


    $.ajax({
            type: 'GET',
            url: 'chat/public/01_index.php?id2=xyz',
            success: function(data) {

    $('.chat-list').html(data);
    }
    });

    });

    }
  </script>




  <?php

            } 
        }

Upvotes: 0

Views: 3744

Answers (2)

Marcel
Marcel

Reputation: 5119

First of all: you don 't need jQuery. The jQuery library is just a wrapper written in native javascript. It would be more performant to use native javascript.

After that as I mentioned in the comments, you should use a click event listener on the parent element, which contains all your buttons. Just have a look at the following example.

<div class="parent-element">
<?php
while ($row = $resource->fetch_object())
{
    echo '<button id="' . $row->id . '">' . $row->title . '</button>;
}
?>
</div>

<script>
    var parent = document.querySelector('.parent-element'),
        xhr = new XMLHttpRequest();

    parent.addEventListener('click', function( event ) {
        let target = event.target;
        if (target.tagName.toLower() == 'button' && target.id) {
            // your xml http request goes here
            xhr.open('GET', yoururl + target.id);
            xhr.onload(function() {
                if (xhr.status === 200) {
                    // do something with the response
                    let response = xhr.responseText;
                }
            });
            xhr.send();
        }
    }, true);
</script>

The while loop adds the buttons to your HTML markup. Further a click event listener was added to the parent div element. On every click it checks, if the target element is a button and if this button has an id attribute. If so an asynchronous request is executed.

Upvotes: 0

Marijan
Marijan

Reputation: 1865

What is the content of the PHP variable $xyz? If it is a string, for example, this:

var xyz=<?php echo $xyz; ?>;

Would result in a JavaScript like:

var xyz=ABCDEFG;

Which is not valid. Instead it should then be:

var xyz = '<?php echo $xyz; ?>';

Furthermore your function defintion seems not right, should be something like this instead, since you can not specify a string as a parameter name:

function myFunction(varNameHere)
{ 
    alert(varNameHere);   
}
<a href="javascript:myFunction('Test')">Click me</a>

Also you are using jQuery ready() function inside your function, which will probably not fire at anytime.

I think what you are looking for is something like this:

function myFunction(xyz)
{ 
    $.ajax({
            type: 'GET',
            url: 'https://httpbin.org/get?q=' + xyz,
            success: function(data) {
                $('.chat-list').html(data.args.q);
            }
    });

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:myFunction('stackoverflow')">Click me</a>
<div class="chat-list">

</div>

Upvotes: 1

Related Questions