-2

Is it possible to pass a javascript variable to php code in the same file?

For example I did this, in my example.php:

JS

$.ajax({
       url: 'example.php',
       type: 'POST',
       data: {var: 12345},
       success: function(data) {
             console.log("success");
       }
});

PHP

$var = $_POST['var'];
echo $var;

But it doesn't work. Any solutions?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
Radec
  • 91
  • 1
  • 1
  • 3
  • 1
    _“But it doesn't work”_ - well what would you _expect_ this to do if it worked? Even if your PHP script makes such an output, you don’t do anything with the received output on the client after your AJAX request. So what exactly did you expect to happen? – misorude Oct 04 '18 at 13:12
  • Perhaps you should read https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming first of all, because the way you are asking makes me doubt a little bit whether you are aware of these basics yet. – misorude Oct 04 '18 at 13:13
  • Did you add jQuery librairie ? – executable Oct 04 '18 at 13:17
  • Yes @executable. – Radec Oct 04 '18 at 13:23
  • Other users marked your question for low quality and need for improvement. I re-worded/formatted your input to make it easier to read/understand. Please review my changes to ensure they reflect your intentions. But I think your question is still not answerable. **You** should [edit] your question now, to add missing details (see [mcve] ). Feel free to drop me a comment in case you have further questions or feedback for me. – GhostCat Oct 05 '18 at 07:06
  • The question is really unclear but I think [this](https://stackoverflow.com/questions/52645474/ajax-post-to-php-var-and-return/52645515#52645515) might be a possible duplicate. – Quentin Oct 05 '18 at 07:09

1 Answers1

0
$.ajax({
   url: 'example.php',
   type: 'POST',
   data: {var: 12345},
   success: function(data) {
         console.log("success");
   }
});

Your AJAX request expect a response (you assigned it to data variable). You should elaborate more the value returned by your PHP script, like console.log(data) to see what it is returning.

Your PHP file can't write it directly to your html file, because it is a server-side operation and your page is already loaded. I think you should add some request-type logic in you PHP too if you want to have HTML file rendering and Javascript AJAX requests both in the same file.

A solution could be to catch the AJAX[POST] request in PHP code and return some HTML or String values to attach in HTML like $(body).append(data);

Here you can learn more: https://www.w3schools.com/php/php_ajax_php.asp

Marco Dal Zovo
  • 369
  • 2
  • 17