Reputation: 31
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.
Upvotes: 2
Views: 91
Reputation: 6539
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 :)
Upvotes: 4
Reputation: 47
This ajax call is like this form submit
<form action="form.php" method="POST">
<input type="text" name="variable" value="5">
<input type="submit" value="Submit">
</form>
Then in your form.php you will do:
<?php
myval = $_POST['variable'];
echo $myval; // output will be 5
?>
Upvotes: 1
Reputation: 61
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);
?>
Upvotes: 5