0

I'm a novice in Javascript and Ajax, but with some help of the internet I got halfway there. But now I'm stuck.

I'm sending some HTML form data to a PHP script using Ajax. The PHP file should return two values. When I put console.log(data); in the success: function(data) block, I can see an array of the two values in Console.

But how can I now use these two values in two separate variables?

Btw, the Ajax call is in the main html file, but I would need these two variables in a functions.js file, where all my other Javascript lives.

EDIT:

The console says [80,120].

A snippet from the bottom of index.html

<script  src="assets/function.js"></script>

<script type="text/javascript">
    $('#calculate').click(function() {
        var val1 = $('#number').val();
    $.ajax({
        type: 'POST',
        url: 'calc.php',
        data: { number: val1 },
        success: function(data) {
            console.log(data); 
        }
    });
});     
</script>

calc.php

...some calculations which end in...
<?php
$Var1 = 80;
$Var2 = 120;
?>

function.js

...
var value1 = ??? //here I'd need the value of $Var1
var value2 = ??? //here I'd need the value of $Var1
...
further calculations
Holger
  • 11
  • 1
  • 8
  • Would be nice if you could add the output of the `console.log` to your question. – Guido Faecke May 17 '22 at 16:07
  • If `data` is an array with two values, then you'd access to values as elements of that array. It's not clear to me what the problem is. Can you provide a [mcve] which demonstrates what you're trying to do and what isn't working as expected? – David May 17 '22 at 16:07
  • Regarding the update... It's still not clear what the problem is. If `console.log(data)` produces `[80,120]` then `data` is an array with two numbers. `data[0]` has the value of `80` and `data[1]` has the value of `120`. Whatever you want to do with those values in that `success` function, go ahead and do it. Currently you're just logging the values to the console. What else do you want to do with them? What's stopping you from doing that? Your `functions.js` "code" suggests that you have two window-level variables. Is that the case? Why can't you set their values in `success`? – David May 17 '22 at 16:57
  • The problem is clearly my limited understanding of Javascript. I can log this array in Console and it shows the numbers I expect. But from there I'm stuck. There isn't a lot I can do with them in `success`, as all the calculations happen in `function.js`. But there console says: `data is not defined` when I try to use `data[0]` So my question might be: how to pass variables from one function to another? – Holger May 18 '22 at 09:32

0 Answers0