Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change DIV content using ajax, php and jQuery

I have a div which contains some text for the database:

<div id="summary">Here is summary of movie</div>

And list of links:

<a href="?id=1" class="movie">Name of movie</a>
<a href="?id=2" class="movie">Name of movie</a>
..

The process should be something like this:

  1. Click on the link
  2. Ajax using the url of the link to pass data via GET to php file / same page
  3. PHP returns string
  4. The div is changed to this string
like image 556
Luis Avatar asked Sep 10 '25 16:09

Luis


2 Answers

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",
     url: 'Your URL',
     data: "id=" + id, // appears as $_GET['id'] @ your backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

And add onclick event in your lists

<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>
like image 61
anasanjaria Avatar answered Sep 12 '25 08:09

anasanjaria


You could achieve this quite easily with jQuery by registering for the click event of the anchors (with class="movie") and using the .load() method to send an AJAX request and replace the contents of the summary div:

$(function() {
    $('.movie').click(function() {
        $('#summary').load(this.href);

        // it's important to return false from the click
        // handler in order to cancel the default action
        // of the link which is to redirect to the url and
        // execute the AJAX request
        return false;
    });
});
like image 27
Darin Dimitrov Avatar answered Sep 12 '25 09:09

Darin Dimitrov