简体   繁体   中英

How to get return text from php file with ajax?

I am making a call with ajax to a php file. All I want to do is get a value back from the php file to test it with javascript. I have tried many many things, but can only get undefined (from the below code).

How can I get "hello" returned from the php file to my javascript?

jQuery.ajax({
   type: "POST",
   url: "the_file_to_call.php",
   data: {userid: group_id_tb},
   success: function(data) {
        var the_returned_string = jQuery(data).html();
        alert(the_returned_string)
    }
});

The PHP file:

<?php
echo '<div id="id-query-result>"';
echo "hello";
echo "</div>";

You can change the code inside PHP like this

<?php
$queryResult = '<div id="id-query-result">hello</div>';

echo json_encode(['html' => $queryResult]);

Then, change your ajax call

jQuery.ajax({
   type: "GET",
   url: "the_file_to_call.php",
   data: {userid: group_id_tb},
   dataType: 'json',
   success: function(data) {
        var the_returned_string = data.html;
        alert(the_returned_string);
   }
});
$.ajax({
  type: "POST",
  url: "the_file_to_call.php",
  data: {userid: group_id_tb},
  success: function(data) {
      $('body').append(data);
      var text = $('#id-query-result').text();
      alert(text);
      $('#id-query-result').remove()
  }
});

Why not just append the HTML response of your php file then get the text accordingly. You can then remove it after.

There are two changes to be done:

  1. Change the type to "GET" since you directly call the PHP File.
  2. remove the wrapped jQuery method inside the success function and add .html as an attribute
jQuery.ajax({
   type: "GET",
   url: "the_file_to_call.php",
   data: {userid: group_id_tb},
   success: function(data) {
        var the_returned_string = data.html
        alert(the_returned_string)
    }
});

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