Pass js variable to php using ajax on same page

this is my html code:

<form id="form" action="javascript:void(0)">
<input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font-size: 23px;font-weight: normal;color:white;margin-top:-3px;text-decoration: none;background-color: rgba(0, 0, 0, 0.53);'>	

this is my javascript code:

function showtemplate(temp)
type: “POST”,
url: ‘ajax.php’,
data: “section=”+temp ,
success: function(data)

this is my ajax.php file:

<?php $ajax=$_POST['section']; echo $ajax; ?>

The above html and javascript code is included in a file named slider.php. In my index file i have included this slider.php file and slider.php is inside slider folder. So basically index.php and slider.php are not inside the same folder.

Javascript code alerts the data properly. But in my php code (ajax.php file) the value of $_POST[‘section’] is empty. What is the problem with my code. I tried googling everything and tried a few codes but it still doesn’t work. Please help me out

that’s a bit of a contradicting statement. ajax.php should be a separate script only for use by ajax requests.

I want to retrieve the javascript variable in my ajax.php file. But it is echoing nothing. I googled a lot and i found the same code almost everywhere. what is the problem with my code.

I don’t know.

you have to debug it. start by opening the browser’s dev tools and monitor what your ajax call sends/receives. also check the Error Console.

if the JS code works as intended, check the PHP side. have a look at the error log, simulate requests, etc.

Yeah i have checked the error log file. But it gives no error. In my javascript code when i alert the data i.e
success: function(data)

It alerts the data properly. Now when i try to retrieve it in my ajax.php file it isn’t echoing anything. So i just wanna know whether I am doing it properly or not.

I think that your understanding of things might be backwards. Once the ajax request has occurred to ajax.php, the output of ajax.php is given back to the JavaScript program as the data variable. There’s no going back to PHP.

ok. But is there a way to use the js variable in php. Because my code is a mixture of php, javascript and ajax and html. How can i retrieve the js variable in a php variable

you can’t.

at most you can call a PHP script from JS that does something on the server (and of course you can feed it with input data) and do something with the response you receive from that script. but you cannot affect a PHP (include) script that has already run.

@Dormilich you said that we can call a php script from js and feed it with input data. Can u please give one example which does this

You provided your own example in OP.
There you call ajax.php with $.ajax with section variable as an input .

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.