简体   繁体   中英

PHP AJAX CALL using XMLHttpRequest

I'm working on a PHP project and need to do an ajax call however it's set up in such a way that "ve never seen before. I have one file: index.php that looks like this:

echo '<input id=ajax_redraw name=ajax_redraw type=button value="Redraw" onclick="ajaxTest()" />';
echo '<div id=destination_div name=destination_div class=ajax_test >';
echo '</div>';

echo end_page();

function redraw_destination_div()
{
    global $db;

    $select = $db->select()
                ->from( EPRESCRIBING_ERROR_MESSAGES, 'error_message' );
    $errors = $db->fetchCol( $select );

    $random_key = rand( 0, (count($errors)-1) );
    $errror_message_for_destination_div = $errors[$random_key];

}

I need to show the variable $errror_message_for_destination_div on the div with the id of destination_div.

My javascript code looks like this:

function ajaxTest() {

  // Getting the specific div to target
  var targetArea = document.getElementById("destination_div");
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST", "ajax_test.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 || this.status === 200){ 
        targetArea.innerHTML = 'SEE ME';
        console.log(this.responseText); // echo from php
    }       
  };
  xmlhttp.send(); 


}

I can display the 'See Me' text no problem. I just need to know how to call and display the response from the PHP function redraw_destination_div. Thank you for any help.

You need to rewrite the PHP.

HTTP requests are made to URLs, not functions.

You need a URL which you can make a request to get the data you need (and only the data you need).

Currently you have a PHP program which:

  • Outputs a <div> you don't want in the Ajax response.
  • Creates a function which stores the data you want in a variable.
  • Doesn't call that function.
  • Doesn't output the contents of the variable in the response.

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