Jump to content

Problem retrieving data using jQuery AJAX request with PHP proxy


Recommended Posts

I'm interviewing for a company and they've given me a take home assignment that I have unlimited time to complete. One of the specifications is that I use a PHP API proxy to get around CORS for their API. I'm not permitted to use any PHP or JS libraries for this, aside from JQuery. I'm very new to PHP and am used to fetching data with React, so I feel a little out of my element. I've found what looks to me like it should be a solution here:

https://github.com/joseftw/php-rest-proxy

...but I can't get it to work. Whenever I load the page and check the console, it just stays <empty string> for both GET and POST requests (on Firefox). I know the calls are firing because they do perform console.log('test') if I add that. So then where's the data?

Here's the code for my PHP proxy file:

<?php

  $url = $_REQUEST["url"];

  if(!$url) {
    echo "You need to pass in a target URL.";
    return;
  }

  $response = "";
  switch (getMethod()) {
    case 'POST':
      $response = makePostRequest(getPostData(), $url);
      break;
    case 'GET':
      $response = makeGetRequest($url);
      break;
    default:
      echo "This proxy only supports POST AND GET REQUESTS.";
      return;
  }

  echo $response;

  function getMethod() {
    return $_SERVER["REQUEST_METHOD"]; 
  }

  function getPostData() {
    return http_build_query($_POST);
  }

  function makePostRequest($data, $url) {
    $httpHeader = array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data));
    
    return makePutOrPostCurl('POST', $data, true, $httpHeader, $url);
  }

  function makeGetRequest($url) {
    $ch = initCurl($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
  }

  function makePutOrPostCurl($type, $data, $returnTransfer, $httpHeader, $url) {

    $ch = initCurl($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, $returnTransfer);
    
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
  }

  function initCurl($url) {
    $httpHeader = array(
    'Content-Type: application/x-www-form-urlencoded');

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36');

    return $ch;
  }


?>

And here are my AJAX requests in my script.js file:

$(document).ready(function () {
	$.ajax({
		url: 'proxy.php?url=https://reqres.in/api/users',
		type: 'POST',
		data: { name: 'Zlatan Ibrahimovic' },
		success: function (data) {
			console.log(data);
		},
	});

	$.get('proxy.php?url=https://reqres.in/api/users?page=2', function (data) {
		console.log(data);
	});
});

The endpoint I've provided is from a sample API and not the company's API. Still, I can't get the proxy/AJAX combo to work with anything. This is day 2 of this and I'm spinning my wheels. Can anyone point me in the right direction? Am I totally off-base with the PHP proxy setup, or is it something else?

So I ended up figuring this out. Here's my PHP and JS:

 

<?php

// getting the baseURL from the request
$baseURL = $_REQUEST['url'];

// getting the request method sent in to the proxy
function getRequestMethod() {
  return $_SERVER["REQUEST_METHOD"]; 
}

// getting the POST data from a POST request
function getPostData() {
  return http_build_query($_POST);
}


function makeGetRequest($baseURL) {
  $ch = curl_init();
  $fullURL = $baseURL.<URLparams here>; 

  curl_setopt($ch, CURLOPT_URL, $fullURL);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

  $response = curl_exec($ch);
  curl_close($ch);
  
	if($e = curl_error($ch)) {
		echo $e;
	} else {
    $json = json_decode($response, true);
    return print_r($json);
	}
}

function makePostRequest($baseURL) {
	$ch = curl_init();
  $data = http_build_query($_POST);

  curl_setopt($ch, CURLOPT_URL, $baseURL);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $response = curl_exec($ch);
  curl_close($ch);

	if($e = curl_error($ch)) {
		echo $e;
	} else {
    $json = json_decode($response, true);
    return print_r($json);
	}
}

$response = "";
switch (getRequestMethod()) {
  case 'GET':
    $response = makeGetRequest($baseURL);
    break;
  case 'POST':
    $response = makePostRequest($baseURL);
    break;
  default:
    echo "There has been an error";
    return;
}

echo $response;
 

 

JS:

$(document).ready(function () {
	$.ajax({
		url: 'proxy.php?url=<Endpoint here>',
		type: 'POST',
		data: {
			partnerName: 'applicant',
			partnerPassword: 'd7c3119c6cdab02d68d9',
			partnerUserID: 'expensifytest@mailinator.com',
			partnerUserSecret: 'hire_me',
		},
		success: function (data) {
			console.log(data);
		},
	});
	$.get(
		'proxy.php?url=<Endpoint here>',
		function (data) {
			console.log(data);
		}
	);
});

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.