16

I suppose what I am asking is really easy for most of you. I want to reload a div without reloading the entire page. What's the best way to do it?

<div class="black_text" id="cp_in_content_div">
<?php
$id = $_GET["id"];
$result = mysql_query("SELECT * FROM Setting WHERE ID = $id");
$row = mysql_fetch_array($result);
switch ($_GET["action"])
{
    case "delete":
    if (!unlink("$_SERVER[DOCUMENT_ROOT]setting/$row[Filename]"))
    {
        echo "Error.";
        header("Refresh: 2.5; URL=delete_setting.php?id=$id");
        exit();
    }
    if (!mysql_query("DELETE FROM Setting WHERE ID = $id"))
    {
        echo "Error.";
        header("Refresh: 2.5; URL=delete_setting.php?id=$id");
        exit();
    }
    else
    {
        echo "Ok!";
        header("Refresh: 1.25; URL=index.php");
    }
    break;
    default:
    echo "form";
}
?>
</div>

I need those header("Refresh:...") to only reload the div instead of the page.

Gabriele
  • 161
  • 1
  • 1
  • 4

4 Answers4

24

jQuery.load() is probably the easiest way to load data asynchronously using a selector, but you can also use any of the jquery ajax methods (get, post, getJSON, ajax, etc.)

Note that load allows you to use a selector to specify what piece of the loaded script you want to load, as in

$("#mydiv").load(location.href + " #mydiv");

Note that this technically does load the whole page and jquery removes everything but what you have selected, but that's all done internally.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • How do I show a "loader.gif" until entire div is not loaded. Because my div is very huge and coming from a file. So it takes about 2 seconds. How to I show something like `loading...` until jquery completes the task. – ajinzrathod Nov 19 '20 at 11:49
  • is there an option to load by tag not by id !? – Yasmine Sep 07 '21 at 11:24
  • @Yasmine you can use any valid selector, even `$("div").load` should work, but keep in mind that this will select _all_ divs on the page and trigger the load – Explosion Pills Sep 09 '21 at 13:46
8
$("#div_element").load('script.php');

demo: http://sandbox.phpcode.eu/g/2ecbe/3

whole code:

<div id="submit">ajax</div> 
<div id="div_element"></div> 
<script> 
$('#submit').click(function(event){ 
   $("#div_element").load('script.php?html=some_arguments');  

}); 
</script> 
genesis
  • 50,477
  • 20
  • 96
  • 125
5

Use this.

$('#mydiv').load(document.URL +  ' #mydiv');

Note, include a space before the hastag.

praveena
  • 222
  • 3
  • 6
1

write a button tag and on click function

var x = document.getElementById('codeRefer').innerHTML;
  document.getElementById('codeRefer').innerHTML = x;

write this all in onclick function

GMchris
  • 5,439
  • 4
  • 22
  • 40
  • hi, I tried this for updating a table. but it seems like the table is still the same as before. No update in the table data, even though new data is added to the table. @Ambala Chandrashekar – Rubel May 31 '21 at 13:28