I know this question has been asked a lot and this is going to get flagged as duplicate, but I need the code because I can't get my head around any of it.
I have a variable x in my js file. I want that in my php file. Here's the messed up code that I have:
index.js-
var x=5;
$.ajax({
type: 'POST',
url: 'form.php',
data: {'variable': x },
});
form.php-
<?php $myval = $_POST['x'];
echo $myval;?>
Also, do I need to connect with the server first or something for the ajax call? Thanks in advance.
You're adding this POST body
['variable' => 5]
Why are you then requesting $_POST['x'];?
The index x is undefined and will throw a notice/error.
Something useful you can do (during development only), when you're unsure what is accessible in you're PHP code is dumping the required variable:
<?php
var_dump($_POST);
?>
In Ajax data you have sent key:value. So in PHP file you can access it by $_POST['key'].
Here your key is variable and value is x which is 5
So you can access it by $_POST['variable']
Write it as below:-
<?php
$myval = $_POST['variable'];
echo $myval; // output will be 5
?>
Hope it will help you :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With