How to pass javascript/jQuery variable to PHP using POST method
ajax, javascript, jquery, php, post
Solution
Here is the code that can be function within a file:
For PHP part, you should pass value to the function and call the function.
I guess you need return data to the client from the php function return. Then, for ajax part, you have to catch the return data.
<?
if(isset($_POST['width'])){
$width = $_POST['width'];
function mobileView($width){
if ($width < 950){
echo 'true';
} else{
echo 'false';
}
}
mobileView($width);
}else{
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
htmlWidth = $("html").width();
$.ajax({
type: "POST",
url: "mobileView.php",
data:{ width: htmlWidth },
success: function(data){
console.log(data);
}
})
</script>
<?
};
?>
Problem
This is really basic. All I want to do is measure the html width of a browser window, and pass that data to a PHP script so that I can adjust what information is passed to the site. I've got the HTML width part down. I'm just having trouble passing the Javascript/jQuery variable to the PHP script using AJAX. Here's the Javascript/jQuery. It is written in PHP so that I can use the `include()` function later. ``` echo '<script> htmlWidth = $("html").width(); $.ajax({ type: "POST", url: "mobileView.php", data:{ width: htmlWidth } }) </script>'; ``` And here's the PHP: ``` $width = $_POST['width']; function mobileView(){ if ($width < 950){ return true; } else{ return false; } } mobileView(); ```