'Transfer data between JavaScript and PHP through JSON

index.html:

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <form method="post" class="set-currency">
        <div class="usd">
            <label for="usd">USD</label>
            <input type="number" name="usd" id="usd">
        </div>
        <div class="eur">
            <label for="eur">EUR</label>
            <input type="number" name="eur" id="eur">
        </div>
        <div class="gbr">
            <label for="gbr">GBR</label>
            <input type="number" name="gbr" id="gbr">
        </div>
        <button type="sumbit" class="submit-rates" name="submit-rates">Set Rates</button>
    </form>
    <br>
    <form method="post" name="exchange-currency">
        <div class="needed-currency">
            <label for="needed">Needed currency</label>
            <select name="needed" id="needed">
                <option value="usd">USD</option>
                <option value="eur">EUR</option>
                <option value="gbr">GBR</option>
                <option value="uan">UAN</option>
            </select>
        </div>
        <div class="base-currency">
            <label for="base">Base currency</label>
            <select name="base" id="base">
                <option value="usd">USD</option>
                <option value="eur">EUR</option>
                <option value="gbr">GBR</option>
                <option selected="selected" value="uan">UAN</option>
            </select>
        </div>
        <div class="converted-currency">
            <label for="amount">Amount:</label>
            <input type="number" id="amount" name="amount">
            <label for="calculated">Converted</label>
            <input type="number" id="calculated" name="calculated">
            <button type="sumbit" name="convert">Convert</button>
        </div>
    </form>

    <script src="script.js"></script>
</body>

</html>`

script.js:


        window.addEventListener("load", function () {
    
        console.log("php es una mierda");
    
        let rates = {};
    
        // document.querySelector(".submit-rates").addEventListener("click", function () {
            let xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    console.log(this.responseText);
                    rates = JSON.parse(this.response);
                }
            };
            xmlhttp.open("GET", "converter.php", true);
            xmlhttp.send();
        // })
    })

converter.php:


    <?php
    
    if (isset($_POST['submit-rates'])):
         $usdRate = (int)$_POST['usd'];
         $eurRate = (int)$_POST['eur'];
         $gbrRate = (int)$_POST['gbr'];
    
         // echo "$usdRate $eurRate $gbrRate";
    endif;
    
    $rates = [
         "usd" => $usdRate, 
         "eur" => $eurRate, 
         "gbr" => $gbrRate];
    
    echo json_encode($rates);
    file_put_contents("./rates.json", json_encode($rates));
    
    ?>

I have to do a currency converter where a user sets the rates, using JavaScript and PHP. I decided to transfer data through JSON, and it works like this:

the whole thing console logs: {"usd":null,"eur":null,"gbr":null} and when I press "Set Rates" button, nothing changes.

how can I transfer the data with rates properly?



Solution 1:[1]

  1. no estas usando json para usar json debes adicionar la libreria jquery
  2. you are not using Json, if you wanna use Json, you should add jquery library

html

<!-- change your button -->
    <button type="button" onclick="registroModificacion()">Convert</button>><
<!-- add at the end of yout page. you have to use jquery library -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" ></script>
    <script>
        function registroModificacion(){
            //get values of your form by id
            const needed = $('#needed').val();
            const usd= $('#usd').val();
            $.ajax({
              url:'paginaEn.php',
              type:"POST",
              data: {needed:needed,usd:usd},
              success:function(r){
               alert(r);
              },
            })
        }
    </script>

paginaEn.php

<?php
    $usd= $_POST['usd'];
    $needed= $_POST['needed'];
    echo $needed." ".$usd;
?>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 andres castellanos