0

I'm trying to display response of PHP script within a div element <div id="divname"></div>

jQuery('#divname').load('TEST.php',{
  'id' : id
});  

My code works as expected and successfully insert «1» inside this div.

TEST.php file:

<?php
  echo '1';
?>

...but I would also like to alert the response in the same time using jQuery, someting like this:

jQuery('#divname').load('TEST.php',{
  'id' : id
}, 
alert(response); //????
);  

Can You help me?

Stphane
  • 3,368
  • 5
  • 32
  • 47
AoW
  • 55
  • 1
  • 6
  • 1
    Use `$.get` with a callback or `$.ajax`. – u_mulder Sep 15 '17 at 12:57
  • I would also suggest to use `$.get` or `$.ajax`, than you can also check if the action executed, failed, succeeded, and more. See the documentation: http://api.jquery.com/jquery.ajax/ – GreyRoofPigeon Sep 15 '17 at 13:00
  • 1
    Possible duplicate of [Using jQuery load with promises](https://stackoverflow.com/questions/6507181/using-jquery-load-with-promises) – Script47 Sep 15 '17 at 13:01

3 Answers3

2

As already commented, I would use $.ajax for this action:

$.ajax({
  url: "TEST.php"
})
  .done(function( data) {
    // alert( "Returned data: " + data );
    $('#divname').html(data);
  })
  .fail(function() {
    alert( "Loading failed" );
  });

You can then check if the action succeeded (done) or failed (fail).

In the done function, data is the data that returns from the request.

GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
1

Use the callback function , documentation

jQuery('#divname').load('TEST.php',{
       'id' : id
  },  function() {
  alert( "Load was performed." );
});
Renzo Calla
  • 7,486
  • 2
  • 22
  • 37
0

Check out this post about how callbacks work. The code below should work as you're expecting.

jQuery('#divname').load('TEST.php',{
    'id' : id
}, response => alert(response));
Dexter
  • 175
  • 1
  • 12