1

I want to extract token from API using jQuery and then pass it to php location header parameter in URL.

Example:

<script>
$.getJSON('https://example.com/APIENDPOINT', function(data) {
    alert(data.access_token)
});
</script>

<?php
header('Location: https://example.com/auth/?access_token=${data.access_token}');
?>

I'm not sure what I am doing wrong, I would appericate if anyone can give me any tips.

SecurityQuy
  • 15
  • 1
  • 6
  • 3
    Well, first, PHP runs on the server to generate the page. Then Javascript runs on the web browser after it gets the page from PHP....... you cannot use js variables in php like this. – IncredibleHat Jan 11 '20 at 15:36
  • Ah, I see - could you please give me instructions or tutorial how would I achieve what I want? – SecurityQuy Jan 11 '20 at 15:39
  • Maybe `window.location.href = 'https://example.com/auth/?access_token=' + data.access_token;` in the function. Note your PHP attempt also wouldn't work because variables aren't expanded in single quotes. – user3783243 Jan 11 '20 at 15:41
  • Its hard to find a guide for something specific to what you want, as its unclear exactly your real end goal here. Are you determined to have PHP do the redirect, or are you wanting JS to do it... – IncredibleHat Jan 11 '20 at 15:41
  • Yes it has to be done with PHP redirect, is getting the token and then passing it to the parameter possible only with PHP? – SecurityQuy Jan 11 '20 at 15:44
  • I would also suggest that you look through the answer on this question: [What is the difference between client-side and server-side programming?](https://stackoverflow.com/a/13840431/2453432) – M. Eriksson Jan 11 '20 at 15:51
  • I figured it out by using PHP curl, extracting the token and passing the variable to header location. Thanks for help :) – SecurityQuy Jan 11 '20 at 16:04
  • Does this answer your question? [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – user3783243 Jan 11 '20 at 16:09

1 Answers1

0

MayBe like this:

$.getJSON('https://example.com/APIENDPOINT', function(data) {
    window.location.href = 'https://example.com/auth/?access_token=' + data.access_token;
});

if need 301 redirect then run on server side only(php)

<?php
  $json = file_get_contents('https://example.com/APIENDPOINT');
  $obj = json_decode($json);
  $token =  $obj->access_token; 
  $url = 'https://example.com/auth/?access_token=' . $token ; 
  header("Location: ".$url, true, 301);
  exit();
?>
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17