0

I am currently looking for a way on how can I access a javascript variable and use it in my php script (same page). I heard about using ajax, but I don't really know where to start, I have little experience when using ajax, could someone please help me start with this problem? The code below is just an example on what I am trying to do:

<script>
var fruit = "apple";

</script>

I am trying to get the value of the variable fruit for example using a php script

<?php
$fruit = code to get the value maybe....

?>

My example above must be wrong and I know ajax is the way to go, but could someone please help me on how to approach or start with it? I would appreciate it! Thanks!

paopao33
  • 107
  • 4
  • 13

1 Answers1

0

in the js you use ajax through jquery to send the vars to php

var fruit = "apple";
$.get('server.php',{fruit:fruit});

in server.php

$fruit = $_GET['fruit'];

of course opening server.php directly will cause an error, you have to run the javascript code in the browser, use the developer tools to inspect the request and the php file output.

Even better you can get back the server.php output in javascript like this:

var fruit = "apple";
$.get('server.php',{fruit:fruit})
   .done(function( data ) {
      alert( "Data Loaded: " + data );
   });
Oussama Gammoudi
  • 685
  • 7
  • 13