简体   繁体   中英

Is it possible to pass var received from API call in Javascript to php?

I am making an API call and receive a response. I save some part of the response in a variable in Javascript. I would like to pass that variable to a php file "main_page.php". I was trying to use ajax inside the function to use the variable and pass it to the php file and then echo it in php file but it doesn't seem to work. Is is even possible? If so can you please tell me how. Thanks!

This is my javascript file that makes an API call and returns a response body. I am trying to pass var urlVal to my php file. I don't need to print it out in php. it is just for testing purposes. I echo it to make sure it s there. So far I am unable to pass it to php as i dont see anything printed out in the console.

document.addEventListener('DOMContentLoaded', bindButtons); 

    function bindButtons(){
            document.getElementById('submit').addEventListener('click',function(event){

                    var req = new XMLHttpRequest();
                    req.open("GET","https://api.nasa.gov/planetary/apod?api_key=" + apiKey, true);


                    req.addEventListener('load', function(){
                    if(req.status >= 200 && req.status < 400)
                        {
                            var response = JSON.parse(req.responseText);
                            console.log(response);
                            var urlVal = document.getElementById('showname').textContent = response.hdurl;


                            $.ajax({
                             type: 'POST',
                             url:'main_page.php', 
                                 data:{
                                    'total' : $("#showname").textContent(),},
                                 success: function(response){
                            }} );

                    req.send(null);


                    event.preventDefault(); }
                    )
                    }

This is some of the code i have in my php file "main_page.php" :

<div id= "second">
            <h2>PREVIEW</h2>
            <p class = "api_desc"> <span id= "showname"> <span> </p> 
        </div>
<?php

        echo $_POST['total'];
?>

Yes, this is possible. Although, what exactly is to be accomplished is unclear. Here is one working approach to build off of...

main_page.php:

<?php
      if($_SERVER['REQUEST_METHOD'] === 'POST') {
        echo $_POST['total'];
      }
?>

index.html:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
  <button id='submit'> SUBMIT! </button>
  <BR><BR><BR>
  <div id= "second">
    <h2>PREVIEW</h2>
    <p class = "api_desc"> <span id= "showname"> </span> </p> 
  </div>
</body>

<script>
document.addEventListener('DOMContentLoaded', bindButtons); 
function bindButtons(){
    document.getElementById('submit').addEventListener('click',function(event){
        var req = new XMLHttpRequest();
        req.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              var response = JSON.parse(req.responseText);
              console.log(response.hdurl);
              var urlVal = document.getElementById('showname').innerText = response.hdurl;
              //console.log($("#showname").text());

              $.ajax({
                type: 'POST',
                url:'main_page.php', 
                data: {'total' : $("#showname").text()},
                success: function(response,status,xhr){
                    alert(response)
                }
              });
          }
        };
        req.open("GET", "api.json", true);
        req.send();
      });
    }
</script>
</html>

api.json:

{"id":"one","data":"stuff","hdurl":"http://www.example.com/"}

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