Joe Riggs
Joe Riggs

Reputation: 1324

Javascript Returing Value from httprequest

The php script is returning a value and the 1st alert works.

I am unable to reference the value returned by httprequest at the 2nd alert. Ideally, I would call the function get_captcha() - and it would return the value - its just that I dont know how to do this.

I realize setting the variable globally may not be the best way to do this but its the only thing I could think of - Im open to alternatives.

  <script type="text/javascript">
   var url = "captcha_get_code.php"; // The server-side script 
   var cap;

   function ValidateForm() {
    get_captcha()
    alert(cap); //undefined

    }

    function get_captcha() {      
      http.open("GET", url, true); 
       http.onreadystatechange = handleHttpResponse; 
       http.send(null); 

}

  function handleHttpResponse() {    
    if (http.readyState == 4) { 
       if (http.status==200) { 
            //return http.responseText; 
        cap=http.responseText; 
            alert(cap);  //this one works
            }

        } 
    } 



function getHTTPObject() { 
  var xmlhttp; 

  if(window.XMLHttpRequest){ 
    xmlhttp = new XMLHttpRequest(); 
  } 
  else if (window.ActiveXObject){ 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    if (!xmlhttp){ 
        xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
    } 

} 
  return xmlhttp;   
} 
var http = getHTTPObject(); // We create the HTTP Object 





</script>   

Upvotes: 0

Views: 7497

Answers (2)

Edgar
Edgar

Reputation: 11

I see this thread is 4 years old, but it has wrong answer!

You can get return value from a successful XMLHttpRequest invocations. My project use WebSocket, but it use XMLHttpRequest to upload images.

    In a javascript, call uploadSend(containerID) where all <img> are stored.


    // ----- uploadSend()
    // ----- This function sends all objects in a container (containerID)
    // ----- All object has to be <img>

FILE: upload.js

    function uploadSend(containerID) {
      var elm = document.getElementById(containerID);
      for (i=0; i<elm.childNodes.length; i++) {
        var form = new FormData();
        form.append('id', elm.childNodes[i].id);
        form.append('src', elm.childNodes[i].src);
        TOS(form);
      }
    }

    function xhrState(self) {
      if ((self.readyState == 4) && (self.status === 200))
        console.log(self.responseText);
    }

    function xhrProgress(event) {
      if (event.lengthComputable)
        if (event.loaded == event.total)
          console.log('Image 100% uploaded.');
    }

    function TOS(form) {
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function () { xhrState(this); }
      xhr.open('POST', '/upload.php');
      xhr.upload.onprogress = function(event) { xhrProgress(event); }
      xhr.send(form);
    }

FILE: upload.php

    header("Content-type: text/plain");

    $filename = '/var/www/public/upload/'.microtime(true);

    // ----- Save a complete file for what we did get.
    $hnd = fopen($filename . 'TXT', 'wb');
    fwrite($hnd, print_r($_COOKIE, true));
    fwrite($hnd, print_r($_GET, true));
    fwrite($hnd, print_r($_FILES, true));
    fwrite($hnd, print_r($_POST, true));
    fclose($hnd);

    // ----- Save just jpg for the images we did get.
    $hnd = fopen($filename . 'jpg', 'wb');
    $image = explode(',', $_POST['src']);
    fwrite($hnd, base64_decode($image[1]));
    fclose($hnd );

    // ----- Type the result that you want back.
    echo "{$filename}.jpg";

Upvotes: 1

Pointy
Pointy

Reputation: 413702

You cannot "return" values from successful XMLHttpRequest invocations. You can perform whatever sort of processing you need inside the callback function.

XMLHttpRequests are performed asynchronously. You cannot make your code "wait" for them (unless you make them synchronous) (and you really, really should not do that). There's no real need, however, because the runtime system will call your "readystatechange" handler when the request completes. From in that code, you're free to do whatever you need.

This fact requires you to think a little differently about how to write the code, but it's not really that much of an adjustment. If, for example, you would be inclined to write a "processResults()" function, then you can still do that — you would simply call that from inside the "readystatechange" handler.

Upvotes: 6

Related Questions