0

I have an API which has an example written in PHP. Unfortunately I need to write in in JavaScript but lack the knowledge to convert it myself.

Are there any online converters or documentation which may be able to help me?

Taking an example I have tarted but cannot finish as I do not understand the php code:

PHP:

//Creates a HTTP Request by given URL & arguments.
function httpGetT($url, $arg = '') {
    $sargs = '';
    if(is_array($arg)) {
        foreach($arg as $k => $v) {
            if(strlen($sargs)) $sargs .= '&';
            $sargs .= $k.'='.urlencode($v);
        }
    }
    if(strlen($sargs)) $sargs = '?'.$sargs;
    $file_stream = @fopen($url.$sargs, 'r');
    if($file_stream) {
        $response = '';
        while($data_row = fread($file_stream, 1024)) {
            $response .= $data_row;
        }
        fclose($file_stream);
        return $response;
    }
    else {
        return false;
    }
}

JavaScript:

function HttpGet(url, arg) {
  var args = ''; 
  if (arg == Array) {
    $.each(arg, function() {
      if (arg.length > 0) {
      }
    });
  }
}

Of course if there is any documentation which can help me as there is a lot of code to copy and transfer.

  • You can't really do a simple conversion of this code. In Javascript, HTTP calls are asynchronous, which requires significant refactoring of the code. – Barmar Oct 21 '15 at 09:47
  • What would be the suggestion then? To talk to the someone and let them know the process will be long and possibly not work? – James Michael Lucas Oct 21 '15 at 09:52
  • Will you be running it in the browser or on a server using something like Node.js? In a browser, you might not even be able to call the API because of the AJAX same-domain restriction. – Barmar Oct 21 '15 at 09:55

2 Answers2

1

Try this looking for transpiler: php to javascript and http://asmblah.github.io/uniter/

If you use "browser javascript" (not node.js) you need to know that javascript don't have analog $file_stream = @fopen($url.$sargs, 'r'); for security reason. Another words - you can't open any file on user machine.

Community
  • 1
  • 1
DLevsha
  • 136
  • 3
0

According to your code. it looks like you're using jQuery. Why not just :

function HttpGet(url, arg) {
   if(arg instanceof Array){ // Check if argument is set and is array
       $.ajax({
          type:'GET', // You can use POST
          data:arg,
          success:function(response){
              // do something
          }
       });
   }
}
Mike
  • 1,231
  • 12
  • 17