简体   繁体   中英

Refresh <div id=“RefhreshableDiv”> content on button click

Let me get straight to the point.
Somewhere in my website i have the following code:

<?php  
echo '<div id="RefreshableDiv">';
/* performs changes to database,
   depending on whether button1 was clicked or not 
   with the help of: if (isset($_POST['button1'])) */

/* retrieves information from database */   

/* creates a button with id="button1", with background image 
   depending on retrieved database information */

echo '</div>';
?>

I am trying to give my site the following functionality:

  • User clicks button1
  • only the part of the page inside <div> with id "RefreshableDiv" gets refreshed (and as a result button1 background image changes.)

Is what I am trying to do even possible ? I am expecting the usage of ajax, i think.

ok first have a page where there is the database changes and stuff you need and name it something like : pagerefrech.php lest say its code is the folowing :

<?php 
//selecting fr database and doing what do you want to do
//this page will return whats gonna be inside the div
//to get the parameter sent by $.post you use $_POST['nameofparam']
//exemple : 
  echo "THIS IS THE CONTENT OF THE DIV";
?>

and your button cilck event is :

$('#button').click(function(){
    $.post(//or $.get if you want to use GET request
    "pagerefrech.php",//path to teh page
    {
    param1  : value1 ,
    param2 : value2//for sending some post vars if you dont want to set it to null
    },
    function(data){//data contains the contenet returned by the page "pagerefrech.php"
    $('#RefreshableDiv').html(data);
    //change here the background image of the button
    $('#button1').css({"background-image" : "yourvaluegoeshere"});
    });//end of $.post function
});//end of button1.click

Explaining : $.post send a POST request to the page pagerefrech.php nad get the result param1 and param2 and param3..... are paramers you can add them to send them to the page if not you can let it as {} without anything inside , this will be exactly like you are sending POST variables like input or select values.

SIMPLE EXEMPLE : create a page named test.php with this code :

<?php echo "cotent recieved"; ?>

create an html page with this code

<html>
<head>
</head>
<body>
<input type="button" value="test" id="but1" />
<div id="refrech"></div>
<script>
$(document).ready(function(){
 $('#but1').click(function(){
        $.post(
        "test.php",
        {
        },
        function(data){
        $('#refrech').html(data);
        });
    });
});
</script>
</body>
</html>

PS : dont forget to add the jquery library to the page in your test hope it was clear

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM