Replacing content using AJAX when clicking a link

General Tech Learning Aids/Tools 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Learning Aids/Tools related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I want to use AJAX to replace the contents of a div. Although the application is fairly complex, I have tried to dumb it down in isolation so that I can get the basic concept working first.

For now, I just want to replace a div as per the PHP file...

php 
$id = $_GET['id'];
if ($id = 1)
    {
        $text = 'This is some text';
    }
elseif ($id = 2) {
    {
        $text = 'This is a lot more text than the first text!';
    }
elseif ($id = 3) {
    {
        $text = 'This is a lot more text than the first text, and a load more than the third as well!!';
    }
echo $text; 
?>

Fairly simple stuff really. So here's my HTML file...






<body>

 id="myDiv">I want this content replacing
href="#" onclick="loadXMLDoc()">ID: 1
href="#" onclick="loadXMLDoc()">ID: 2
href="#" onclick="loadXMLDoc()">ID: 3 body>

I realise what is there will never work as I've modified some stuff I found online, but basically I'm looking to pass a variable such as the ID in the link to the AJAX script to replace the contents of the div.

How do I get this working? Is there a better alternative to using  tags?

profilepic.png
manpreet 2 years ago

Using jQuery

Your HTML

 href="#" class="ajax" data-id="1">ID: 1

Javascript

// Delegate click event
$(document).on('click', 'a.ajax', function(){

    var el = $(this);
    $.ajax({
        url: 'ajax.php',
        data: {id: el.data('id')},
    }).done(function(response){
        $('#myDiv').html(response);
    });

});

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.