Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS variable to PHP

Tags:

javascript

php

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.

like image 882
Navya Nidhi Sharma Avatar asked May 05 '26 03:05

Navya Nidhi Sharma


2 Answers

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);
?>
like image 59
Gearloose Avatar answered May 07 '26 18:05

Gearloose


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 :)

like image 27
Ravi Avatar answered May 07 '26 16:05

Ravi