abrad1212 abrad1212 - 5 months ago 24
jQuery Question

How do I pass PHP variables through jQuery AJAX

Okay so I'm trying to follow this tutorial but instead of storing it in a database I'm gonna store it somewhere else.

One problem though I have no clue how to append PHP variables with jQuery to the body!

Here is index.php

<html>

<head>
<title>Store Your Browser Resolution!</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/main.js"></script>
</head>

<body>
<button id="btn-POST">CLICK</button>
</body>




Here is Main.js

$(document).ready(function(){
$("#btn-POST").click(function(){
$.ajax({
type: 'POST',
url: '/index.php',
data: {
width : $(window).width(),
height : $(window).height(),
screen_width : screen.width,
screen_height: screen.height
},
success: function( data )
{
console.log('SUCCESS!');
$("body").append($('<?php $width = $_POST["width"]; $height = $_POST["height"]; $screen_width = $_POST["screen_width"]; $screen_height = $_POST["screen_height"]; ?>'));
$("body").delay(800).append($('<?php echo ?>'))
}
});
});
console.log('Test!');
});


Any help would be appreciated :)

-Alex

Answer

Once the user has loaded the HTML / PHP site from your server it's impossible to execute more PHP commands.

This is because PHP is server sided, the user requests the document, your server executes all php commands and give the user the resulting HTML document.

Adding PHP code via JavaScript is clientside, so it won't work.