0

I am learning PHP and jQuery. I have a PHP file called renderPicture.php that returns a dynamically created image in an HTML IMG tag. I want to change that image after a click event on my webpage -- without reloading the page. I know that I need a jQuery Ajax call to renderPicture. And I know that I need to set the inner HTML of my div to the result of that jQuery Ajax call. I learned how to set inner HTML here How to replace innerHTML of a div using jQuery? But I am not quite sure how to do this with the AJAX call.

How to I set the inner HTML of a DIV to the output of a PHP file using jQuery?

Here is the jQuery and some of the HTML:

<script>

$(document).ready(function(){
   $("#myDIV").click(function(){
        //var resultOfAjaxCall = $.ajax({ url: './renderPicture.php',});
        $("#myDIV").html(resultOfAjaxCall); //This is roughly what I want to do
    });
});

</script>

</head>
<div id='myDIV'>
<?php 
$cryptinstall="./renderPicture.php";
include $cryptinstall; 
?>
</div>
</html>

Here is renderpicture.php

<?php

$cryptinstall="./cryptographp.fct.php";
include $cryptinstall; 
if(session_id() == "") session_start();
$_SESSION['cryptdir']= dirname($cryptinstall);
$cfg=0;
echo "<img id='cryptogram' src='".$_SESSION['cryptdir']."/cryptographp.php?cfg=".$cfg."&".SID."'>";
 ren
?>
Community
  • 1
  • 1
bernie2436
  • 22,841
  • 49
  • 151
  • 244

3 Answers3

3

Use .load():

$(document).ready(function(){
   $("#myDIV").click(function(){
        $("#myDIV").load('renderPicture.php');
    });
});

This is shorthand for:

$(document).ready(function(){
   $("#myDIV").click(function(){
        $.ajax({
            url: './renderPicture.php',
            success: function(resultOfAjaxCall) {
                $("#myDIV").html(resultOfAjaxCall);
            }
        });
    });
});

Whenever you want to do something with the result of an AJAX call, you have to do it in the callback function.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

If I am guessing correctly ,You need load()

Load data from the server and place the returned HTML into the matched element.

  $("#myDIV").load('qualifiedFilePath');
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Use jQuery.get() to make an ajax request.

$.get('ajax/test.html', function(data) {
  $('#myDIV').html(data);
  alert('Load was performed.');
});
Hirshy
  • 367
  • 3
  • 16